text:
#include <stdio.h>
//#include <unistd.h>

#include <utility>
#include <iostream>

#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>

#include <muduo/base/Logging.h>
#include <muduo/base/Thread.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>

#include <bfcp/client/base_client.h>

using namespace muduo;
using namespace muduo::net;
using namespace bfcp;

void controlFunc(EventLoop *loop);
void onClientStateChanged(BaseClient::State state);
void onReceivedResponse(BaseClient::Error error, bfcp_prim prim, void *data);

#define CHECK_CIN_RESULT(res) do {\
  if (!(res)) {\
  std::cin.clear(); \
  std::cin.ignore(); \
  break; \
  }\
} while (false)

int main(int argc, char* argv[])
{
  Logger::setLogLevel(Logger::kTRACE);
  LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();

  EventLoop loop;
  Thread thread(boost::bind(&controlFunc, &loop));
  thread.start();

  loop.loop();
  thread.join();
}

void printMenu()
{
  printf(
    "\n--------PARTICIPANT LIST-----------------------------\n"
    " ?      - Show the menu\n"
    " c      - Create the Participant\n"
    " h      - Destroy the Participant\n"
    " s      - Show the information of the conference\n"
    "BFCP Messages:\n"
    " f      - Hello\n"
    " r      - FloorRequest\n"
    " l      - FloorRelease\n"
    " o      - FloorRequestQuery\n"
    " u      - UserQuery\n"
    " e      - FloorQuery\n"
    " a      - ChairAction\n"
    " q      - quit\n"
    "------------------------------------------------------\n\n");
}

void resetClient(boost::shared_ptr<BaseClient> client)
{
  client = nullptr;
}

void controlFunc(EventLoop *loop)
{
  boost::shared_ptr<BaseClient> client;
  printMenu();
  char ch;
  while (std::cin >> ch)
  {
    switch (ch)
    {
      case '?':
        printMenu(); break;
      case 'c':
        {
          if (client)
          {
            printf("Error: A participant already exist\n");
            break;
          }
          printf("Enter the conferenceID of the conference:\n");
          uint32_t conferenceID;
          CHECK_CIN_RESULT(std::cin >> conferenceID);
          printf("Enter the userID of the participant:\n");
          uint16_t userID;
          CHECK_CIN_RESULT(std::cin >> userID);
          InetAddress serverAddr(AF_INET, "127.0.0.1", 7890);
          printf("connect to hostport:%s\n", serverAddr.toIpPort().c_str());
          client.reset(new BaseClient(loop, serverAddr, conferenceID, userID, 10.0));
          client->setStateChangedCallback(&onClientStateChanged);
          client->setResponseReceivedCallback(&onReceivedResponse);
          client->connect();
          printf("BFCP Participant created.\n");
        } break;
      case 'h':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          client->forceDisconnect();
          // client must destruct in event loop
          //loop->runInLoop(boost::bind(&boost::shared_ptr<BaseClient>::reset, client));
          loop->runInLoop(boost::bind(resetClient, client));
          client = nullptr;
          printf("BFCP participant destroyed.\n");
        } break;
      case 'f':
        if (!client)
        {
          printf("Error: No participant exist\n");
          break;
        }
        client->sendHello();
        break;

      case 'r':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          FloorRequestParam param;
          printf("Request for beneficiary user?: 0=false, 1=true\n");
          CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
          if (param.hasBeneficiaryID)
          {
            printf("Enter the BeneficiaryID of the new request:\n");
            CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
          }
          printf("Enter the priority for this request (0=lowest --> 4=highest):\n");
          int priority = 0;
          CHECK_CIN_RESULT(std::cin >> priority);
          param.priority = static_cast<bfcp_priority>(priority);
          printf("Enter the FloorID:\n");
          uint16_t floorID = 0;
          CHECK_CIN_RESULT(std::cin >> floorID);
          param.floorIDs.push_back(floorID);
          printf("Enter the rest floors count:\n");
          size_t restCount = 0;
          CHECK_CIN_RESULT(std::cin >> restCount);
          printf("Enter the rest floorIDs:\n");
          for (size_t i = 0; i < restCount; ++i)
          {
            CHECK_CIN_RESULT(std::cin >> floorID);
            param.floorIDs.push_back(floorID);
          }
          client->sendFloorRequest(param);
          printf("Message sent!\n");
        } break;

      case 'l':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          printf("Enter the FloorRequestID of the request you want to release:\n");
          uint16_t floorRequestID;
          CHECK_CIN_RESULT(std::cin >> floorRequestID);
          client->sendFloorRelease(floorRequestID);
          printf("Message send!\n");
        } break;

      case 'o':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          printf("Enter the FloorRequestID of the request you're interested in:\n");
          uint16_t floorRequestID = 0;
          CHECK_CIN_RESULT(std::cin >> floorRequestID);
          client->sendFloorRequestQuery(floorRequestID);
          printf("Message send!\n");
        } break;

      case 'u':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          UserQueryParam param;
          printf("Query the beneficiary user?: 0=false, 1=true\n");
          CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
          if (param.hasBeneficiaryID)
          {
            printf("Enter the BeneficiaryID if you want information about a specific user:\n");
            CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
          }
          client->sendUserQuery(param);
          printf("Message send!\n");
        } break;

      case 'e':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          bfcp_floor_id_list floorIDs;
          printf("Enter the floorID count:\n");
          size_t floorIDCount = 0;
          CHECK_CIN_RESULT(std::cin >> floorIDCount);
          printf("Enter the FloorIDs:\n");
          uint16_t floorID = 0;
          for (size_t i = 0; i < floorIDCount; ++i)
          {
            CHECK_CIN_RESULT(std::cin >> floorID);
            floorIDs.push_back(floorID);
          }
          client->sendFloorQuery(floorIDs);
          printf("Message send!\n");
        } break;

      case 'a':
        {
          if (!client)
          {
            printf("Error: No participant exist\n");
            break;
          }
          FloorRequestInfoParam param;
          printf("Enter the FloorRequestID:\n");
          CHECK_CIN_RESULT(std::cin >> param.floorRequestID);

          param.valueType |= AttrValueType::kHasOverallRequestStatus;
          param.oRS.floorRequestID = param.floorRequestID;
          param.oRS.hasRequestStatus = true;
          printf("What to do with this request? (2=Accept / 4=Deny / 7=Revoke):\n");
          int status;
          CHECK_CIN_RESULT(std::cin >> status);
          param.oRS.requestStatus.status = static_cast<bfcp_reqstat>(status);

          printf("Enter the desired position in queue for this request (0 if you are not interested in that):\n");
          int pos = 0;
          CHECK_CIN_RESULT(std::cin >> pos);
          param.oRS.requestStatus.qpos = static_cast<uint8_t>(pos);

          FloorRequestStatusParam floorStatus;
          printf("Enter the FloorID:\n");
          CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
          param.fRS.push_back(floorStatus);

          printf("Enter the rest floors count:\n");
          size_t restCount = 0;
          CHECK_CIN_RESULT(std::cin >> restCount);
          printf("Enter the rest floorIDs:\n");
          for (size_t i = 0; i < restCount; ++i)
          {
            CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
            param.fRS.push_back(floorStatus);
          }

          client->sendChairAction(param);
          printf("Message send!\n");
        } break;

      case 's':
        // TODO:
        printf("TODO:\n");
        break;

      case 'q':
        printf("Quit\n");
        if (client)
        {
          client->forceDisconnect();
          //loop->runInLoop(boost::bind(&boost::shared_ptr<BaseClient>::reset, client));
          loop->runInLoop(boost::bind(resetClient, client));
          client = nullptr;
        }
        loop->quit();
        return;

      default:
        printf("Invalid menu choice - try again\n");
        break;
    }
  }
}

void onClientStateChanged( BaseClient::State state )
{

}

void onReceivedResponse( BaseClient::Error error, bfcp_prim prim, void *data )
{

}


text:
#include <boost/program_options.hpp>
//#include <experimental/filesystem>
#include <boost/filesystem.hpp>
#include <iostream>
#include <string>
#include <regex>
#include <cstdlib>
#include "atomsciflow/parser/cif.h"
#include "atomsciflow/parser/xyz.h"
#include "atomsciflow/base/crystal.h"
#include "atomsciflow/utils.h"

// needs: libboost-dev, libboost-program-options-dev

namespace po = boost::program_options;

//namespace filesys = std::experimental::filesystem;  // --std=c++17 -lstdc++fs
namespace filesys = boost::filesystem;     // --std=c++11 -lboost_filesystem -lboost_system

// used to allow negative number parsed to boost cmd option
std::vector<po::option> ignore_numbers(std::vector<std::string>& args)
{
    // this function can help to alow negative number args but it probhibits positional args
    // however we do not need positional args. so it is ok.
    std::vector<po::option> result;
    int pos = 0;
    while(!args.empty()) {
        const auto& arg = args[0];
        double num;
        if(boost::conversion::try_lexical_convert(arg, num)) {
            result.push_back(po::option());
            po::option& opt = result.back();

            opt.position_key = pos++;
            opt.value.push_back(arg);
            opt.original_tokens.push_back(arg);

            args.erase(args.begin());
        } else {
            break;
        }
    }

    return result;
}

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

    po::options_description global("Global options");
    global.add_options()
        ("command", po::value<std::string>(), "command to execute")
        ("subargs", po::value<std::vector<std::string> >(), "Arguments for command")
        ("help, h", "print out help information");

    po::positional_options_description pos;
    pos.add("command", 1).add("subargs", -1);

    po::variables_map vm;

    po::parsed_options parsed = po::command_line_parser(argc, argv).
        options(global).
        positional(pos).
        allow_unregistered().
        run();

    po::store(parsed, vm);

    std::cout << "**********************************************************************" << std::endl;
    std::cout << "*                       skit.x utils runnig                          *" << std::endl;
    std::cout << "**********************************************************************" << std::endl;

    if (0 == vm.count("command")) { // or by vm.empty()
        std::cout << "You didn't specify any subcommand!\n";
        std::exit(1);
    }
    std::string cmd = vm["command"].as<std::string>();

    if (cmd == "convert") {
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> convert                                               " << std::endl;
        std::cout << "Run info:" << std::endl;

        // convert command has the following options:
        po::options_description opt_convert("convert options");
        opt_convert.add_options()
            ("input, i", po::value<std::string>()->required(), "input structure file")
            ("output, o", po::value<std::string>()->required(), "output structure file");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_convert).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_convert << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;
            //crystal.read_xyz_file(vm["input"].as<std::string>());
            //crystal.write_cif_file(vm["output"].as<std::string>());

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            std::cout << "input: " << input_file << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }

        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: convert finished!!!                                      " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;

    } else if (cmd == "supercell") {
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> supercell                                             " << std::endl;
        std::cout << "Run info:" << std::endl;

        // supercell command has the following options:
        po::options_description opt_supercell("supercell options");
        opt_supercell.add_options()
            ("input, i", po::value<std::string>()->required(), "input structure file")
            ("output, o", po::value<std::string>()->required(), "output structure file")
            ("n", po::value<std::vector<int> >()->multitoken(), "n to define the supercell")
            ("precision", po::value<double>()->default_value(1.0e-8), "precision for redefine lattice");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin())        ;
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_supercell).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_supercell << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();
            std::vector<int> n = vm["n"].as<std::vector<int>>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            //std::cout << "input file: " << input_file << std::endl;
            //std::cout << "output file: " << output_file << std::endl;

            //std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            // read structure file
            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            // build the supercell
            std::cout << "we are building the supercell from" << std::endl;
            std::cout << input_file << std::endl;
            std::cout << "to" << std::endl;
            std::cout << output_file << std::endl;
            std::cout << "by -> " << n[0] << "x" << n[1] << "x" << n[2] << std::endl;
            crystal.build_supercell(n);

            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end supercell cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: supercell finished!!!                                    " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;
    } else if (cmd == "redefine") {
        //
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> redefine                                              " << std::endl;
        std::cout << "Run info:" << std::endl;

        // redefine command has the following options:
        po::options_description opt_redefine("redefine options");
        opt_redefine.add_options()
            ("input, i", po::value<std::string>(), "input structure file")
            ("output, o", po::value<std::string>(), "output structure file")
            ("a", po::value<std::vector<int> >()->multitoken(), "three integer to define the new a vector")
            ("b", po::value<std::vector<int> >()->multitoken(), "three integer to define the new b vector")
            ("c", po::value<std::vector<int> >()->multitoken(), "three integer to define the new c vector")
            ("precision", po::value<double>()->default_value(1.0e-8), "precision for redefine lattice");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        //po::store(po::command_line_parser(opts).options(opt_redefine).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).run(), vm);
        po::store(po::command_line_parser(opts).options(opt_redefine).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_redefine << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        std::cout << "abc info" << std::endl;
        std::cout << "a: " << vm["a"].as<std::vector<int>>()[0] << " " << vm["a"].as<std::vector<int>>()[1] << " " << vm["a"].as<std::vector<int>>()[2] << std::endl;
        std::cout << "b: " << vm["b"].as<std::vector<int>>()[0] << " " << vm["b"].as<std::vector<int>>()[1] << " " << vm["b"].as<std::vector<int>>()[2] << std::endl;
        std::cout << "c: " << vm["c"].as<std::vector<int>>()[0] << " " << vm["c"].as<std::vector<int>>()[1] << " " << vm["c"].as<std::vector<int>>()[2] << std::endl;

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            std::cout << "input: " << input_file << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            // build the supercell
            std::vector<int> a = vm["a"].as<std::vector<int>>();
            std::vector<int> b = vm["b"].as<std::vector<int>>();
            std::vector<int> c = vm["c"].as<std::vector<int>>();

            redefine_lattice(&crystal, a, b, c, vm["precision"].as<double>());

            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end redefine lattice cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: redefine finished!!!                                     " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;
    } else if (cmd == "tube") {
        //
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> tube                                                  " << std::endl;
        std::cout << "Run info:" << std::endl;

        // redefine command has the following options:
        po::options_description opt_tube("nanotube options");
        opt_tube.add_options()
            ("input, i", po::value<std::string>(), "input structure file")
            ("output, o", po::value<std::string>(), "output structure file")
            ("axis", po::value<std::string>(), "build nanotube along an axis parallel to axis specified, can be: a, b or c")
            ("plane", po::value<int>(), "on which plane to add vacuum layer. 1: ab, 2: ac, 3: bc");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_tube).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_tube << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            std::cout << "input: " << input_file << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            // build the nanotube

            if (vm["plane"].as<int>() == 1) {
                crystal = build_nanotube_ab(&crystal, vm["axis"].as<std::string>());
            } else if (vm["plane"].as<int>() == 2) {
                crystal = build_nanotube_ac(&crystal, vm["axis"].as<std::string>());
            } else if (vm["plane"].as<int>() == 3) {
                crystal = build_nanotube_bc(&crystal, vm["axis"].as<std::string>());
            }

            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end supercell cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: tube finished!!!                                         " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;

    } else if (cmd == "merge") {
        //
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> merge                                                 " << std::endl;
        std::cout << "Run info:" << std::endl;

        // redefine command has the following options:
        po::options_description opt_merge("merge layers options");
        opt_merge.add_options()
            ("input, i", po::value<std::vector<std::string>>()->multitoken()->required(), "input structure file")
            ("output, o", po::value<std::string>()->required(), "output structure file")
            ("usecell", po::value<int>()->default_value(0), "use cell of structure 1 or 2, otherwise 0 (avearge) by default")
            ("thick", po::value<double>()->default_value(10), "thickness of the vacuum layer")
            ("distance", po::value<double>()->default_value(3.4), "distance between the layer, in unit of Angstromg, default is 3.4");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_merge).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_merge << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal1;
            atomsciflow::Crystal crystal2;
            atomsciflow::Crystal crystal;

            std::vector<std::string> input_files = vm["input"].as<std::vector<std::string>>();
            std::string output_file = vm["output"].as<std::string>();

            std::vector<filesys::path> in_paths;
            in_paths.push_back(filesys::path{input_files[0]});
            in_paths.push_back(filesys::path{input_files[1]});
            filesys::path out_path(output_file);

            std::cout << "input: " << input_files[0] << " " << input_files[1] << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_paths[0].extension().string() << std::endl;
            std::cout << "in_path(extension)->" << in_paths[1].extension().string() << std::endl;

            if (in_paths[0].has_extension() && in_paths[0].extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal1, input_files[0]);
            } else if (in_paths[0].has_extension() && in_paths[0].extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal1, input_files[0]);
            }

            if (in_paths[1].has_extension() && in_paths[1].extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal2, input_files[1]);
            } else if (in_paths[1].has_extension() && in_paths[1].extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal2, input_files[1]);
            }

            // merge the layers
            std::cout << "beginning to merge layers" << std::endl;
            crystal = merge_layers(&crystal1, &crystal2, vm["usecell"].as<int>(), vm["distance"].as<double>(), vm["thick"].as<double>());

            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end merge layers cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: merge finished!!!                                        " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;
    } else if (cmd == "cleave") {

        //
        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> cleave                                                " << std::endl;
        std::cout << "Run info:" << std::endl;

        // redefine command has the following options:
        po::options_description opt_cleave("cleave options");
        opt_cleave.add_options()
            ("input, i", po::value<std::string>(), "input structure file")
            ("output, o", po::value<std::string>(), "output structure file")
            ("direction", po::value<std::vector<int>>()->multitoken(), "directino of the surface plane to cleave")
            ("thick", po::value<double>()->default_value(10), "thickness of the vacuum layer")
            ("precision", po::value<double>()->default_value(1.0e-8), "a value that is large than 0 and infinitely close to 0 used to judge whether one atom is in another periodic of the redefined cell used in cleave surface");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_cleave).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_cleave << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            std::cout << "input: " << input_file << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            std::cout << "finish reading the structure file, begin to cleave the surface" << std::endl;

            // cleave surface
            cleave_surface(&crystal, vm["direction"].as<std::vector<int>>(), vm["thick"].as<double>(), vm["precision"].as<double>());

            std::cout << "finish cleaving the surface" << std::endl;
            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end cleave surface cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: cleave finished!!!                                       " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;

    } else if (cmd == "vacuum") {

        //
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub commands -> vacuum                                                " << std::endl;
        std::cout << "Run info:" << std::endl;

        // redefine command has the following options:
        po::options_description opt_vacuum("vacuum options");
        opt_vacuum.add_options()
            ("input, i", po::value<std::string>(), "input structure file")
            ("output, o", po::value<std::string>(), "output structure file")
            ("plane", po::value<int>(), "plane to add vacuum layer, 1: ab, 2: ac, 3: bc")
            ("thick", po::value<double>()->default_value(10), "thickness of the vacuum layer");
        //opts.add_options()
        //    ("input, i", po::value<std::string>(&input), "input structure file")
        //    ("output, o", po::value<std::string>(&output), "output structure file");
        // collect all the unrecognized options from the first pass. this will include the
        // (positional) command name so we need to erase that
        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
        opts.erase(opts.begin());
        //parse again...
        po::store(po::command_line_parser(opts).options(opt_vacuum).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);

        if (vm.count("help")) {
            std::cout << opt_vacuum << std::endl;
            std::exit(1);
        }
        po::notify(vm);

        if (vm.count("input") && vm.count("output")) {
            atomsciflow::Crystal crystal;

            std::string input_file = vm["input"].as<std::string>();
            std::string output_file = vm["output"].as<std::string>();

            filesys::path in_path(input_file);
            filesys::path out_path(output_file);

            std::cout << "input: " << input_file << std::endl;
            std::cout << "output: " << output_file << std::endl;

            // read structure file
            std::cout << "in_path(extension)->" << in_path.extension().string() << std::endl;

            if (in_path.has_extension() && in_path.extension().string() == ".cif") {
                atomsciflow::read_cif_file(&crystal, input_file);
            } else if (in_path.has_extension() && in_path.extension().string() == ".xyz") {
                atomsciflow::read_xyz_file(&crystal, input_file);
            }

            std::cout << "finish reading the structure file, begin to add vacuum layer" << std::endl;

            // add vacuum layer
            vacuum_layer(&crystal, vm["plane"].as<int>(), vm["thick"].as<double>());

            std::cout << "finish add vacuum layer" << std::endl;
            // write structure file

            if (out_path.has_extension() && out_path.extension().string() == ".cif") {
                atomsciflow::write_cif_file(&crystal, output_file);
            } else if (out_path.has_extension() && out_path.extension().string() == ".xyz") {
                atomsciflow::write_xyz_file(&crystal, output_file);
            }
        }
        // end supercell cmd
        std::cout << "----------------------------------------------------------------------" << std::endl;
        std::cout << "sub command: vacuum  finished!!!                                      " << std::endl;
        std::cout << "----------------------------------------------------------------------" << std::endl;

    } else {
        std::cout << "The specified subcommand is not defined!\n";
    }

    //
    return 0;
}

ext: cpp

max_stars_repo_name: DeqiTang/pymatflow

max_issues_repo_name: DeqiTang/pymatflow

max_forks_repo_name: DeqiTang/pymatflow


text:
/*
Copyright 2011-2013, 2015 Rogier van Dalen.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#ifndef RANGE_MEMBER_VIEW_HPP_INCLUDED
#define RANGE_MEMBER_VIEW_HPP_INCLUDED

#include <type_traits>

#include <boost/utility/enable_if.hpp>

#include <boost/mpl/or.hpp>
#include <boost/mpl/and.hpp>

#include "core.hpp"

#include "meta/vector.hpp"

#include "utility/returns.hpp"

#include "detail/meta_is_linear_subset.hpp"

namespace range {

/**
Extract something from a struct or a class.
The operator() takes a reference to a structure and returns this something.
There are three types of ways that this "something" can be extracted.

1. The value of a member variable.
For a struct "structure" with a member "int i", this looks like
    member_extractor <int structure::*, &structure::i>.
This works with any type that is implicitly convertible to structure &,
structure const &, or structure &&.
This will return the same type of reference to the member variable.

2. The return value of a nullary member function.
For a member function
    int get_int(),
this looks like
    member_extractor <int (structure::*)() [const], &structure::get_int>.
The member function must be correctly const-qualified.
The return value is the exact return value of the member function.

3. The return value of a unary free function that takes a reference to the
structure.
For a function
    int get_int (structure const &),
this looks like
    member_extractor <int (*) (structure const &), &get_int>.
The return value is the exact return value of the function.

Preferably, of course, this would have worked somehow without specifying the
type.
However, I do not think this is possible for compile-time values.
*/
template <typename Member, Member> struct member_extractor;

// Specialisation for a member variable.
template <typename Structure, typename Type, Type Structure::* member>
    struct member_extractor <Type Structure::*, member>
{
    Type & operator() (Structure & structure) const
    { return structure.*member; }

    Type const & operator() (Structure const & structure) const
    { return structure.*member; }

    Type && operator() (Structure && structure) const
    { return static_cast <Type &&> (structure.*member); }
};

// Specialisation for a member function.
template <typename Structure, typename ReturnType,
    ReturnType (Structure::*member_function) ()>
struct member_extractor <ReturnType (Structure::*)(), member_function> {
    ReturnType operator() (Structure & structure) const
    { return (structure.*member_function)(); }
};

template <typename Structure, typename ReturnType,
    ReturnType (Structure::*member_function) () const>
struct member_extractor <ReturnType (Structure::*)() const, member_function> {
    ReturnType operator() (Structure const & structure) const
    { return (structure.*member_function)(); }
};

// Specialisation for a free function.
template <typename Structure, typename ReturnType,
    ReturnType (* function) (Structure)>
struct member_extractor <ReturnType (*) (Structure), function> {
    typedef ReturnType value_type;

    ReturnType operator() (Structure structure) const
    { return (function) (std::forward <Structure> (structure)); }
};

namespace detail {
    /**
    Base class for member_view.
    Different views of the same member have the same instantiation of this
    class as a base.
    This makes conversion (such as in "drop") easy.
    */
    template <class Structure> class member_view_base {
        static_assert (std::is_reference <Structure>::value,
            "Structure must be an lvalue or rvalue reference.");
    public:
        member_view_base (Structure structure_)
        : structure_ (&structure_) {}

        Structure structure() const
        { return static_cast <Structure> (*structure_); }

    private:
        typename std::add_pointer <Structure>::type structure_;
    };
} // namespace detail

/**
Lightweight range that traverses a struct or class.
The range can be used from either "front" or "back" direction.

The Extractors is a meta-list of member_extractor<> (or similar) classes,
which each extract a specific member from a structure.

\a Structure must be a reference; it can be a lvalue reference, a const
reference, or an rvalue reference.
Extractors are passed the structure qualified in exactly that way, and are
free to do with this with they please.
*/
template <class Structure, class Extractors> class member_view
: public detail::member_view_base <Structure> {
    typedef detail::member_view_base <Structure> base;
    static std::size_t constexpr extractor_num = meta::size <Extractors>::value;

public:
    explicit member_view (Structure structure)
    : base (static_cast <Structure> (structure)) {}

    /**
    Generalised copy constructor.
    Extractors2 must be a superset of Extractors.
    */
    template <class Extractors2>
        member_view (member_view <Structure, Extractors2> const & that,
            typename boost::enable_if <
                detail::is_linear_subset <Extractors, Extractors2>>::type * = 0)
    : base (that) {}

    typedef Structure structure_type;
    typedef Extractors extractors_type;

private:
    friend class helper::member_access;

    auto empty (direction::front) const
    RETURNS (rime::bool_<extractor_num == 0>());

    auto size (direction::front) const
    RETURNS (rime::size_t <extractor_num>());

    // first.
    template <class Direction> struct first_extractor
    : meta::first <Direction, Extractors> {};

    template <class Direction> struct first_type
    : result_of <typename first_extractor <Direction>::type (Structure)> {};

    template <class Direction>
        typename boost::lazy_enable_if_c <
            (extractor_num != 0), first_type <Direction>>::type
        first (Direction) const
    { return typename first_extractor <Direction>::type() (this->structure()); }

    // drop.
    template <class Increment, class Direction> struct drop_result {
        typedef typename meta::drop <Direction, Increment, Extractors>::type
            new_extractors;
        typedef member_view <Structure, new_extractors> type;
    };

    template <class Direction, class Increment>
        typename boost::lazy_enable_if_c <
            (std::size_t (Increment::value) <= extractor_num),
            drop_result <Increment, Direction>>::type
    drop_constant (Increment const &, Direction const &) const
    { return typename drop_result <Increment, Direction>::type (*this); }
};

namespace member_view_operation {
    struct member_view_tag {};
} // namespace member_view_operation

template <class Structure, class Extractors>
    struct tag_of_qualified <member_view <Structure, Extractors>>
{ typedef member_view_operation::member_view_tag type; };

} // namespace range

#endif  // RANGE_MEMBER_VIEW_HPP_INCLUDED

ext: hpp

max_stars_repo_name: rogiervd/range

max_issues_repo_name: rogiervd/range

max_forks_repo_name: rogiervd/range


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DEINTERLEAVE_FIRST_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_DEINTERLEAVE_FIRST_HPP_INCLUDED

namespace boost { namespace simd
{

#if defined(DOXYGEN_ONLY)
  /*!
    @ingroup group-swar
    Function object implementing deinterleave_first capabilities

    Computes a vector from a combination of the two inputs.

    @par Semantic:

    For every parameters of type T
    @code
    T r = deinterleave_first(x,y);
    @endcode

    is equivalent to :

    @code
    r = [ x[0] x[2] ... x[n/2] y[0] y[2] ... y[n/2] ]
    @endcode

    with <tt> n = cardinal_of<T>::value </tt>

  **/
  Value deinterleave_first(Value const& v0, Value const& v1);
#endif
} }

#include <boost/simd/function/simd/deinterleave_first.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
// Boost.Geometry

// Copyright (c) 2021, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGY_SPHERICAL_ENVELOPE_BOXES_HPP
#define BOOST_GEOMETRY_STRATEGY_SPHERICAL_ENVELOPE_BOXES_HPP

#include <vector>

#include <boost/geometry/algorithms/detail/envelope/initialize.hpp>
#include <boost/geometry/algorithms/detail/envelope/range_of_boxes.hpp>

namespace boost { namespace geometry
{

namespace strategy { namespace envelope
{

class spherical_boxes
{
public:
    template <typename Box>
    class state
    {
        friend spherical_boxes;

        std::vector<Box> m_boxes;
    };

    template <typename Box>
    static void apply(state<Box> & st, Box const& box)
    {
        st.m_boxes.push_back(box);
    }

    template <typename Box>
    static void result(state<Box> const& st, Box & box)
    {
        if (! st.m_boxes.empty())
        {
            geometry::detail::envelope::envelope_range_of_boxes::apply(st.m_boxes, box);
        }
        else
        {
            geometry::detail::envelope::initialize<Box, 0, dimension<Box>::value>::apply(box);
        }
    }
};

}} // namespace strategy::envelope

}} //namepsace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGY_SPHERICAL_ENVELOPE_BOXES_HPP


text:
/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <iostream>
#include <new>
#include <sysexits.h>

#include <boost/program_options/errors.hpp>
#include <sdd/order/order_error.hh>

#include "conf/fill_configuration.hh"
#include "mc/mc.hh"
#include "support/parsers/parse_pn.hh"
#include "support/parsers/parse_properties.hh"
#include "support/parsers/parse_error.hh"
#include "support/util/paths.hh"

/*------------------------------------------------------------------------------------------------*/

int
main(int argc, const char** argv)
{
  using namespace pnmc;

  try
  {
    if (const auto conf = conf::fill_configuration(argc, argv))
    {
      const auto net_ptr = parsers::parse(conf->pn_input);
      const auto properties = parsers::parse(conf->properties_input);
      mc::mc{*conf}(*net_ptr, properties);
    }
    return EX_OK;
  }
  catch (const boost::program_options::error& e)
  {
    std::cerr << e.what() << '\n';
    return EX_USAGE;
  }
  catch (const parsers::parse_error& e)
  {
    std::cerr << "Error when parsing input:\n";
    std::cerr << e.what() << '\n';
    return EX_DATAERR;
  }
  catch (const sdd::order_error& e)
  {
    std::cerr << "Order error:\n";
    std::cerr << e.what() << '\n';
    return EX_DATAERR;
  }
  catch (const std::runtime_error& e)
  {
    std::cerr << "Error:\n";
    std::cerr << e.what() << '\n';
    return EX_DATAERR;
  }
  catch (const std::bad_alloc&)
  {
    std::cerr << "Can't allocate memory\n";
    return EX_OSERR;
  }
  catch (std::exception& e)
  {
    std::cerr << "Error unknown. Please report the following to alexandre.hamez+pnmc@gmail.com.\n";
    std::cerr << e.what() << '\n';
    return EX_SOFTWARE;
  }
}

/*------------------------------------------------------------------------------------------------*/

ext: cc

max_stars_repo_name: ahamez/pnmc

max_issues_repo_name: ahamez/pnmc

max_forks_repo_name: ahamez/pnmc


text:
/*
 *  divide_by_inplace_test.cpp
 *  MTL
 *
 *  Created by Hui Li (huil@Princeton.EDU)
 *
 */

#include <iostream>
#include <cmath>
#include <complex>
#include <boost/numeric/mtl/concept/collection.hpp>
#include <boost/numeric/mtl/matrix/compressed2D.hpp>
#include <boost/numeric/mtl/matrix/dense2D.hpp>
#include <boost/numeric/mtl/matrix/laplacian_setup.hpp>
#include <boost/numeric/mtl/operation/print.hpp>
#include <boost/numeric/mtl/operation/operators.hpp>
#include <boost/numeric/mtl/operation/divide_by_inplace.hpp>

using namespace std;

template <typename MatrixA, typename MatrixB>
void test(MatrixA& a, MatrixB& b, unsigned dim1, unsigned dim2, const char* name)
{
    unsigned size= dim1 * dim2;
    MTL_THROW_IF(size == 0, mtl::runtime_error("Matrix size must be larger than 0 to make the test meaningful."));

    const unsigned max_print_size= 25;
    cout << "\n" << name << "\n";
    laplacian_setup(a, dim1, dim2);
    laplacian_setup(b, dim1, dim2);

    // right_scale_inplace(a, 2.0);
    a*= 2.0;
    if (size <= max_print_size)
		cout << "A= \n\n" << a << "\n";

    typename mtl::Collection<MatrixA>::value_type eight(8.0);
    MTL_THROW_IF(a[0][0] != eight, mtl::runtime_error("Scaling with scalar wrong"));

    a /= 2.0; // divide_by_inplace(a, 2.0);
    a*= b;   // right_scale_inplace(a, b);

    if (size <= max_print_size)
		cout << "A= \n\n" << a << "B= \n\n" << b << "\n";

    // Check for stencil below in the middle of the matrix
    //        1
    //     2 -8  2
    //  1 -8 20 -8  1
    //     2 -8  2
    //        1
    if (dim1 == 5 && dim2 == 5) {
	typename mtl::Collection<MatrixA>::value_type twenty(20.0), two(2.0), one(1.0),
	                                              zero(0.0), minus_eight(-8.0);
	MTL_THROW_IF(a[12][12] != twenty, mtl::runtime_error("wrong diagonal"));
	MTL_THROW_IF(a[12][13] != minus_eight, mtl::runtime_error("wrong east neighbor"));
	MTL_THROW_IF(a[12][14] != one, mtl::runtime_error("wrong east east neighbor"));
	MTL_THROW_IF(a[12][15] != zero, mtl::runtime_error("wrong zero-element"));
	MTL_THROW_IF(a[12][17] != minus_eight, mtl::runtime_error("wrong south neighbor"));
	MTL_THROW_IF(a[12][18] != two, mtl::runtime_error("wrong south east neighbor"));
	MTL_THROW_IF(a[12][22] != one, mtl::runtime_error("wrong south south neighbor"));
    }
}

int main(int argc, char* argv[])
{
    using namespace mtl;
    unsigned dim1= 5, dim2= 5;

    if (argc > 2) {dim1= atoi(argv[1]);dim2= atoi(argv[2]);}
    unsigned size= dim1 * dim2;

    compressed2D<double>                                 cr(size, size);
    compressed2D<double, mat::parameters<col_major> > cc(size, size);

    dense2D<double>                                      dr(size, size);
    dense2D<double, mat::parameters<col_major> >      dc(size, size);

    test(cr, dr, dim1, dim2, "Row-major sparse scaled with row-major dense");
    test(cr, dc, dim1, dim2, "Row-major sparse scaled with column-major dense");
    test(cc, dr, dim1, dim2, "Column-major sparse scaled with row-major dense");
    test(cc, dc, dim1, dim2, "Column-major sparse scaled with column-major dense");

    test(dr, cr, dim1, dim2, "Row-major dense scaled with row-major sparse");
    test(dr, cc, dim1, dim2, "Row-major dense scaled with column-major sparse");
    test(dc, cr, dim1, dim2, "Column-major dense scaled with row-major sparse");
    test(dc, cc, dim1, dim2, "Column-major dense scaled with column-major sparse");

    return 0;
}


text:
/*
 *      Copyright (C) 2005-2013 Team XBMC
 *      http://xbmc.org
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with XBMC; see the file COPYING.  If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */
#include "system.h"

#define WL_EGL_PLATFORM

#include <string>
#include <vector>

#include <boost/bind.hpp>

#include <gtest/gtest.h>

#include <wayland-client.h>
#include <wayland-client-protocol.h>

#if defined(HAVE_WAYLAND_XBMC_PROTO)
#include "xbmc_wayland_test_client_protocol.h"
#endif

#include "windowing/egl/wayland/Display.h"
#include "windowing/egl/wayland/Registry.h"
#include "windowing/egl/wayland/Surface.h"
#include "windowing/egl/EGLNativeTypeWayland.h"

#include "TmpEnv.h"
#include "WestonTest.h"
#include "XBMCWayland.h"

using ::testing::Values;
using ::testing::WithParamInterface;

namespace xt = xbmc::test;
namespace xw = xbmc::wayland;
namespace xtw = xbmc::test::wayland;

class EGLNativeTypeWaylandWestonTest :
  public WestonTest
{
protected:

  CEGLNativeTypeWayland m_nativeType;
};

TEST_F(EGLNativeTypeWaylandWestonTest, TestCheckCompatibilityWithEnvSet)
{
  TmpEnv env("WAYLAND_DISPLAY", TempSocketName().c_str());
  EXPECT_TRUE(m_nativeType.CheckCompatibility());
}

TEST_F(EGLNativeTypeWaylandWestonTest, TestCheckCompatibilityWithEnvNotSet)
{
  EXPECT_FALSE(m_nativeType.CheckCompatibility());
}

class CompatibleEGLNativeTypeWaylandWestonTest :
  public EGLNativeTypeWaylandWestonTest
{
public:

  CompatibleEGLNativeTypeWaylandWestonTest();
  virtual void SetUp();

private:

  TmpEnv m_waylandDisplayEnv;
};

CompatibleEGLNativeTypeWaylandWestonTest::CompatibleEGLNativeTypeWaylandWestonTest() :
  m_waylandDisplayEnv("WAYLAND_DISPLAY",
                      TempSocketName().c_str())
{
}

void
CompatibleEGLNativeTypeWaylandWestonTest::SetUp()
{
  WestonTest::SetUp();
  ASSERT_TRUE(m_nativeType.CheckCompatibility());
}

TEST_F(CompatibleEGLNativeTypeWaylandWestonTest, TestConnection)
{
  EXPECT_TRUE(m_nativeType.CreateNativeDisplay());
}

class ConnectedEGLNativeTypeWaylandWestonTest :
  public CompatibleEGLNativeTypeWaylandWestonTest
{
public:

  ConnectedEGLNativeTypeWaylandWestonTest();
  ~ConnectedEGLNativeTypeWaylandWestonTest();
  virtual void SetUp();

protected:

  xw::Display *m_display;
  struct wl_surface *m_mostRecentSurface;

private:

  void Global(struct wl_registry *, uint32_t, const char *, uint32_t);
  void DisplayAvailable(xw::Display &display);
  void SurfaceCreated(xw::Surface &surface);
};

ConnectedEGLNativeTypeWaylandWestonTest::ConnectedEGLNativeTypeWaylandWestonTest()
{
  xw::WaylandDisplayListener &displayListener(xw::WaylandDisplayListener::GetInstance());
  displayListener.SetHandler(boost::bind(&ConnectedEGLNativeTypeWaylandWestonTest::DisplayAvailable,
                                         this, _1));

  xw::WaylandSurfaceListener &surfaceListener(xw::WaylandSurfaceListener::GetInstance());
  surfaceListener.SetHandler(boost::bind(&ConnectedEGLNativeTypeWaylandWestonTest::SurfaceCreated,
                                         this, _1));
}

ConnectedEGLNativeTypeWaylandWestonTest::~ConnectedEGLNativeTypeWaylandWestonTest()
{
  xw::WaylandDisplayListener &displayListener(xw::WaylandDisplayListener::GetInstance());
  displayListener.SetHandler(xw::WaylandDisplayListener::Handler());

  xw::WaylandSurfaceListener &surfaceListener(xw::WaylandSurfaceListener::GetInstance());
  surfaceListener.SetHandler(xw::WaylandSurfaceListener::Handler());
}

void
ConnectedEGLNativeTypeWaylandWestonTest::SetUp()
{
  CompatibleEGLNativeTypeWaylandWestonTest::SetUp();
  ASSERT_TRUE(m_nativeType.CreateNativeDisplay());
}

void
ConnectedEGLNativeTypeWaylandWestonTest::DisplayAvailable(xw::Display &display)
{
  m_display = &display;
}

void
ConnectedEGLNativeTypeWaylandWestonTest::SurfaceCreated(xw::Surface &surface)
{
  m_mostRecentSurface = surface.GetWlSurface();
}

TEST_F(ConnectedEGLNativeTypeWaylandWestonTest, CreateNativeWindowSuccess)
{
  EXPECT_TRUE(m_nativeType.CreateNativeWindow());
}

TEST_F(ConnectedEGLNativeTypeWaylandWestonTest, ProbeResolutionsSuccess)
{
  std::vector<RESOLUTION_INFO> info;
  EXPECT_TRUE(m_nativeType.ProbeResolutions(info));
}

TEST_F(ConnectedEGLNativeTypeWaylandWestonTest, PreferredResolutionSuccess)
{
  RESOLUTION_INFO info;
  EXPECT_TRUE(m_nativeType.GetPreferredResolution(&info));
}

TEST_F(ConnectedEGLNativeTypeWaylandWestonTest, CurrentNativeSuccess)
{
  RESOLUTION_INFO info;
  EXPECT_TRUE(m_nativeType.GetNativeResolution(&info));
}

TEST_F(ConnectedEGLNativeTypeWaylandWestonTest, GetMostRecentSurface)
{
  m_nativeType.CreateNativeWindow();
  EXPECT_TRUE(m_mostRecentSurface != NULL);
}

#if defined(HAVE_WAYLAND_XBMC_PROTO)

class AssistedEGLNativeTypeWaylandTest :
  public ConnectedEGLNativeTypeWaylandWestonTest
{
protected:

  AssistedEGLNativeTypeWaylandTest();
  ~AssistedEGLNativeTypeWaylandTest();

  virtual void SetUp();

  void Global(struct wl_registry *registry,
              uint32_t name,
              const char *interface,
              uint32_t version);

  boost::scoped_ptr<xtw::XBMCWayland> m_xbmcWayland;
};

AssistedEGLNativeTypeWaylandTest::AssistedEGLNativeTypeWaylandTest()
{
  xw::ExtraWaylandGlobals &extra(xw::ExtraWaylandGlobals::GetInstance());
  extra.SetHandler(boost::bind(&AssistedEGLNativeTypeWaylandTest::Global,
                               this, _1, _2, _3, _4));
}

AssistedEGLNativeTypeWaylandTest::~AssistedEGLNativeTypeWaylandTest()
{
  xw::ExtraWaylandGlobals &extra(xw::ExtraWaylandGlobals::GetInstance());
  extra.SetHandler(xw::ExtraWaylandGlobals::GlobalHandler());
}

void
AssistedEGLNativeTypeWaylandTest::SetUp()
{
  ConnectedEGLNativeTypeWaylandWestonTest::SetUp();
  ASSERT_TRUE(m_xbmcWayland.get());
}

void
AssistedEGLNativeTypeWaylandTest::Global(struct wl_registry *registry,
                                         uint32_t name,
                                         const char *interface,
                                         uint32_t version)
{
  if (std::string(interface) == "xbmc_wayland")
    m_xbmcWayland.reset(new xtw::XBMCWayland(static_cast<xbmc_wayland *>(wl_registry_bind(registry,
                                                                                name,
                                                                                &xbmc_wayland_interface,
                                                                                version))));
}

TEST_F(AssistedEGLNativeTypeWaylandTest, TestGotXBMCWayland)
{
  EXPECT_TRUE(m_xbmcWayland.get() != NULL);
}

TEST_F(AssistedEGLNativeTypeWaylandTest, AdditionalResolutions)
{
  m_xbmcWayland->AddMode(2, 2, 2, static_cast<enum wl_output_mode>(0));
  std::vector<RESOLUTION_INFO> resolutions;
  m_nativeType.ProbeResolutions(resolutions);
  EXPECT_TRUE(resolutions.size() == 2);
}

TEST_F(AssistedEGLNativeTypeWaylandTest, PreferredResolutionChange)
{
  m_xbmcWayland->AddMode(2, 2, 2, static_cast<enum wl_output_mode>(WL_OUTPUT_MODE_PREFERRED));
  RESOLUTION_INFO res;
  m_nativeType.GetPreferredResolution(&res);
  EXPECT_EQ(res.iWidth, 2);
  EXPECT_EQ(res.iHeight, 2);
}

TEST_F(AssistedEGLNativeTypeWaylandTest, CurrentResolutionChange)
{
  m_xbmcWayland->AddMode(2, 2, 2, static_cast<enum wl_output_mode>(WL_OUTPUT_MODE_CURRENT));
  RESOLUTION_INFO res;
  m_nativeType.GetNativeResolution(&res);
  EXPECT_EQ(res.iWidth, 2);
  EXPECT_EQ(res.iHeight, 2);
}

#endif

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
// ignore warnings in this file
#include "libtorrent/aux_/disable_warnings_push.hpp"

#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/ed25519.hpp"

#ifndef ED25519_NO_SEED

#if TORRENT_USE_CRYPTOGRAPHIC_BUFFER
#include <robuffer.h>
#include <wrl/client.h>
using namespace Windows::Security::Cryptography;
using namespace Windows::Storage::Streams;
using namespace Microsoft::WRL;
#elif defined _WIN32
#include <windows.h>
#include <wincrypt.h>
#else
#include <stdio.h>
#endif

void ed25519_create_seed(unsigned char *seed) {
#if TORRENT_USE_CRYPTOGRAPHIC_BUFFER
    IBuffer^ seedBuffer = CryptographicBuffer::GenerateRandom(32);
    ComPtr<IBufferByteAccess> bufferByteAccess;
    reinterpret_cast<IInspectable*>(seedBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess));
    bufferByteAccess->Buffer(&seed);
#elif defined _WIN32
    HCRYPTPROV prov;

    if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))  {
        throw boost::system::system_error(boost::system::error_code(GetLastError()
            , boost::system::system_category()));
    }

    if (!CryptGenRandom(prov, 32, seed))  {
        CryptReleaseContext(prov, 0);
        throw boost::system::system_error(boost::system::error_code(GetLastError()
            , boost::system::system_category()));
    }

    CryptReleaseContext(prov, 0);
#else
    FILE *f = fopen("/dev/urandom", "rb");

    if (f == NULL) {
        throw boost::system::system_error(boost::system::error_code(errno, boost::system::system_category()));
    }

    int read = fread(seed, 1, 32, f);
    if (read != 32) {
        fclose(f);
        throw boost::system::system_error(boost::system::error_code(errno, boost::system::system_category()));
    }

    fclose(f);
#endif
}

#endif


text:
/************************************************************************
*	DICOMLIB
*	Copyright 2003 Sunnybrook and Women's College Health Science Center
*	Implemented by Trevor Morgan  (morgan@sten.sunnybrook.utoronto.ca)
*
*	See LICENSE.txt for copyright and licensing info.
*************************************************************************/
#include <iostream>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

#include <boost/tokenizer.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/date_parsing.hpp>

#include "DataSet.hpp"
#include "Types.hpp"
#include "Decoder.hpp"
#include "VR.hpp"
#include "Exceptions.hpp"
#include "DataDictionary.hpp"
#include "ValueToStream.hpp"

#include "Dumper.hpp"

using namespace std;

namespace dicom{

	struct Decoder
	{
		void Decode();
        bool DecodeElement();

		Decoder(Buffer& buffer,DataSet& ds,TS ts):buffer_(buffer),dataset_(ds),ts_(ts){}

		//!see 5/7.5.2
		struct EndOfSequence{};
	private:

		void DecodeVRAndLength(Tag tag, VR& vr, UINT32& length);

		Buffer& buffer_;
		DataSet& dataset_;
		TS ts_;

		void DecodeSequence(Tag tag, UINT32  length);

		/*!
			Extract one element onto dataset.
		*/
		template <VR vr>
		void GetElementValue(Tag tag)
		{
			typename TypeFromVR<vr>::Type data;

			buffer_>>data;

			//the 'template' keyword in the following line is technically redundant
			//but works round a known bug in gcc.
			//See http://gcc.gnu.org/cgi-bin/gnatsweb.pl?cmd=view%20audit-trail&database=gcc&pr=9510
			dataset_.template Put<vr>(tag,data);

		}

		/*!
			Only use previous function directly if we're sure that multiplicity is 1.
			(ie. if VR is one of SQ,OB,OW,or UN).  Otherwise use this function, which
			takes multiplicity into account.
		*/
		template <VR vr>
		void GetElementValue(Tag tag, size_t length)
		{
			StaticMultiplicityCheck<vr>();
			typedef typename TypeFromVR<vr>::Type DataType;

			Buffer::iterator end = buffer_.position()+length;
			while(buffer_.position()!=end)
				GetElementValue<vr>(tag);
		}

		/*!
			slightly different than above, as string multiplicity is handled differently than
			other types, using a backslash as a seperator.
		*/

		template <VR vr>
		void DecodeString(Tag tag, size_t length)
		{
			BOOST_STATIC_ASSERT((boost::is_same<std::string,typename TypeFromVR<vr>::Type>::value));

			string s(length,' ');
			buffer_>>s;

			StripTrailingWhitespace(s);

			/*
				Technically speaking, we shouldn't have to do this, but there seem to be
				many people producing images with null characters (0x00) in strings.
			*/
			StripTrailingNull(s);

			//	parse multiplicity using boost::tokenizer

			typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
			boost::char_separator<char> sep("\\","",boost::keep_empty_tokens);//strings are seperated by backslashes;
			tokenizer tokens(s, sep);

			for (tokenizer::iterator tok_iter = tokens.begin();tok_iter != tokens.end(); ++tok_iter)
				dataset_.template Put<vr>(tag,*tok_iter);
		}

		void DecodeUID(Tag tag, size_t length)
		{
			string s(length, ' ');
			buffer_ >> s;
			StripTrailingNull(s);

			/*
				We shouldn't have to do this, but some people are producing UIDS
				with trailing whitespace instead of NULLs, so we'll be lenient!
			*/
			StripTrailingWhitespace(s);

			typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
			boost::char_separator<char> sep("\\","",boost::keep_empty_tokens);//UIDS are seperated by backslashes;
			tokenizer tokens(s, sep);

			for (tokenizer::iterator tok_iter = tokens.begin();tok_iter != tokens.end(); ++tok_iter)
				dataset_.template Put<VR_UI>(tag,UID(*tok_iter));
		}

		void DecodeOB(Tag tag, size_t length)
		{
			if(length == UNDEFINED_LENGTH)
			{
				Enforce(TAG_PIXEL_DATA==tag,"only pixel data can be encoded");
				/*
					this probably means we're decoding encapsulated compressed
					pixel data, see Part 5, Annex A.4.
					-Transfer syntax should be one of the JPEG transfer syntaxes,
					-tag should be 'Pixel Data'
					-Data is encapsulated as shown in Part5, Table A.4-2

					I think we could handle this by treating the fragments as multiple values
					for this tag.  We could throw away the offset table, sacrificing potential
					speed gains for simplicity, but this might upset clients that expect
					it to be persisted?
				*/
				Enforce(ts_.isEncoded(),"Undefined value length on non-encoded transfer syntax.");

				//extract offset table, then pull out multiple elements until we hit a Sequence Delimiter Item
				Tag offset_table_tag;
				buffer_ >> offset_table_tag;
				Enforce(TAG_ITEM==offset_table_tag,"Offset table must be defined in encoded data");
				UINT32 length;
				buffer_ >> length;
				buffer_.Increment(length);//we ignore the offset table...

				for(;;)
				{
					Tag tag;
					UINT32 length;
					buffer_ >> tag;
					buffer_ >> length;
					if(TAG_SEQ_DELIM_ITEM==tag)
						break;
					Enforce(TAG_ITEM==tag,"Tag must be sequence item");
					TypeFromVR<VR_OB>::Type data(length,0);
					buffer_>>data;
					dataset_.Put<VR_OB>(TAG_PIXEL_DATA,data);
				}
			}
			else
			{
				TypeFromVR<VR_OB>::Type data(length,0);
				buffer_>>data;
				dataset_.Put<VR_OB>(tag,data);
			}
		}

	};

	//!DICOM messages need to have even byte length.(Part 5 section 7.1)
	void CheckEven(int ByteLength)throw (exception)
	{
		if(ByteLength & 1)
			throw dicom::exception("Byte length not even.");
	}

	void Decoder::DecodeVRAndLength(Tag tag, VR& vr, UINT32& length)
	{
		if(ts_.isExplicitVR())		//then get VR from stream
		{
			UINT16 w;
			buffer_ >> w;

			vr=VR(w);

			if (vr == VR_UN || vr == VR_SQ || vr == VR_OW || vr == VR_OB || vr == VR_UT)//see Part5 / 7.1.2
			{
				buffer_ >> w;		//	2 bytes unused
				buffer_>>length;	//4 bytes of length info
			}
			else
			{
				buffer_>>w;			//only 2 bytes of length info
				length = w;
			}
		}
		else						//VR is implicit, look up in data dictionary
		{
			vr=GetVR(tag);		//look up in data dictionary.
			buffer_ >> length;		//4 bytes of length info.
		}
	}

	//TAG_NULL not handled?
	/*!
		This is described in Part 5, section 7.1
	*/
    bool Decoder::DecodeElement()
	{
		Tag tag;
		buffer_ >> tag;

		if(tag==TAG_ITEM_DELIM_ITEM)
		{
			UINT32 dummy_length;
			buffer_>> dummy_length;		//deliminator item always has length 0x00000000;

            return false;
            //throw new EndOfSequence();	//ie jump to end of loop in Decoder::Decode()
									//This is a bit of a hack, not an optimal approach to handling
									//this kind of situation, as it's not really 'unexpected'.
		}

		VR vr;
		UINT32 length;

		DecodeVRAndLength(tag,vr,length);

		if(tag==TAG_NULL)
		{
			cout<< "null tag, length=" << length << endl;
			//what am I supposed to do here?(I think this has something to do with group length, which we're ignoring)
			//I think this gets sent at the beginning of a DICOM message.  TODO
		}

		if (vr == VR_SQ || (vr==VR_UN && length == UNDEFINED_LENGTH))//See Part 5, section 6.2.2, Notes 4
		//if (vr == VR_SQ)//is this correct?
        {
            DecodeSequence(tag,length);
            return true;
		}

        if(UNDEFINED_LENGTH!=length){
            CheckEven(length);
        }

		if(TAG_DATA_SET_PADDING==tag)
        {//throw away padding - we don't maintain it.
			vector<unsigned char> dummy(length);
            buffer_>>dummy;
            return true;
		}

		/*
			use the 'switch' statement to explicitly instantiate instances
			of GetElementValue templated on required VR.
		*/
		/*
			Now we read the relevant data from the byte stream, transfrom it
			to the correct C++ type and push it onto the data set.
		*/

		/*
			Part5, Annex A actually says we have to do some magic on a bunch of the
			OB/OW tags, depending on the transfer syntax, but currently we're ignoring
			that, and letting the end user sort it out.
		*/

		switch(vr)
		{

		case VR_AT://attribute tag??
        {	 GetElementValue<VR_AT>(tag,length); return true;}
		case VR_US://Unsigned Short
        {	 GetElementValue<VR_US>(tag,length); return true;}
		case VR_SS://signed short
        {	 GetElementValue<VR_SS>(tag,length); return true;}
		case VR_OB://other byte string
        {	 DecodeOB(tag,length); return true;}
		case VR_OW://other word string
			{
				TypeFromVR<VR_OW>::Type data((length>>1),0);// divide length by 2 because this is an array of
															// two-byte characters, and 'length' is the number
															// of bytes.
				buffer_>>data;
				dataset_.Put<VR_OW>(tag,data);
			}
			break;
		case VR_UL://unsigned long
        {	GetElementValue<VR_UL>(tag,length); return true;}
		case VR_SL://signed long
        {	GetElementValue<VR_SL>(tag,length); return true;}
		case VR_FL://float
        {	GetElementValue<VR_FL>(tag,length); return true;}
		case VR_FD://double
        {	GetElementValue<VR_FD>(tag,length); return true;}
		case VR_UI://unique identifier.
        {	DecodeUID(tag,length); return true;}
		case VR_DA://date, 8 bytes fixed date format.
			{//Multiplicity!!!
				/*if(length!=8)
					throw DecoderError("Date must be 8 bytes long.");*/
				string s(length,' ');
				buffer_>>s;

				StripTrailingWhitespace(s);

				//	parse multiplicity using boost::tokenizer

				typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
				boost::char_separator<char> sep("\\","",boost::keep_empty_tokens);//strings are seperated by backslashes;
				tokenizer tokens(s, sep);

				for (tokenizer::iterator tok_iter = tokens.begin();tok_iter != tokens.end(); ++tok_iter)
				{
					try
					{
						boost::gregorian::date d(boost::gregorian::from_undelimited_string(*tok_iter));
						dataset_.template Put<VR_DA>(tag,d);
					}
					catch(std::out_of_range& e)
					{	//currently, if we have a bad date then we
						//just don't put it onto the data set.  I'm
						//not sure whether this is the best thing to do
						//or not.
						cerr << "Bad date: " << *tok_iter;
					}
				}

			}
			break;
		case VR_UN:
			{
				vector <BYTE> v (length);
				buffer_>>v;
				dataset_.Put<VR_UN>(tag,v);
			}
			break;

			//all the string types!
			//(This list will get shorter as we introduce more intelligent types for
			// some VR's, e.g. a proper Date type,)
		case VR_AS:
        {	 DecodeString<VR_AS>(tag,length); return true;}
		case VR_CS:
        {	 DecodeString<VR_CS>(tag,length); return true;}
		case VR_DS:
        {	 DecodeString<VR_DS>(tag,length); return true;}
		case VR_DT:
        {	 DecodeString<VR_DT>(tag,length); return true;}//really should be a datetime object!!
		case VR_LO:
        {	 DecodeString<VR_LO>(tag,length); return true;}
		case VR_LT:
        {	 DecodeString<VR_LT>(tag,length); return true;}
		case VR_PN:
        {	 DecodeString<VR_PN>(tag,length); return true;}
		case VR_SH:
        {	 DecodeString<VR_SH>(tag,length); return true;}
		case VR_ST:
        {	 DecodeString<VR_ST>(tag,length); return true;}
		case VR_TM:
        {	 DecodeString<VR_TM>(tag,length); return true;}
		case VR_UT://unlimited text.  Cannot be multivalued.
			{

				string s(length,' ');
				buffer_>>s;
				StripTrailingWhitespace(s);
				dataset_.template Put<VR_UT>(tag,s);

			}
			break;
		case VR_IS:
        {	DecodeString<VR_IS>(tag,length); return true;}
		case VR_AE:
        {   DecodeString<VR_AE>(tag,length); return true;}
		default:
			cout << "Unknown VR: " << UINT32(vr) << " in DecodeElement()" << endl;
            cout << "Tag is: " << UINT32(tag) << "  dataset size is " << dataset_.size() << endl;
			throw UnknownVR(vr);
        }

        return true;
	}

	/*!
		Sequences are described in Part 5, section 7.5.
	*/
	void Decoder::DecodeSequence(Tag SequenceTag,UINT32 SequenceLength)
	{
		//need to keep track of bytes read if SequenceLength is not UNDEFINED_LENGTH
		Sequence sequence;
		UINT32 BytesLeftToRead=SequenceLength;
		while(BytesLeftToRead>0)
		{

			UINT16 Group;
			UINT16 Element;
			buffer_>>Group;
			buffer_>>Element;
			Tag tag=makeTag(Group,Element);

			UINT32 ItemLength;
			buffer_ >> ItemLength;

			if(BytesLeftToRead!=UNDEFINED_LENGTH)
				BytesLeftToRead -= 8;
			switch (tag)
			{
			case TAG_ITEM:
				{
					DataSet data;

					if(ItemLength!=UNDEFINED_LENGTH)
					{
						/* make a copy of relevant bit of buffer.
						* This is time-intensive, but simplifies the code considerably.
						*/

						Buffer b(buffer_.ExternalByteOrder_);
						std::copy(buffer_.position(),buffer_.position()+ItemLength,std::back_inserter(b));
						Decoder D(b,data,ts_);
						D.Decode();

						//buffer_.position()+=ItemLength;
						buffer_.Increment(ItemLength);

						if(BytesLeftToRead!=UNDEFINED_LENGTH)
							BytesLeftToRead-=ItemLength;
					}
					else
					{
						/*
						Just feed in current buffer and trust system to correctly increment I
						*/

						Buffer::iterator I=buffer_.position();
						Decoder D(buffer_,data,ts_);

						D.Decode();

						UINT32 BytesRead=buffer_.position()-I;

						if(BytesLeftToRead!=UNDEFINED_LENGTH)
							BytesLeftToRead-=BytesRead;

					}

					sequence.push_back(data);
					if(BytesLeftToRead==0)
					{

						dataset_.Put<VR_SQ>(SequenceTag,sequence);

						return;
					}
				}
				break;
			case TAG_SEQ_DELIM_ITEM:
				//maybe check that length is 0x00000000
				if(ItemLength!=0)
					cout<<"sequence delimination item length should really be zero." << endl;

				//we're done

				dataset_.Put<VR_SQ>(SequenceTag,sequence);

				return;
			default:
				cout << "some funny tag in DecodeSequence() :" << tag << endl;
				throw UnknownTag(tag);
			}
		}

		dataset_.Put<VR_SQ>(SequenceTag,sequence);
	}

	void Decoder::Decode()
	{
		try
        {
            bool controlLoop = true;
            while(controlLoop && (buffer_.position()!=buffer_.end())){
                controlLoop = DecodeElement();
            }
		}
        catch(EndOfSequence *eos)
		{
            delete (eos);
			return;
		}
        catch(...)
        {
            return;
        }
	}

	void ReadFromBuffer(Buffer& buffer, DataSet& data, TS transfer_syntax)
    {
		Decoder d(buffer,data,transfer_syntax);
        d.Decode();
	}

	void ReadElementFromBuffer(Buffer& buffer, DataSet& ds,TS transfer_syntax)
	{
		Decoder d(buffer,ds,transfer_syntax);
		d.DecodeElement();

	}
};//namespace dicom

/*

Some notes on data time:

Part5/Table 6.2-1 specifies how VR_DT is encoded.
We're not currently converting this interally to a boost time object, but
hopefully we will in the future.
However boost doesn't have a mechanism for managing Coordinated Universal Time
offsets, so it might be safest to just leave it as a string.  If we do that,
then we should probably also make VR_DA stay as a string, and get rid of
the dependency on boost::date_time entirely?

*/

max_stars_repo_name: marcosivni/dicomlib

max_issues_repo_name: marcosivni/dicomlib

max_forks_repo_name: marcosivni/dicomlib


text:
#include "core/application.hpp"
#include "core/options.hpp"

#include <gearshifft_version.hpp>

#include <iostream>
#include <fstream>
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>

using namespace gearshifft;
namespace po = boost::program_options;

OptionsDefault::OptionsDefault() {
  add_options()
    ("help,h", "Print help messages")
    ("extent,e", po::value<std::vector<std::string>>()->multitoken()->
     composing(), "Specific extent (eg. 1024x1024) [>=1 nr. of args possible]")
    ("file,f", po::value<std::vector<std::string>>()->multitoken()->
     composing(), "File with extents (row-wise csv) [>=1 nr. of args possible]")
    ("output,o", po::value<std::string>(&outputFile_)->default_value("result.csv"), "output csv file, will be overwritten!")
    ("add-tag,t", po::value<std::string>(&tag_)->default_value(""), "Add custom tag to header of output file")
    ("verbose,v", "Prints benchmark statistics")
    ("version,V", "Prints gearshifft version")
    ("device,d", po::value<std::string>(&device_)->default_value("gpu"), "Compute device = (gpu|cpu|acc|<ID>). If device is not supported by FFT lib, then it is ignored and default is used.")
    ("ndevices,n", po::value<size_t>(&ndevices_)->default_value(0), "Number of devices (0=all), if supported by FFT lib (e.g. clfft and fftw with n CPU threads).")
    ("list-devices,l", "List of available compute devices with IDs, if supported.")
    ("list-benchmarks,b", "Show registered benchmarks")
    ("run-benchmarks,r", po::value<std::string>(), "Run specific benchmarks (wildcards possible, e.g. ClFFT/float/*/Inplace_Real)")
    ;
}

OptionsDefault::~OptionsDefault() {
  delete[] tmp_;
  tmp_ = nullptr;
}

void OptionsDefault::parseFile(const std::string& file) {
  std::ifstream f(file);
  std::string line;
  while(std::getline(f, line)) {
    if(boost::starts_with(line, "#")) // skip comment line
      continue;
    if(line.empty())
      continue;
    parseExtent(line);
  }
}

void OptionsDefault::parseExtent( const std::string& extent ) {
  std::vector<std::string> token;
  boost::split(token, extent, boost::is_any_of("x,"));
  if(token.size()==1) {
    Extents1D array = {std::stoull(token[0])};
    vector1D_.push_back( array );
  } else if(token.size()==2) {
    Extents2D array = {std::stoull(token[0]),
                       std::stoull(token[1])};
    vector2D_.push_back( array );
  } else {
    Extents3D array = {std::stoull(token[0]),
                       std::stoull(token[1]),
                       std::stoull(token[2])};
    vector3D_.push_back( array );
  }
}

/// processes command line arguments and apply the values to the variables
int OptionsDefault::parse(std::vector<char*>& _argv, std::vector<char*>& _boost_vargv) {

  po::variables_map vm;
  try {
    po::parsed_options parsed
      = po::command_line_parser( _argv.size(),
                                 _argv.data()
                               ).options(desc_).allow_unregistered().run();
    po::store(parsed, vm);
    if( vm.count("version")  ) {
      std::cout << "gearshifft " << gearshifft::gearshifft_version() << "\n";
      return 1;
    }
    if( vm.count("help")  ) {
      std::cout << "gearshifft " << gearshifft::gearshifft_version() << "\n\n"
                << desc_
                << std::endl;
      return 1;
    }
    if( vm.count("file")  ) {
      auto files = vm["file"].as<std::vector<std::string> >();
      for( auto f : files ) {
        parseFile(f);
      }
    }
    if( vm.count("extent")  ) {
      auto extents = vm["extent"].as<std::vector<std::string> >();
      for( auto e : extents ) {
        parseExtent(e);
      }
    }
    if( vm.count("verbose")  ) {
      verbose_ = true;
    }else{
      verbose_ = false;
    }
    if( vm.count("list-devices")  ) {
      listDevices_ = true;
      return 1;
    }else{
      listDevices_ = false;
    }
    // no file and no extent given, use default config
    if( !vm.count("file") && !vm.count("extent") ) {
      if( std::ifstream(BOOST_STRINGIZE(GEARSHIFFT_INSTALL_CONFIG_FILE)).good() ) {
        parseFile(BOOST_STRINGIZE(GEARSHIFFT_INSTALL_CONFIG_FILE));
      }else if(std::ifstream("../share/gearshifft/extents.conf").good()){ // if not configs installed yet, use local path
        parseFile("../share/gearshifft/extents.conf");
      }else{ // if default config file is missing, then use these extents
        std::cerr << "Could not find 'extents.conf' so internal fallback is used." << std::endl;
        parseExtent("32");
        parseExtent("32x32");
        parseExtent("32x32x32");
      }
    }

    // use Boost command line arguments
    if( vm.count("list-benchmarks") ){
      _boost_vargv.emplace_back(const_cast<char*>("--list_content"));
    }
    if( vm.count("run-benchmarks") ){
      // C / C++ string madness
      std::string str = "--run_test=" + vm["run-benchmarks"].as<std::string>();
      if(tmp_)
        throw std::runtime_error("This is not supposed to happen, the pointer should be null.");
      tmp_ = new char[str.size()+1];
      str.copy(tmp_, str.size());
      tmp_[str.size()] = '\0';
      _boost_vargv.emplace_back( tmp_ );
    }

    po::notify(vm);
  }
  catch(po::error& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
    std::cerr << desc_ << std::endl;
    return 2;
  }

  return 0;
}

max_stars_repo_name: paklui/gearshifft

max_issues_repo_name: paklui/gearshifft

max_forks_repo_name: paklui/gearshifft


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2016 Sebastian Schlenkrich

*/

#ifndef quantlib_templateauxilliaries_regression_hpp
#define quantlib_templateauxilliaries_regression_hpp

//#include <ql/types.hpp>
//#include <boost/function.hpp>

//#include <ql/experimental/template/auxilliaries/templatesvd.hpp>
#include <ql/experimental/templatemodels/auxilliaries/qrfactorisationT.hpp>

namespace TemplateAuxilliaries {

    template <class Type>
    class Regression {

    protected:

        size_t                               maxDegree_;  // max polynomial degree
        std::vector< std::vector<size_t> >   multIdx_;    // list of all multi-indeces with degree <= maxDegree_
        std::vector<Type>                    beta_;       // linear coefficients

        inline void divide( std::vector<size_t> x, size_t idx, size_t degree) {
            if (idx==x.size()-1) {
                x[idx] = degree;
                multIdx_.push_back(x);
            } else {
                for (size_t k=0; k<=degree; ++k) {
                    x[idx] = k;
                    divide(x, idx+1, degree-k);
                }
            }
        }

        // initialise multi-index matrix via recursive call of divide()
        inline void setUpMultiIndex(const size_t dim, const size_t maxDegree) {
            multIdx_.clear();
            std::vector<size_t> x(dim,0);
            for (size_t k=0; k<=maxDegree; ++k) divide(x,0,k);
        }

        // perform actual regression calculation
        inline void calculateRegression( const std::vector< std::vector<Type> >& controls,
                                         const std::vector< Type >&              observations ) {
            std::vector<Type> b(observations);
            std::vector< std::vector<Type> >  M(controls.size());
            for (size_t i=0; i<M.size(); ++i) M[i] = monomials(controls[i]);
            qrsolveles(M,b);
            for (size_t i=0; i<beta_.size(); ++i) beta_[i] = b[i];

        }

    public:

        Regression ( const std::vector< std::vector<Type> >& controls,
                     const std::vector< Type >&              observations,
                     const size_t                            maxDegree ) : maxDegree_(maxDegree) {
            // check dimensions
            size_t nRows = 0;
            if (controls.size()==observations.size()) nRows = controls.size();

            if (nRows>0) setUpMultiIndex(controls[0].size(),maxDegree_);
            size_t nCols = multIdx_.size();

            // initialise beta
            beta_.resize(nCols,0.0);
            if ((nRows>0)&&(nRows>=nCols))
                calculateRegression(controls,observations);  // if nRows < nCols regression does not really make sense

        }

        const std::vector<Type> monomials( const std::vector<Type>& x ) const {
            std::vector<Type> y(multIdx_.size(),0.0);
            if ((multIdx_.size()==0)||(multIdx_[0].size()!=x.size())) return y;  // dimension mismatch
            for (size_t i=0; i<y.size(); ++i) {
                y[i] = 1.0;
                for (size_t j=0; j<x.size(); ++j) {  // don't want to use pow coz not clear how it's implemented
                    for (size_t k=0; k<multIdx_[i][j]; ++k) y[i] *= x[j];
                }
            }
            return y;
        }

        const Type value( const std::vector<Type>& x ) const {
            std::vector<Type> y = monomials(x);
            if (y.size()!=beta_.size()) return 0.0;  // dimension mismatch
            Type res = 0.0;
            for (size_t i=0; i<y.size(); ++i) res += beta_[i] * y[i];
            return res;
        }

        // inspectors

        const size_t                              maxDegree() const { return maxDegree_; }
        const std::vector< std::vector<size_t> >& multIdx()   const { return multIdx_;   }
        const std::vector<Type>&                  beta()      const { return beta_;      }

        const std::vector< std::vector<Type> >    multiIndex() const {  // workaround for Excel interface debugging
            std::vector< std::vector<Type> > M(multIdx_.size());
            for (size_t i=0; i<multIdx_.size(); ++i) {
                M[i].resize(multIdx_[i].size());
                for (size_t j=0; j<multIdx_[i].size(); ++j) M[i][j] = multIdx_[i][j];
            }
            return M;
        }

    };

}

#endif  /* ifndef quantlib_templateauxilliaries_regression_hpp */

max_stars_repo_name: sschlenkrich/quantlib

max_issues_repo_name: sschlenkrich/quantlib

max_forks_repo_name: sschlenkrich/quantlib


text:
#include <fstream>
#include <assert.h>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "../ipc/zmq_ipc/zmq_context_singleton.hpp"
#include "../ipc/zmq_ipc/zmq_socket_factory.hpp"
#include "../ipc/zmq_ipc/zmqhelper.hpp"

#include "../api/ctp/ThostFtdcMdApi.h"
#include "../api/ctp/ThostFtdcTraderApi.h"
#include "../api/ctp/ThostFtdcUserApiDataType.h"
#include "../api/ctp/ThostFtdcUserApiStruct.h"

#include "../event/event_engine.h"
#include "../event/event_tick.h"

#include "../pojo/market_data.h"
#include "../pojo/bar.h"
#include "../util/bar_generator.h"
#include "../strategy/macd.h"
#include "../util/util_func.h"

// 这个文件对应的进程是为了从main_preprocess 里接收预处理数据， 进行策略的生成
int main(){

    zmq_context_singleton & singleton = zmq_context_singleton::singleton();
    void * context = singleton.get_singleton_context();

    void * socket_bar = zmq_socket_factory::get_socket(context, "bar", 0);
    void * socket_suggestion = zmq_socket_factory::get_socket(context, "suggestion", 1);

    zmq_pollitem_t items[] ={
        {socket_bar, 0, ZMQ_POLLIN, 0}
    };

    int load_history_flag = 0;
    std::vector<double> v;

    int i = 0;
    while(i < 30){

        zmq_poll(items, 1, -1);

        if(items[0].revents & ZMQ_POLLIN){

            if(load_history_flag == 0){
                load_history(v);
            }
            std::pair<std::string, kbar *> pa = z_msg_recv<kbar>(socket_bar);
            std::cout << pa.second->contract << "     ";
            std::cout << pa.second->minute << "     ";
            std::cout << pa.second->high << "     ";
            std::cout << pa.second->low << "     ";
            std::cout << pa.second->open << "     ";
            std::cout << pa.second->close << std::endl;

            v.push_back(pa.second->close);
            int result = macd_calulate(v, v.size() - 40, v.size()-1);
            if(result == -2) continue;

            //other strategy calculation  like 100 kind
            //combine several strategy to get the suggestion

            //order suggestion send out
            z_msg_send(socket_suggestion, pa.second->contract, result);

        }

    }

    zmq_socket_factory::close_socket(socket_bar);
    singleton.close_context();

}

max_stars_repo_name: DavidLongbottom/apolo

max_issues_repo_name: DavidLongbottom/apolo

max_forks_repo_name: DavidLongbottom/apolo