<commit_before><commit_msg>add seperate all nodes by hierarchy<commit_after>// C++ program to generate long DFS traversal from a given vertex in a  given graph
#include <iostream>
#include <list>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>

using namespace std;

// Pre-define hierarchy array
// CUI: array of top nodes concept id of each hierarchy
// ConName: array of the name of each hierarchy
const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};
const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"};

// define global variables
// nodeMap: store all the concepts [key,value]
// reversedNodeMap: store reversed nodeMap [value,key]
// nodeFile, relationFile, outputFile, as variable name

std::map<long long, int> nodeMap;
std::map<int, long long> reversedNodeMap;
string nodeFile = "2016nodes.txt";
string relationFile = "2016relation.txt";
string outPutFolder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/";
std::vector<long long> outPutVec;
// Graph class represents a directed graph using adjacency list representation
class Graph
{
    long long V;
    list<long long> *adj;
    void DFSUtil(long long v, bool visited[]);
public:
    Graph(long long V);
    void addEdge(long long v, long long w);
    void DFS(long long v);
};

Graph::Graph(long long V)
{
    this->V = V;
    adj = new list<long long>[V];
}

void Graph::addEdge(long long v, long long w)
{
    adj[v].push_back(w);
}

void Graph::DFSUtil(long long v, bool visited[])
{
    visited[v] = true;
    // output to terminal
    // cout << reversedNodeMap[v] << " ";

    // output to file
    outPutVec.push_back(reversedNodeMap[v]);
    list<long long>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i, visited);
}

void Graph::DFS(long long v)
{
    bool *visited = new bool[V];
    for (long long i = 0; i < V; i++)
        visited[i] = false;

    DFSUtil(v, visited);
}

// string split function: split(s,d)
// input: s: string, d: delimiter
// output: a vector of splitted strings
void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

vector<long long> split(const string &s, char delim) {
    vector<string> elems;
    vector<long long> res;
    split(s, delim, elems);
    for(auto i : elems){
        res.push_back(std::stoll(i));
    }
    return res;
}

int main()
{

    long long topNode;
    // cin >> outputFile >> topNode;
    string sline;
    vector<string> relation;
    std::vector<string> nodes;

    fstream fin;
    fin.open(nodeFile,ios::in);
    while (getline(fin, sline)){
        nodes.push_back(sline);
    }
    fin.close();
    for (int i = 0; i < nodes.size(); ++i){
        nodeMap[std::stoll(nodes[i])] = i;
    }

    for (map<long long, int>::iterator i = nodeMap.begin(); i != nodeMap.end(); ++i)
        reversedNodeMap[i->second] = i->first;

    int nodeSize = nodeMap.size();
    fin.open(relationFile,ios::in);
    while (getline(fin, sline)){
        relation.push_back(sline);
    }
    fin.close();
    Graph g(nodeSize);
    std::vector<long long> vres;
    for (auto i : relation){
        vres.clear();
        vres = split(i, ',');
        g.addEdge(nodeMap[vres[1]],nodeMap[vres[0]]);
    }
    // g.addEdge(1, 2);
    // g.DFS(nodeMap[vres[0]]);
    // g.DFS(nodeMap[105590001]);
    string outPutFile;
    for (int i = 0; i < 19; ++i){
        outPutVec.clear();
        outPutFile.clear();
        outPutFile = outPutFolder + ConName[i];
        topNode = CUI[i];
        g.DFS(nodeMap[topNode]);
        fstream fout;
        fout.open(outPutFile,ios::app);
        for (auto o : outPutVec){
            fout << o << endl;
        }
        fout.close();
        // cout << outPutVec.size() << endl;
    }

      return 0;
}<|endoftext|>


<commit_before>
#include <initializer_list>
#include <iostream>
#include <fstream>
#include <array>
#include <type_traits>
#include <algorithm>
#include <memory>
#include <stdio.h>
#include <utility>

#include <vector>
#include <map>

#include "ast.h"
#include "helpers.h"
#include "llvm.h"
#include "parser.h"

int main(int argc, char **argv)
{
  Llvm vm;
  vm.registerExtern(vm.intTy(), "printf", true);

  std::unique_ptr<Reader> r;
  std::ifstream src;
  if (argc == 2) {
    src.open(argv[1]);
    r.reset(new Reader(argv[1], src));
  } else {
    r.reset(new Reader("-", std::cin));
  }

  msg("Parse:");
  std::vector<std::unique_ptr<SExpr>> toplevel;
  while (SExpr *e = sexpr(*r))
    toplevel.emplace_back(e);

  msg("Compile:");
  llvm::Value *last;
  for (auto &e : toplevel)
    last = e->codegen(vm);
  vm.builder.CreateRet(last);
  vm.module->dump();

  std::string err;
  std::unique_ptr<llvm::ExecutionEngine> ee(
    llvm::EngineBuilder(std::move(vm.module)).setErrorStr(&err).create());
  if (!ee) {
    std::cerr << "Could not create exe engine: " << err << std::endl;
    return 1;
  }
  ee->runFunction(vm.prog, {});
}
<commit_msg>Add verification check for module.<commit_after>
#include <initializer_list>
#include <iostream>
#include <fstream>
#include <array>
#include <type_traits>
#include <algorithm>
#include <memory>
#include <stdio.h>
#include <utility>

#include <vector>
#include <map>

#include <llvm/IR/Verifier.h>

#include "ast.h"
#include "helpers.h"
#include "llvm.h"
#include "parser.h"

int main(int argc, char **argv)
{
  Llvm vm;
  vm.registerExtern(vm.intTy(), "printf", true);

  std::unique_ptr<Reader> r;
  std::ifstream src;
  if (argc == 2) {
    src.open(argv[1]);
    r.reset(new Reader(argv[1], src));
  } else {
    r.reset(new Reader("-", std::cin));
  }

  msg("Parse:");
  std::vector<std::unique_ptr<SExpr>> toplevel;
  while (SExpr *e = sexpr(*r))
    toplevel.emplace_back(e);

  msg("Compile:");
  llvm::Value *last;
  for (auto &e : toplevel)
    last = e->codegen(vm);
  vm.builder.CreateRet(last);
  vm.module->dump();

  if (!llvm::verifyModule(*vm.module))
    return 1;

  std::string err;
  std::unique_ptr<llvm::ExecutionEngine> ee(
    llvm::EngineBuilder(std::move(vm.module)).setErrorStr(&err).create());
  if (!ee) {
    std::cerr << "Could not create exe engine: " << err << std::endl;
    return 1;
  }
  ee->runFunction(vm.prog, {});
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "closestPairInLine.hpp"
#include "cmdline.h"
#define WIDTH 28
#define HEIGHT 28
#define TRY_TIME 100
using namespace std;
int d, n;
string path;
cmdline::parser p;
short s[60020][800] = {0};
double ans;
int cpx, cpy;
vector<double> line;
vector<pair<double, int>> pos;

void setCmdParser() {
    // -n command
    p.add<int>("number", 'n', "the number of images", true, 0);
    // -d command
    p.add<int>("dimensions", 'd', "the dimensions of images", true, 0);
    // -f command
    p.add<string>("file", 'f', "the path to dataset", true, "");
}

void readDataset(int n, int d, string path) {
    ifstream input(path);
    if (!input.is_open()) {
        cout << "input file doesn't exist!" << endl;
        exit(0);
    }
    for (int w = 1; w <= n; w++) {
        int i, j;
        input >> i;
        for (j = 1; j <= d; j++) input >> s[i][j];
    }
}

void printImage(int x) {
    for (int i = 1; i <= HEIGHT; i++) {
        for (int j = 1; j <= WIDTH; j++)
            if (s[x][(i - 1) * 28 + j] == 0)
                cout << '*';
            else
                cout << ' ';
        cout << '\n';
    }
}

double getStandardNormalDistribution() {
    const double epsilon = numeric_limits<double>::min();
    const double twoPi = 2.0 * 3.14159265358979323846;
    double x, y, flag;
    do {
        x = rand() * (1.0 / RAND_MAX);
        y = rand() * (1.0 / RAND_MAX);
        flag = rand() * (1.0 / RAND_MAX);
    } while (x <= epsilon);
    if (flag > 0.5)
        return sqrt(-2.0 * log(x)) * cos(twoPi * y);
    else
        return sqrt(-2.0 * log(x)) * sin(twoPi * y);
}

void getRandomLine(int d) {
    line.clear();
    for (int i = 1; i <= d; i++) {
        line.push_back(getStandardNormalDistribution() * 1000);
    }
}

double euclideanDistance(int x, int y, int d) {
    double ans = 0;
    for (int i = 1; i <= d; i++) {
        ans = ans + (s[x][i] - s[y][i]) * (s[x][i] - s[y][i]);
    }
    return ans;
}

void findClosestPair(int flag) {
    for (int k = 1; k <= TRY_TIME; k++) {
        getRandomLine(d);
        pos.clear();
        for (int i = 1; i <= n; i++) {
            double temp = 0;
            for (int j = 1; j <= d; j++) temp = temp + s[i][j] * line[j - 1];
            pos.push_back(make_pair(temp, i));
        }
        pair<int, int> p = getClosestPairInLine(n, flag);
        double temp = euclideanDistance(p.first, p.second, d);
        if (temp < ans || ans < 0) {
            ans = temp;
            cpx = p.first;
            cpy = p.second;
        }
    }
}

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

    p.parse_check(argc, argv);
    // get arguments
    n = p.get<int>("number");
    d = p.get<int>("dimensions");
    path = p.get<string>("file");

    readDataset(n, d, path);

    srand(time(NULL));
    ans = -1;
    findClosestPair(PIVOT_FLAG);
    //findClosestPair(MEDIAN_FLAG);

    cout << "Closest Pair is Image No." << cpx << " and Image No." << cpy
         << endl;
    cout << "Image No." << cpx << endl;
    printImage(cpx);
    cout << "Image No." << cpy << endl;
    printImage(cpy);
    return 0;
}
<commit_msg>fix bug<commit_after>#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "closestPairInLine.hpp"
#include "cmdline.h"
#define WIDTH 28
#define HEIGHT 28
#define TRY_TIME 100
using namespace std;
int d, n;
string path;
cmdline::parser p;
short s[60020][800] = {0};
double ans;
int cpx, cpy;
vector<double> line;
vector<pair<double, int>> pos;

void setCmdParser() {
    // -n command
    p.add<int>("number", 'n', "the number of images", true, 0);
    // -d command
    p.add<int>("dimensions", 'd', "the dimensions of images", true, 0);
    // -f command
    p.add<string>("file", 'f', "the path to dataset", true, "");
}

void readDataset(int n, int d, string path) {
    ifstream input(path);
    if (!input.is_open()) {
        cout << "input file doesn't exist!" << endl;
        exit(0);
    }
    for (int w = 1; w <= n; w++) {
        int i, j;
        input >> i;
        for (j = 1; j <= d; j++) input >> s[i][j];
    }
}

void printImage(int x) {
    for (int i = 1; i <= HEIGHT; i++) {
        for (int j = 1; j <= WIDTH; j++)
            if (s[x][(i - 1) * 28 + j] == 0)
                cout << '*';
            else
                cout << ' ';
        cout << '\n';
    }
}

double getStandardNormalDistribution() {
    const double epsilon = numeric_limits<double>::min();
    const double twoPi = 2.0 * 3.14159265358979323846;
    double x, y, flag;
    do {
        x = rand() * (1.0 / RAND_MAX);
        y = rand() * (1.0 / RAND_MAX);
        flag = rand() * (1.0 / RAND_MAX);
    } while (x <= epsilon);
    if (flag > 0)
        return sqrt(-2.0 * log(x)) * cos(twoPi * y);
    else
        return sqrt(-2.0 * log(x)) * sin(twoPi * y);
}

void getRandomLine(int d) {
    line.clear();
    for (int i = 1; i <= d; i++) {
        line.push_back(getStandardNormalDistribution());
    }
}

double euclideanDistance(int x, int y, int d) {
    double ans = 0;
    for (int i = 1; i <= d; i++) {
        ans = ans + (s[x][i] - s[y][i]) * (s[x][i] - s[y][i]);
    }
    return ans;
}

void findClosestPair(int flag) {
    for (int k = 1; k <= TRY_TIME; k++) {
        getRandomLine(d);
        pos.clear();
        for (int i = 1; i <= n; i++) {
            double temp = 0;
            for (int j = 1; j <= d; j++) temp = temp + s[i][j] * line[j - 1];
            pos.push_back(make_pair(temp, i));
        }
        pair<int, int> p = getClosestPairInLine(n, flag);
        double temp = euclideanDistance(p.first, p.second, d);
        if (temp < ans || ans < 0) {
            ans = temp;
            cpx = p.first;
            cpy = p.second;
        }
    }
}

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

    p.parse_check(argc, argv);
    // get arguments
    n = p.get<int>("number");
    d = p.get<int>("dimensions");
    path = p.get<string>("file");

    readDataset(n, d, path);

    srand(time(NULL));
    ans = -1;
    //findClosestPair(PIVOT_FLAG);
    findClosestPair(MEDIAN_FLAG);

    cout << "Closest Pair is Image No." << cpx << " and Image No." << cpy
         << endl;
    cout << "Image No." << cpx << endl;
    printImage(cpx);
    cout << "Image No." << cpy << endl;
    printImage(cpy);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 findrec developers
 *
 * See the file license.txt for copying permission.
 */

#include "findfiles.h"
#include "filematch.h"

#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <boost/utility/binary.hpp>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#  define IS_WINDOWS 1
#endif

static struct Options
{
    enum StatusCode : int
    {
        Success     =  0,
        EarlyExit   = -1,
        MissingArg  = -2,
        InvalidArg  = -3,
    };

    enum ExecMode
    {
        NoExec      = BOOST_BINARY(000),
        ExecAll     = BOOST_BINARY(001),
        ExecEach    = BOOST_BINARY(010),
    };

    std::string     needle;
    MatchType       match_type;
    MatchFileType   match_file_type;

    ExecMode        exec_mode;
    std::vector<std::string> exec_command;

    Options()
    : match_type(Expansion),
      match_file_type((MatchFileType)(Directories | Files)),
      exec_mode(NoExec)
    {}
} options;

static void print_usage(const char* progname)
{
    printf("Usage:  %s [options] search_term\n", progname);
    printf( "\nOptions are:\n"
            "    --regex, -r    The search term is a regular expression.\n"
            "    --directories, -d\n"
            "                   Match only directories.\n"
            "    --files, -f    Match only files that are not directories.\n"
            "    --exec-all command\n"
            "                   Execute a command with the matched files as arguments\n"
            );
}

static Options::StatusCode parse_args(int argc, char** argv)
{
    using namespace std;

    for (int i = 1; i < argc; i++)
    {
        string arg = argv[i];
        const bool is_short_opt = arg.length() && arg.at(0) == '-';
        const bool is_long_opt = arg.compare(0, 2, "--") == 0;

        if (arg == "--help" || arg == "-h")
        {
            print_usage(argv[0]);
            return Options::EarlyExit;
        }
        else if (arg == "--regex" || arg == "-r")
        {
            options.match_type = Regex;
        }
        else if (arg == "--directories" || arg == "-d")
        {
            options.match_file_type = (MatchFileType)(options.match_file_type & ~Files);
        }
        else if (arg == "--files" || arg == "-f")
        {
            options.match_file_type = (MatchFileType)(options.match_file_type & ~Directories);
        }
        else if (arg == "--exec-all")
        {
            options.exec_mode = Options::ExecAll;
            if (i >= argc - 1)
            {
                fprintf(stderr, "Missing argument to %s\n", argv[i]);
                return Options::MissingArg;
            }
            while (i < argc - 1)
            {
                string arg = argv[++i];
                if (arg == "end")
                    break;
                options.exec_command.push_back(std::move(arg));
            }
        }
        else if (is_long_opt)
        {
            fprintf(stderr, "Unrecognized option:  %s\n", argv[i]);
            return Options::InvalidArg;
        }
        else if (is_short_opt)
        {
            const char ch = arg.length() >= 2 ? arg.at(0) : ' ';
            fprintf(stderr, "Unrecognized option:  %c\n", ch);
            return Options::InvalidArg;
        }
        else
        {
            options.needle = arg;
        }
    }

    return Options::Success;
}

static void matched_plain_printer(const boost::filesystem::path& path)
{
    printf("%s\n", path.string().c_str());
}

static void matched_vector_pusher(std::vector<boost::filesystem::path>& matched_paths, const boost::filesystem::path& path)
{
    matched_paths.push_back(path);
    matched_plain_printer(path);
}

// Create command from executable, params, and matched paths
static std::string create_command(const std::vector<std::string>& exe_pieces, const std::vector<boost::filesystem::path>& paths)
{
    std::string command;
    for (size_t i = 0; i < exe_pieces.size(); i++)
    {
        command += "\"" + exe_pieces.at(i) + "\" ";
    }

    for (size_t i = 0; i < paths.size(); i++)
    {
        std::string absolute_path = boost::filesystem::canonical(paths.at(i)).string();
        command += " \"" + absolute_path + "\"";
    }
    #if IS_WINDOWS
    command = "\"" + command + "\"";    // cmd gets really confused about spaces and quotations
    #endif
    return command;
}

int main(int argc, char** argv)
{
    using namespace std;
    using namespace std::placeholders;

    Options::StatusCode rv = parse_args(argc, argv);
    if (rv)
        return rv;

    boost::filesystem::path root = ".";
    Matcher matcher = create_matcher(options.needle, options.match_type, options.match_file_type);

    // Figure out what callback to call on match
    function<void(const boost::filesystem::path&)> match_callback = matched_plain_printer;
    vector<boost::filesystem::path> matched_paths;
    if (options.exec_mode == Options::ExecAll)
        match_callback = std::bind(&matched_vector_pusher, std::ref(matched_paths), _1);

    find_files(root, matcher, match_callback);

    if (options.exec_mode == Options::ExecAll && options.exec_command.size() && matched_paths.size())
    {
        const std::string command = create_command(options.exec_command, matched_paths);
        system(command.c_str());
    }

    return 0;
}
<commit_msg>Add placement parameter to --exec-all<commit_after>/*
 * Copyright (c) 2013 findrec developers
 *
 * See the file license.txt for copying permission.
 */

#include "findfiles.h"
#include "filematch.h"

#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <boost/utility/binary.hpp>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#  define IS_WINDOWS 1
#endif

static struct Options
{
    enum StatusCode : int
    {
        Success     =  0,
        EarlyExit   = -1,
        MissingArg  = -2,
        InvalidArg  = -3,
    };

    enum ExecMode
    {
        NoExec      = BOOST_BINARY(000),
        ExecAll     = BOOST_BINARY(001),
        ExecEach    = BOOST_BINARY(010),
    };

    std::string     needle;
    MatchType       match_type;
    MatchFileType   match_file_type;

    ExecMode        exec_mode;
    std::vector<std::string> exec_command;

    Options()
    : match_type(Expansion),
      match_file_type((MatchFileType)(Directories | Files)),
      exec_mode(NoExec)
    {}
} options;

static void print_usage(const char* progname)
{
    printf("Usage:  %s [options] search_term\n", progname);
    printf( "\nOptions are:\n"
            "    --regex, -r    The search term is a regular expression.\n"
            "    --directories, -d\n"
            "                   Match only directories.\n"
            "    --files, -f    Match only files that are not directories.\n"
            "    --exec-all command\n"
            "                   Execute a command with the matched files as arguments.\n"
            "                   Specify $* to specify where in the command matched paths\n"
            "                   should be placed.  If omitted, they will be appended to the\n"
            "                   end of the command.\n"
            );
}

static Options::StatusCode parse_args(int argc, char** argv)
{
    using namespace std;

    for (int i = 1; i < argc; i++)
    {
        string arg = argv[i];
        const bool is_short_opt = arg.length() && arg.at(0) == '-';
        const bool is_long_opt = arg.compare(0, 2, "--") == 0;

        if (arg == "--help" || arg == "-h")
        {
            print_usage(argv[0]);
            return Options::EarlyExit;
        }
        else if (arg == "--regex" || arg == "-r")
        {
            options.match_type = Regex;
        }
        else if (arg == "--directories" || arg == "-d")
        {
            options.match_file_type = (MatchFileType)(options.match_file_type & ~Files);
        }
        else if (arg == "--files" || arg == "-f")
        {
            options.match_file_type = (MatchFileType)(options.match_file_type & ~Directories);
        }
        else if (arg == "--exec-all")
        {
            options.exec_mode = Options::ExecAll;
            if (i >= argc - 1)
            {
                fprintf(stderr, "Missing argument to %s\n", argv[i]);
                return Options::MissingArg;
            }
            while (i < argc - 1)
            {
                string arg = argv[++i];
                if (arg == "end")
                    break;
                options.exec_command.push_back(std::move(arg));
            }
        }
        else if (is_long_opt)
        {
            fprintf(stderr, "Unrecognized option:  %s\n", argv[i]);
            return Options::InvalidArg;
        }
        else if (is_short_opt)
        {
            const char ch = arg.length() >= 2 ? arg.at(0) : ' ';
            fprintf(stderr, "Unrecognized option:  %c\n", ch);
            return Options::InvalidArg;
        }
        else
        {
            options.needle = arg;
        }
    }

    return Options::Success;
}

static void matched_plain_printer(const boost::filesystem::path& path)
{
    printf("%s\n", path.string().c_str());
}

static void matched_vector_pusher(std::vector<boost::filesystem::path>& matched_paths, const boost::filesystem::path& path)
{
    matched_paths.push_back(path);
    matched_plain_printer(path);
}

// Create command from executable, params, and matched paths
static std::string create_command(const std::vector<std::string>& exe_pieces, const std::vector<boost::filesystem::path>& paths)
{
    using namespace std;

    // Concatenate matched paths
    string paths_param;
    for (size_t i = 0; i < paths.size(); i++)
    {
        string absolute_path = boost::filesystem::canonical(paths.at(i)).string();
        paths_param += " \"" + absolute_path + "\"";
    }

    // Concatenate exec, params, and matched paths
    string command;
    bool contains_placement = false;
    for (size_t i = 0; i < exe_pieces.size(); i++)
    {
        if (exe_pieces.at(i) == "$*")  // Look for placement parameter
        {
            contains_placement = true;
            command += " " + paths_param;
        }
        else
            command += " \"" + exe_pieces.at(i) + "\" ";
    }
    // If placement parameter is not specified, put the matched paths at the end
    if (!contains_placement)
        command += paths_param;

    #if IS_WINDOWS
    command = "\"" + command + "\"";    // cmd gets really confused about spaces and quotations
    #endif
    return command;
}

int main(int argc, char** argv)
{
    using namespace std;
    using namespace std::placeholders;

    Options::StatusCode rv = parse_args(argc, argv);
    if (rv)
        return rv;

    boost::filesystem::path root = ".";
    Matcher matcher = create_matcher(options.needle, options.match_type, options.match_file_type);

    // Figure out what callback to call on match
    function<void(const boost::filesystem::path&)> match_callback = matched_plain_printer;
    vector<boost::filesystem::path> matched_paths;
    if (options.exec_mode == Options::ExecAll)
        match_callback = std::bind(&matched_vector_pusher, std::ref(matched_paths), _1);

    find_files(root, matcher, match_callback);

    if (options.exec_mode == Options::ExecAll && options.exec_command.size() && matched_paths.size())
    {
        const std::string command = create_command(options.exec_command, matched_paths);
        #if 0
        printf("Executing:\n%s\n", command.c_str());
        #endif
        system(command.c_str());
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "custer.h"
#include "CusterServer.h"

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>

#include <iostream>

namespace bpo = boost::program_options;

int main(int argc, char* argv[])
{
	bpo::options_description custer_options("Opciones permitidas");
	custer_options.add_options()
		("help,h", "muestra este mensaje de ayuda")
		("port,p", bpo::value<int>()->default_value(80, " 80"),
			"puerto al que asociarse")
		("directory,d", bpo::value<std::string>()->default_value(".", " dir. actual"),
			"directorio que se servira")
		("verbose,v", "imprime más informacion durante la ejecucion")
		("debug,d", "imprime informacion de depuracion");

	bpo::variables_map cmdline_variables;
	try {
		bpo::store(bpo::command_line_parser(argc, argv).
			options(custer_options).run(), cmdline_variables);
		bpo::notify(cmdline_variables);
	} catch (bpo::error& err) {
		fatal("%s", err.what());
	}

	if (cmdline_variables.count("help")) {
		std::cout << custer_options << std::endl;
		return 0;
	}

	if (cmdline_variables.count("verbose")) {
		logLevel = LOG_INFO;
	}
	if (cmdline_variables.count("debug")) {
		logLevel = LOG_DEBUG;
	}

	uint16_t port = cmdline_variables["port"].as<int>();
	std::string directory = cmdline_variables["directory"].as<std::string>();
	debug("Puerto: %u", port);
	debug("Directorio: '%s'", directory.c_str());

	boost::shared_ptr<custer::CusterServer> custerServer(
		new custer::CusterServer(port, directory));

	std::cout << "Iniciando servidor..." << std::endl;
	custerServer->run();

	return 0;
}<commit_msg>Llamada a WSAStartup para la implementacion de Windows<commit_after>#include "custer.h"
#include "CusterServer.h"

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>

#include <iostream>

namespace bpo = boost::program_options;

int main(int argc, char* argv[])
{
	bpo::options_description custer_options("Opciones permitidas");
	custer_options.add_options()
		("help,h", "muestra este mensaje de ayuda")
		("port,p", bpo::value<int>()->default_value(80, " 80"),
			"puerto al que asociarse")
		("directory,d", bpo::value<std::string>()->default_value(".", " dir. actual"),
			"directorio que se servira")
		("verbose,v", "imprime más informacion durante la ejecucion")
		("debug,d", "imprime informacion de depuracion");

	bpo::variables_map cmdline_variables;
	try {
		bpo::store(bpo::command_line_parser(argc, argv).
			options(custer_options).run(), cmdline_variables);
		bpo::notify(cmdline_variables);
	} catch (bpo::error& err) {
		fatal("%s", err.what());
	}

	if (cmdline_variables.count("help")) {
		std::cout << custer_options << std::endl;
		return 0;
	}

	if (cmdline_variables.count("verbose")) {
		logLevel = LOG_INFO;
	}
	if (cmdline_variables.count("debug")) {
		logLevel = LOG_DEBUG;
	}

	uint16_t port = cmdline_variables["port"].as<int>();
	std::string directory = cmdline_variables["directory"].as<std::string>();
	debug("Puerto: %u", port);
	debug("Directorio: '%s'", directory.c_str());

	boost::shared_ptr<custer::CusterServer> custerServer(
		new custer::CusterServer(port, directory));

#ifdef WIN32
	// Inicializamos WinSock
	WSADATA wsaData;
	int returnCode;
	if ((returnCode = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) {
		fatal("Inicializando WinSock 2.2 (codigo: %d)", returnCode);
	}

	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
		WSACleanup();
		fatal("Version WinSock 2.2 no disponible (version disponible: %d.%d)",
			LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
	}
#endif

	std::cout << "Iniciando servidor..." << std::endl;
	custerServer->run();

	return 0;
}<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2013, Institute for Artificial Intelligence,
 *  Universität Bremen.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Institute for Artificial Intelligence,
 *     Universität Bremen, nor the names of its contributors may be
 *     used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/** \author Jan Winkler */

// System
#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <string>

// Private
#include <semrec/SemanticHierarchyRecorderROS.h>

// Storage of former signal handlers
typedef void (*Handler)(int signum);
Handler hdlrOldSIGWINCH = SIG_IGN;

// Global variable for shutdown triggering
semrec::SemanticHierarchyRecorderROS* g_srRecorder;

void printHelp(std::string strExecutableName) {
  std::cout << "Semantic Hierarchy Recorder System (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m) by Jan Winkler <winkler@cs.uni-bremen.de>" << std::endl;
  std::cout << "Licensed under BSD. https://www.github.com/code-iai/ros-semrec" << std::endl << std::endl;
  std::cout << "Usage: " << strExecutableName << " [options]" << std::endl << std::endl;

  std::cout << "Available options are:" << std::endl;
  std::cout << "  -h, --help\t\tPrint this help" << std::endl;
  std::cout << "  -c, --config <file>\tLoad config file <file> instead of the default one" << std::endl;
  std::cout << "  -q, --quiet\t\tStart in quiet mode (command line output is suppressed)" << std::endl;
  std::cout << "  -s, --signify\t\tPrint single message when init is done (for automation)" << std::endl;
  std::cout << std::endl;

  std::cout << "Should any questions arise, feel free to send an email to winkler@cs.uni-bremen.de" << std::endl;
}

void catchHandler(int nSignum) {
  switch(nSignum) {
  case SIGTERM:
  case SIGINT: {
    g_srRecorder->triggerShutdown();
  } break;

  case SIGWINCH: {
    if(hdlrOldSIGWINCH != SIG_IGN && hdlrOldSIGWINCH != SIG_DFL) {
      (*hdlrOldSIGWINCH)(SIGWINCH);
    }

    g_srRecorder->triggerTerminalResize();
  } break;

  default:
    break;
  }
}

int main(int argc, char** argv) {
  g_srRecorder = new semrec::SemanticHierarchyRecorderROS(argc, argv);

  // Read command line parameters
  int nC, option_index = 0;
  static struct option long_options[] = {{"config",  required_argument, 0, 'c'},
				         {"quiet",   no_argument,       0, 'q'},
				         {"help",    no_argument,       0, 'h'},
					 {"signify", no_argument,       0, 's'},
				         {0,         0,                 0, 0}};

  std::string strConfigFile = "";
  bool bQuit = false;
  bool bQuiet = false;
  bool bSignify = false;

  while((nC = getopt_long(argc, argv, "c:qhs", long_options, &option_index)) != -1) {
    switch(nC) {
    case 'c': {
      strConfigFile = std::string(optarg);
    } break;

    case 'q': {
      bQuiet = true;
    } break;

    case 'h': {
      printHelp(std::string(argv[0]));
      bQuit = true;
    } break;

    case 's': {
      bSignify = true;
    } break;

    default: {
    } break;
    }
  }

  if(bQuit == false) {
    g_srRecorder->setQuiet(bQuiet);

    g_srRecorder->info("Starting semantic hierarchy recorder system (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m).");

    semrec::Result resInit = g_srRecorder->init(strConfigFile);

    if(resInit.bSuccess) {
      // Catch SIGTERM and SIGINT and bind them to the callback function
      // catchSIGTERMandSIGINT. This will trigger the shutdown mechanism
      // in the semrec instance.
      struct sigaction action;
      memset(&action, 0, sizeof(struct sigaction));
      action.sa_handler = catchHandler;
      sigaction(SIGTERM, &action, NULL);
      sigaction(SIGINT, &action, NULL);

      hdlrOldSIGWINCH = signal(SIGWINCH, SIG_IGN);
      sigaction(SIGWINCH, &action, NULL);

      g_srRecorder->info("Initialization complete, ready for action.", true);

      if(bSignify) {
	std::cout << "Signify: semrec init complete (version " + g_srRecorder->version() << ")" << std::endl;
      }

      while(g_srRecorder->cycle()) {
	// Idle here at will.
	usleep(10);
      }
    } else {
      g_srRecorder->fail("Initialization of the recorder system failed. Being a quitter.");
    }

    std::cout << "\r";
    g_srRecorder->info("Exiting gracefully.");
    g_srRecorder->cycle();

    g_srRecorder->deinit();
    g_srRecorder->cycle();

    delete g_srRecorder;
  }

  return EXIT_SUCCESS;
}
<commit_msg>A bit of help output and source code comments<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2013, Institute for Artificial Intelligence,
 *  Universität Bremen.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Institute for Artificial Intelligence,
 *     Universität Bremen, nor the names of its contributors may be
 *     used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/** \author Jan Winkler */

// System
#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <string>

// Private
#include <semrec/SemanticHierarchyRecorderROS.h>

// Storage of former signal handlers
typedef void (*Handler)(int signum);
Handler hdlrOldSIGWINCH = SIG_IGN;

// Global variable for shutdown triggering
semrec::SemanticHierarchyRecorderROS* g_srRecorder;

void printHelp(std::string strExecutableName) {
  std::cout << "Semantic Hierarchy Recorder System (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m) by Jan Winkler <winkler@cs.uni-bremen.de>" << std::endl;
  std::cout << "Licensed under BSD. https://www.github.com/code-iai/ros-semrec" << std::endl << std::endl;
  std::cout << "Usage: " << strExecutableName << " [options]" << std::endl << std::endl;

  std::cout << "Available options are:" << std::endl;
  std::cout << "  -h, --help\t\tPrint this help" << std::endl;
  std::cout << "  -c, --config <file>\tLoad config file <file> instead of the default one" << std::endl;
  std::cout << "  -q, --quiet\t\tStart in quiet mode (command line output is suppressed)" << std::endl;
  std::cout << "  -s, --signify\t\tPrint single message when init is done (for automation)" << std::endl;
  std::cout << std::endl;

  std::cout << "Should any questions arise, feel free to send an email to winkler@cs.uni-bremen.de" << std::endl;
  std::cout << "Get the source here: https://github.com/code-iai/semrec" << std::endl;
}

void catchHandler(int nSignum) {
  switch(nSignum) {
  case SIGTERM:
  case SIGINT: {
    g_srRecorder->triggerShutdown();
  } break;

  case SIGWINCH: {
    if(hdlrOldSIGWINCH != SIG_IGN && hdlrOldSIGWINCH != SIG_DFL) {
      (*hdlrOldSIGWINCH)(SIGWINCH);
    }

    g_srRecorder->triggerTerminalResize();
  } break;

  default:
    break;
  }
}

int main(int argc, char** argv) {
  g_srRecorder = new semrec::SemanticHierarchyRecorderROS(argc, argv);

  // Read command line parameters
  int nC, option_index = 0;
  static struct option long_options[] = {{"config",  required_argument, 0, 'c'},
				         {"quiet",   no_argument,       0, 'q'},
				         {"help",    no_argument,       0, 'h'},
					 {"signify", no_argument,       0, 's'},
				         {0,         0,                 0, 0}};

  std::string strConfigFile = "";
  bool bQuit = false;
  bool bQuiet = false;
  bool bSignify = false;

  while((nC = getopt_long(argc, argv, "c:qhs", long_options, &option_index)) != -1) {
    switch(nC) {
    case 'c': {
      strConfigFile = std::string(optarg);
    } break;

    case 'q': {
      bQuiet = true;
    } break;

    case 'h': {
      printHelp(std::string(argv[0]));
      bQuit = true;
    } break;

    case 's': {
      bSignify = true;
    } break;

    default: {
    } break;
    }
  }

  if(bQuit == false) {
    g_srRecorder->setQuiet(bQuiet);

    g_srRecorder->info("Starting semantic hierarchy recorder system (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m).");

    semrec::Result resInit = g_srRecorder->init(strConfigFile);

    if(resInit.bSuccess) {
      // Catch SIGTERM and SIGINT and bind them to the callback
      // function `catchHandler`. This will trigger the shutdown
      // mechanism in the global semrec instance.
      struct sigaction action;
      memset(&action, 0, sizeof(struct sigaction));
      action.sa_handler = catchHandler;
      sigaction(SIGTERM, &action, NULL);
      sigaction(SIGINT, &action, NULL);

      // Catch SIGWINCH to tell semrec about terminal resizes, and
      // store the original signal handler to invoke it, too.
      hdlrOldSIGWINCH = signal(SIGWINCH, SIG_IGN);
      sigaction(SIGWINCH, &action, NULL);

      g_srRecorder->info("Initialization complete, ready for action.", true);

      if(bSignify) {
	std::cout << "Signify: semrec init complete (version " + g_srRecorder->version() << ")" << std::endl;
      }

      while(g_srRecorder->cycle()) {
	// Idle here at will.
	usleep(10);
      }
    } else {
      g_srRecorder->fail("Initialization of the recorder system failed. Being a quitter.");
    }

    std::cout << "\r";
    g_srRecorder->info("Exiting gracefully.");
    g_srRecorder->cycle();

    g_srRecorder->deinit();
    g_srRecorder->cycle();

    delete g_srRecorder;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "lz4.h"
#include "lz4hc.h"
#include "xxhash.h"
#include "lz4mt.h"
#include "lz4mt_benchmark.h"
#include "lz4mt_io_cstdio.h"
#include "test_clock.h"

namespace {

const char LZ4MT_EXTENSION[] = ".lz4";

const char usage[] =
	"usage :\n"
	"  lz4mt [switch...] <input> [output]\n"
	"switch :\n"
	"  -c0/-c  : Compress (lz4) (default)\n"
	"  -c1/-hc : Compress (lz4hc)\n"
	"  -d      : Decompress\n"
	"  -y      : Overwrite without prompting\n"
	"  -H      : Help (this text + advanced options)\n"
;

const char usage_advanced[] =
	"\nAdvanced options :\n"
	" -t       : decode test mode (do not output anything)\n"
	" -B#      : Block size [4-7](default : 7)\n"
	" -BX      : enable block checksum (default:disabled)\n"
	" -Sx      : disable stream checksum (default:enabled)\n"
	" -b#      : benchmark files, using # [0-1] compression level\n"
	" -i#      : iteration loops [1-9](default : 3), benchmark mode"
	             " only\n"
	"  -s      : Single thread mode\n"
	"  -m      : Multi thread mode (default)\n"
	"  input   : can be 'stdin' (pipe) or a filename\n"
	"  output  : can be 'stdout'(pipe) or a filename or 'null'\n"
;

struct Option {
	Option(int argc, char* argv[])
		: error(false)
		, exitFlag(false)
		, compMode(CompMode::COMPRESS_C0)
		, sd(lz4mtInitStreamDescriptor())
		, mode(LZ4MT_MODE_DEFAULT)
		, inpFilename()
		, outFilename()
		, nullWrite(false)
		, overwrite(false)
		, benchmark()
	{
		static const std::string nullFilename = "null";

		std::map<std::string, std::function<void ()>> opts;
		opts["-c0"] =
		opts["-c" ] = [&] { compMode = CompMode::COMPRESS_C0; };
		opts["-c1"] =
		opts["-hc"] = [&] { compMode = CompMode::COMPRESS_C1; };
		opts["-d" ] = [&] { compMode = CompMode::DECOMPRESS; };
		opts["-y" ] = [&] { overwrite = true; };
		opts["-s" ] = [&] { mode |= LZ4MT_MODE_SEQUENTIAL; };
		opts["-m" ] = [&] { mode &= ~LZ4MT_MODE_SEQUENTIAL; };
		opts["--help"] = opts["-h" ] = opts["/?" ] = [&] {
			std::cerr << usage;
			exitFlag = true;
		};
		opts["-H" ] = [&] {
			std::cerr << usage << usage_advanced;
			exitFlag = true;
		};
		for(int i = 4; i <= 7; ++i) {
			opts[std::string("-B") + std::to_string(i)] = [&, i] {
				sd.bd.blockMaximumSize = static_cast<char>(i);
			};
		}
		opts["-BX"] = [&] { sd.flg.blockChecksum = 1; };
		opts["-Sx"] = [&] { sd.flg.streamChecksum = 0; };
		opts["-t" ] = [&] {
			compMode = CompMode::DECOMPRESS;
			outFilename = nullFilename;
		};

		for(int i = 0; i <= 1; ++i) {
			opts["-b" + std::to_string(i)] = [&, i] {
				if(i == 0) {
					compMode = CompMode::COMPRESS_C0;
				} else {
					compMode = CompMode::COMPRESS_C1;
				}
				benchmark.enable = true;
			};
		}
		for(int i = 1; i <= 9; ++i) {
			opts[std::string("-i") + std::to_string(i)] = [&, i] {
				benchmark.nIter = i;
				benchmark.enable = true;
			};
		}

		for(int iarg = 1; iarg < argc && !error && !exitFlag; ++iarg) {
			const auto a = std::string(argv[iarg]);
			const auto i = opts.find(a);
			if(opts.end() != i) {
				i->second();
			} else if(a[0] == '-') {
				std::cerr << "ERROR: bad switch [" << a << "]\n";
				error = true;
			} else if(benchmark.enable) {
				benchmark.files.push_back(a);
			} else if(inpFilename.empty()) {
				inpFilename = a;
			} else if(outFilename.empty()) {
				outFilename = a;
			} else {
				std::cerr << "ERROR: Bad argument [" << a << "]\n";
				error = true;
			}
		}

		if(cmpFilename(nullFilename, outFilename)) {
			nullWrite = true;
		}
	}

	bool isCompress() const {
		return CompMode::COMPRESS_C0 == compMode
		    || CompMode::COMPRESS_C1 == compMode;
	}

	bool isDecompress() const {
		return CompMode::DECOMPRESS == compMode;
	}

	static bool cmpFilename(const std::string& lhs, const std::string& rhs) {
		const auto pLhs = lhs.c_str();
		const auto pRhs = rhs.c_str();
#if defined(_WIN32)
		return 0 == _stricmp(pLhs, pRhs);
#else
		return 0 == strcmp(pLhs, pRhs);
#endif
	}

	enum class CompMode {
		  DECOMPRESS
		, COMPRESS_C0
		, COMPRESS_C1
	};

	bool error;
	bool exitFlag;
	CompMode compMode;
	Lz4MtStreamDescriptor sd;
	int mode;
	std::string inpFilename;
	std::string outFilename;
	bool nullWrite;
	bool overwrite;
	Lz4Mt::Benchmark benchmark;
};

} // anonymous namespace

int main(int argc, char* argv[]) {
	using namespace Lz4Mt::Cstdio;
	Option opt(argc, argv);

	if(opt.exitFlag) {
		exit(EXIT_SUCCESS);
	} else if(opt.error) {
		exit(EXIT_FAILURE);
	}

	Lz4MtContext ctx = lz4mtInitContext();
	ctx.mode			= static_cast<Lz4MtMode>(opt.mode);
	ctx.read			= read;
	ctx.readSeek		= readSeek;
	ctx.readEof			= readEof;
	ctx.write			= write;
	ctx.compress		= LZ4_compress_limitedOutput;
	ctx.compressBound	= LZ4_compressBound;
	ctx.decompress		= LZ4_decompress_safe;
	if(Option::CompMode::COMPRESS_C1 == opt.compMode) {
		ctx.compress = LZ4_compressHC_limitedOutput;
	}

	if(opt.benchmark.enable) {
		opt.benchmark.openIstream	= openIstream;
		opt.benchmark.closeIstream	= closeIstream;
		opt.benchmark.getFilesize	= getFilesize;
		opt.benchmark.measure(ctx, opt.sd);
		exit(EXIT_SUCCESS);
	}

	if(opt.inpFilename.empty()) {
		std::cerr << "ERROR: No input filename\n";
		exit(EXIT_FAILURE);
	}

	if(opt.outFilename.empty()) {
		if(opt.isCompress()) {
			if("stdin" == opt.inpFilename) {
				opt.outFilename = "stdout";
			} else {
				opt.outFilename = opt.inpFilename + LZ4MT_EXTENSION;
			}
		} else {
			std::cerr << "ERROR: No output filename\n";
			exit(EXIT_FAILURE);
		}
	}

	if(!openIstream(&ctx, opt.inpFilename)) {
		std::cerr << "ERROR: Can't open input file "
				  << "[" << opt.inpFilename << "]\n";
		exit(EXIT_FAILURE);
	}

	if(!opt.nullWrite && !opt.overwrite && fileExist(opt.outFilename)) {
		const int ch = [&]() -> int {
			if("stdin" != opt.inpFilename) {
				std::cerr << "Overwrite [y/N]? ";
				return std::cin.get();
			} else {
				return 0;
			}
		} ();
		if('y' != ch && 'Y' != ch) {
			std::cerr << "Abort: " << opt.outFilename << " already exists\n";
			exit(EXIT_FAILURE);
		}
	}

	if(!openOstream(&ctx, opt.outFilename, opt.nullWrite)) {
		std::cerr << "ERROR: Can't open output file ["
				  << opt.outFilename << "]\n";
		exit(EXIT_FAILURE);
	}

	const auto t0 = Clock::now();
	const auto e = [&]() -> Lz4MtResult {
		if(opt.isCompress()) {
			return lz4mtCompress(&ctx, &opt.sd);
		} else if(opt.isDecompress()) {
			return lz4mtDecompress(&ctx, &opt.sd);
		} else {
			assert(0);
			std::cerr << "ERROR: You must specify a switch -c or -d\n";
			return LZ4MT_RESULT_BAD_ARG;
		}
	} ();
	const auto t1 = Clock::now();

	closeOstream(&ctx);
	closeIstream(&ctx);

	const auto dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0).count();
	std::cerr << "Total time: " << dt << "sec\n";

	if(LZ4MT_RESULT_OK != e) {
		std::cerr << "ERROR: " << lz4mtResultToString(e) << "\n";
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}
<commit_msg>Add <string.h><commit_after>#include <cassert>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <string.h>
#include <vector>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "lz4.h"
#include "lz4hc.h"
#include "xxhash.h"
#include "lz4mt.h"
#include "lz4mt_benchmark.h"
#include "lz4mt_io_cstdio.h"
#include "test_clock.h"

namespace {

const char LZ4MT_EXTENSION[] = ".lz4";

const char usage[] =
	"usage :\n"
	"  lz4mt [switch...] <input> [output]\n"
	"switch :\n"
	"  -c0/-c  : Compress (lz4) (default)\n"
	"  -c1/-hc : Compress (lz4hc)\n"
	"  -d      : Decompress\n"
	"  -y      : Overwrite without prompting\n"
	"  -H      : Help (this text + advanced options)\n"
;

const char usage_advanced[] =
	"\nAdvanced options :\n"
	" -t       : decode test mode (do not output anything)\n"
	" -B#      : Block size [4-7](default : 7)\n"
	" -BX      : enable block checksum (default:disabled)\n"
	" -Sx      : disable stream checksum (default:enabled)\n"
	" -b#      : benchmark files, using # [0-1] compression level\n"
	" -i#      : iteration loops [1-9](default : 3), benchmark mode"
	             " only\n"
	"  -s      : Single thread mode\n"
	"  -m      : Multi thread mode (default)\n"
	"  input   : can be 'stdin' (pipe) or a filename\n"
	"  output  : can be 'stdout'(pipe) or a filename or 'null'\n"
;

struct Option {
	Option(int argc, char* argv[])
		: error(false)
		, exitFlag(false)
		, compMode(CompMode::COMPRESS_C0)
		, sd(lz4mtInitStreamDescriptor())
		, mode(LZ4MT_MODE_DEFAULT)
		, inpFilename()
		, outFilename()
		, nullWrite(false)
		, overwrite(false)
		, benchmark()
	{
		static const std::string nullFilename = "null";

		std::map<std::string, std::function<void ()>> opts;
		opts["-c0"] =
		opts["-c" ] = [&] { compMode = CompMode::COMPRESS_C0; };
		opts["-c1"] =
		opts["-hc"] = [&] { compMode = CompMode::COMPRESS_C1; };
		opts["-d" ] = [&] { compMode = CompMode::DECOMPRESS; };
		opts["-y" ] = [&] { overwrite = true; };
		opts["-s" ] = [&] { mode |= LZ4MT_MODE_SEQUENTIAL; };
		opts["-m" ] = [&] { mode &= ~LZ4MT_MODE_SEQUENTIAL; };
		opts["--help"] = opts["-h" ] = opts["/?" ] = [&] {
			std::cerr << usage;
			exitFlag = true;
		};
		opts["-H" ] = [&] {
			std::cerr << usage << usage_advanced;
			exitFlag = true;
		};
		for(int i = 4; i <= 7; ++i) {
			opts[std::string("-B") + std::to_string(i)] = [&, i] {
				sd.bd.blockMaximumSize = static_cast<char>(i);
			};
		}
		opts["-BX"] = [&] { sd.flg.blockChecksum = 1; };
		opts["-Sx"] = [&] { sd.flg.streamChecksum = 0; };
		opts["-t" ] = [&] {
			compMode = CompMode::DECOMPRESS;
			outFilename = nullFilename;
		};

		for(int i = 0; i <= 1; ++i) {
			opts["-b" + std::to_string(i)] = [&, i] {
				if(i == 0) {
					compMode = CompMode::COMPRESS_C0;
				} else {
					compMode = CompMode::COMPRESS_C1;
				}
				benchmark.enable = true;
			};
		}
		for(int i = 1; i <= 9; ++i) {
			opts[std::string("-i") + std::to_string(i)] = [&, i] {
				benchmark.nIter = i;
				benchmark.enable = true;
			};
		}

		for(int iarg = 1; iarg < argc && !error && !exitFlag; ++iarg) {
			const auto a = std::string(argv[iarg]);
			const auto i = opts.find(a);
			if(opts.end() != i) {
				i->second();
			} else if(a[0] == '-') {
				std::cerr << "ERROR: bad switch [" << a << "]\n";
				error = true;
			} else if(benchmark.enable) {
				benchmark.files.push_back(a);
			} else if(inpFilename.empty()) {
				inpFilename = a;
			} else if(outFilename.empty()) {
				outFilename = a;
			} else {
				std::cerr << "ERROR: Bad argument [" << a << "]\n";
				error = true;
			}
		}

		if(cmpFilename(nullFilename, outFilename)) {
			nullWrite = true;
		}
	}

	bool isCompress() const {
		return CompMode::COMPRESS_C0 == compMode
		    || CompMode::COMPRESS_C1 == compMode;
	}

	bool isDecompress() const {
		return CompMode::DECOMPRESS == compMode;
	}

	static bool cmpFilename(const std::string& lhs, const std::string& rhs) {
		const auto pLhs = lhs.c_str();
		const auto pRhs = rhs.c_str();
#if defined(_WIN32)
		return 0 == _stricmp(pLhs, pRhs);
#else
		return 0 == strcmp(pLhs, pRhs);
#endif
	}

	enum class CompMode {
		  DECOMPRESS
		, COMPRESS_C0
		, COMPRESS_C1
	};

	bool error;
	bool exitFlag;
	CompMode compMode;
	Lz4MtStreamDescriptor sd;
	int mode;
	std::string inpFilename;
	std::string outFilename;
	bool nullWrite;
	bool overwrite;
	Lz4Mt::Benchmark benchmark;
};

} // anonymous namespace

int main(int argc, char* argv[]) {
	using namespace Lz4Mt::Cstdio;
	Option opt(argc, argv);

	if(opt.exitFlag) {
		exit(EXIT_SUCCESS);
	} else if(opt.error) {
		exit(EXIT_FAILURE);
	}

	Lz4MtContext ctx = lz4mtInitContext();
	ctx.mode			= static_cast<Lz4MtMode>(opt.mode);
	ctx.read			= read;
	ctx.readSeek		= readSeek;
	ctx.readEof			= readEof;
	ctx.write			= write;
	ctx.compress		= LZ4_compress_limitedOutput;
	ctx.compressBound	= LZ4_compressBound;
	ctx.decompress		= LZ4_decompress_safe;
	if(Option::CompMode::COMPRESS_C1 == opt.compMode) {
		ctx.compress = LZ4_compressHC_limitedOutput;
	}

	if(opt.benchmark.enable) {
		opt.benchmark.openIstream	= openIstream;
		opt.benchmark.closeIstream	= closeIstream;
		opt.benchmark.getFilesize	= getFilesize;
		opt.benchmark.measure(ctx, opt.sd);
		exit(EXIT_SUCCESS);
	}

	if(opt.inpFilename.empty()) {
		std::cerr << "ERROR: No input filename\n";
		exit(EXIT_FAILURE);
	}

	if(opt.outFilename.empty()) {
		if(opt.isCompress()) {
			if("stdin" == opt.inpFilename) {
				opt.outFilename = "stdout";
			} else {
				opt.outFilename = opt.inpFilename + LZ4MT_EXTENSION;
			}
		} else {
			std::cerr << "ERROR: No output filename\n";
			exit(EXIT_FAILURE);
		}
	}

	if(!openIstream(&ctx, opt.inpFilename)) {
		std::cerr << "ERROR: Can't open input file "
				  << "[" << opt.inpFilename << "]\n";
		exit(EXIT_FAILURE);
	}

	if(!opt.nullWrite && !opt.overwrite && fileExist(opt.outFilename)) {
		const int ch = [&]() -> int {
			if("stdin" != opt.inpFilename) {
				std::cerr << "Overwrite [y/N]? ";
				return std::cin.get();
			} else {
				return 0;
			}
		} ();
		if('y' != ch && 'Y' != ch) {
			std::cerr << "Abort: " << opt.outFilename << " already exists\n";
			exit(EXIT_FAILURE);
		}
	}

	if(!openOstream(&ctx, opt.outFilename, opt.nullWrite)) {
		std::cerr << "ERROR: Can't open output file ["
				  << opt.outFilename << "]\n";
		exit(EXIT_FAILURE);
	}

	const auto t0 = Clock::now();
	const auto e = [&]() -> Lz4MtResult {
		if(opt.isCompress()) {
			return lz4mtCompress(&ctx, &opt.sd);
		} else if(opt.isDecompress()) {
			return lz4mtDecompress(&ctx, &opt.sd);
		} else {
			assert(0);
			std::cerr << "ERROR: You must specify a switch -c or -d\n";
			return LZ4MT_RESULT_BAD_ARG;
		}
	} ();
	const auto t1 = Clock::now();

	closeOstream(&ctx);
	closeIstream(&ctx);

	const auto dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0).count();
	std::cerr << "Total time: " << dt << "sec\n";

	if(LZ4MT_RESULT_OK != e) {
		std::cerr << "ERROR: " << lz4mtResultToString(e) << "\n";
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include "circuits/element.h"
#include "matrix/solve.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

#define DEBUG

static const int MAX_LINHA = 80;
static const int MAX_NOME = 11;
static const int MAX_ELEM = 50;

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

    cout << endl;
    cout << "Modified Nodal Analysis" << endl;
    cout << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)" << endl;
    cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl;
    cout << endl;

    ifstream netlistFile;
    string filepath;

    switch(argc) {
        case 1: {
            cout << "Enter path to netlist file: ";
            cin >> filepath;
            break;
        }
        case 2: {
            filepath = argv[1];
            break;
        }
        default:
            cerr << "FAILURE: Too much information!" << endl;
            #if defined (WIN32) || defined(_WIN32)
	        cin.get();
            #endif
            exit(EXIT_FAILURE);
    }

    netlistFile.open(filepath.c_str(), ifstream::in);
    if(!netlistFile.is_open()){
        cerr << "FAILURE: Cannot open file " << filepath << endl;
        #if defined (WIN32) || defined(_WIN32)
	    cin.get();
        #endif
        exit(EXIT_FAILURE);
    }

    string txt;
    vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */
    lista[0] = "0";
    vector<Element> netlist(MAX_ELEM);

    int nv=0, /* Variaveis */
        nn=0; /* Nos */

    /* Foram colocados limites nos formatos de leitura para alguma protecao
       contra excesso de caracteres nestas variaveis */
    char tipo;

    double g,
           Yn[MAX_NOS+1][MAX_NOS+2];

    cout << "Lendo netlist:" << endl;
    getline(netlistFile, txt);
    cout << "Titulo: " << txt;
    while (getline(netlistFile, txt)) {
        Element::ne++; /* Nao usa o netlist[0] */
        if (Element::ne>MAX_ELEM) {
            cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl;
            #if defined (WIN32) || defined(_WIN32)
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        netlist[Element::ne] = Element(txt, nv, lista);
    }
    netlistFile.close();

    /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */
    nn=nv;
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') {
            nv++;
            if (nv>MAX_NOS) {
                cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl;
                #if defined (WIN32) || defined(_WIN32)
	            cin.get();
                #endif
                exit(EXIT_FAILURE);
            }
            lista[nv] = "j"; /* Tem espaco para mais dois caracteres */
            lista[nv].append( netlist[i].nome );
            netlist[i].x=nv;
        }
        else if (tipo=='H') {
            nv=nv+2;
            if (nv>MAX_NOS) {
                cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl;
                #if defined (WIN32) || defined(_WIN32)
	            cin.get();
                #endif
                exit(EXIT_FAILURE);
            }
            lista[nv-1] = "jx";
            lista[nv-1].append(netlist[i].nome);
            netlist[i].x=nv-1;
            lista[nv] = "jy";
            lista[nv].append( netlist[i].nome );
            netlist[i].y=nv;
        }
    }
    cout << endl;

    /* Lista tudo */
    cout << "Variaveis internas: " << endl;
    for (int i=0; i<=nv; i++)
        cout << i << " -> " << lista[i] << endl;
    cout << endl;

    cout << "Netlist interno final" << endl;
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='R' || tipo=='I' || tipo=='V') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl;
        }
        else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " "
                 << netlist[i].c << " " << netlist[i].d   << " " << netlist[i].valor << endl;
        }
        else if (tipo=='O') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " "
                 << netlist[i].c << " " << netlist[i].d   << endl;
        }
        if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O')
            cout << "Corrente jx: " << netlist[i].x << endl;
        else if (tipo=='H')
            cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl;
    }
    cout << endl;

    /* Monta o sistema nodal modificado */
    cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << Element::ne << " elementos" << endl;
    cout << endl;

    /* Zera sistema */
    for (int i=0; i<=nv; i++) {
        for (int j=0; j<=nv+1; j++)
            Yn[i][j]=0;
    }

    /* Monta estampas */
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='R') {
            g=1/netlist[i].valor;
            Yn[netlist[i].a][netlist[i].a]+=g;
            Yn[netlist[i].b][netlist[i].b]+=g;
            Yn[netlist[i].a][netlist[i].b]-=g;
            Yn[netlist[i].b][netlist[i].a]-=g;
        }
        else if (tipo=='G') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].c]+=g;
            Yn[netlist[i].b][netlist[i].d]+=g;
            Yn[netlist[i].a][netlist[i].d]-=g;
            Yn[netlist[i].b][netlist[i].c]-=g;
        }
        else if (tipo=='I') {
            g=netlist[i].valor;
            Yn[netlist[i].a][nv+1]-=g;
            Yn[netlist[i].b][nv+1]+=g;
        }
        else if (tipo=='V') {
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].a]-=1;
            Yn[netlist[i].x][netlist[i].b]+=1;
            Yn[netlist[i].x][nv+1]-=netlist[i].valor;
        }
        else if (tipo=='E') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].a]-=1;
            Yn[netlist[i].x][netlist[i].b]+=1;
            Yn[netlist[i].x][netlist[i].c]+=g;
            Yn[netlist[i].x][netlist[i].d]-=g;
        }
        else if (tipo=='F') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].x]+=g;
            Yn[netlist[i].b][netlist[i].x]-=g;
            Yn[netlist[i].c][netlist[i].x]+=1;
            Yn[netlist[i].d][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].c]-=1;
            Yn[netlist[i].x][netlist[i].d]+=1;
        }
        else if (tipo=='H') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].y]+=1;
            Yn[netlist[i].b][netlist[i].y]-=1;
            Yn[netlist[i].c][netlist[i].x]+=1;
            Yn[netlist[i].d][netlist[i].x]-=1;
            Yn[netlist[i].y][netlist[i].a]-=1;
            Yn[netlist[i].y][netlist[i].b]+=1;
            Yn[netlist[i].x][netlist[i].c]-=1;
            Yn[netlist[i].x][netlist[i].d]+=1;
            Yn[netlist[i].y][netlist[i].x]+=g;
        }
        else if (tipo=='O') {
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].c]+=1;
            Yn[netlist[i].x][netlist[i].d]-=1;
        }

#ifdef DEBUG
        /* Opcional: Mostra o sistema apos a montagem da estampa */
        cout << "Sistema apos a estampa de " << netlist[i].nome << endl;
        for (int k=1; k<=nv; k++) {
            for (int j=1; j<=nv+1; j++)
                if (Yn[k][j]!=0){
                    cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos;
                    cout << Yn[k][j] << " ";
                }
                else cout << " ... ";
            cout << endl;
        }
        cout << endl;
#endif

    }
    /* Resolve o sistema */
    if (solve(nv, Yn)) {
        cout << "FAILURE: Could not solve!" << endl;
        #if defined (WIN32) || defined(_WIN32)
	    cin.get();
        #endif
        exit(EXIT_FAILURE);
    }

#ifdef DEBUG
    /* Opcional: Mostra o sistema resolvido */
    cout << "Sistema resolvido:" << endl;
    for (int i=1; i<=nv; i++) {
        for (int j=1; j<=nv+1; j++)
            if (Yn[i][j]!=0){
                cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos;
                cout << Yn[i][j] << " ";
            }
            else cout << " ... ";
        cout << endl;
    }
    cout << endl;
#endif

    /* Mostra solucao */
    cout << "Solucao:" << endl;
    txt = "Tensao";
    for (int i=1; i<=nv; i++) {
        if (i==nn+1)
            txt = "Corrente";
        cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl;
    }

    #if defined (WIN32) || defined(_WIN32)
	cin.get();
    #endif
}

<commit_msg>Implements polite exit :crown:<commit_after>#include "circuits/element.h"
#include "matrix/solve.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

#define DEBUG

static const int MAX_LINHA = 80;
static const int MAX_NOME = 11;
static const int MAX_ELEM = 50;

void exitPolitely(int exitCode) {
	#if defined (WIN32) || defined(_WIN32)
	cout << endl << "Press any key to exit...";
	cin.get();
	cin.get();
	#endif
	exit(exitCode);
}

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

    cout << endl;
    cout << "Modified Nodal Analysis" << endl;
    cout << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)" << endl;
    cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl;
    cout << endl;

    ifstream netlistFile;
    string filepath;

    switch(argc) {
        case 1: {
            cout << "Enter path to netlist file: ";
            cin >> filepath;
            break;
        }
        case 2: {
            filepath = argv[1];
            break;
        }
        default:
            cerr << "FAILURE: Too much information!" << endl;
            exitPolitely(EXIT_FAILURE);
    }

    netlistFile.open(filepath.c_str(), ifstream::in);
    if(!netlistFile.is_open()){
        cerr << "FAILURE: Cannot open file " << filepath << endl;
		exitPolitely(EXIT_FAILURE);
    }

    string txt;
    vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */
    lista[0] = "0";
    vector<Element> netlist(MAX_ELEM);

    int nv=0, /* Variaveis */
        nn=0; /* Nos */

    /* Foram colocados limites nos formatos de leitura para alguma protecao
       contra excesso de caracteres nestas variaveis */
    char tipo;

    double g,
           Yn[MAX_NOS+1][MAX_NOS+2];

    cout << "Lendo netlist:" << endl;
    getline(netlistFile, txt);
    cout << "Titulo: " << txt;
    while (getline(netlistFile, txt)) {
        Element::ne++; /* Nao usa o netlist[0] */
        if (Element::ne>MAX_ELEM) {
            cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl;
			exitPolitely(EXIT_FAILURE);
        }
        netlist[Element::ne] = Element(txt, nv, lista);
    }
    netlistFile.close();

    /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */
    nn=nv;
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') {
            nv++;
            if (nv>MAX_NOS) {
                cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl;
                exitPolitely(EXIT_FAILURE);
            }
            lista[nv] = "j"; /* Tem espaco para mais dois caracteres */
            lista[nv].append( netlist[i].nome );
            netlist[i].x=nv;
        }
        else if (tipo=='H') {
            nv=nv+2;
            if (nv>MAX_NOS) {
                cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl;
                exitPolitely(EXIT_FAILURE);
            }
            lista[nv-1] = "jx";
            lista[nv-1].append(netlist[i].nome);
            netlist[i].x=nv-1;
            lista[nv] = "jy";
            lista[nv].append( netlist[i].nome );
            netlist[i].y=nv;
        }
    }
    cout << endl;

    /* Lista tudo */
    cout << "Variaveis internas: " << endl;
    for (int i=0; i<=nv; i++)
        cout << i << " -> " << lista[i] << endl;
    cout << endl;

    cout << "Netlist interno final" << endl;
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='R' || tipo=='I' || tipo=='V') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl;
        }
        else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " "
                 << netlist[i].c << " " << netlist[i].d   << " " << netlist[i].valor << endl;
        }
        else if (tipo=='O') {
            cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " "
                 << netlist[i].c << " " << netlist[i].d   << endl;
        }
        if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O')
            cout << "Corrente jx: " << netlist[i].x << endl;
        else if (tipo=='H')
            cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl;
    }
    cout << endl;

    /* Monta o sistema nodal modificado */
    cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << Element::ne << " elementos" << endl;
    cout << endl;

    /* Zera sistema */
    for (int i=0; i<=nv; i++) {
        for (int j=0; j<=nv+1; j++)
            Yn[i][j]=0;
    }

    /* Monta estampas */
    for (int i=1; i<=Element::ne; i++) {
        tipo=netlist[i].nome[0];
        if (tipo=='R') {
            g=1/netlist[i].valor;
            Yn[netlist[i].a][netlist[i].a]+=g;
            Yn[netlist[i].b][netlist[i].b]+=g;
            Yn[netlist[i].a][netlist[i].b]-=g;
            Yn[netlist[i].b][netlist[i].a]-=g;
        }
        else if (tipo=='G') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].c]+=g;
            Yn[netlist[i].b][netlist[i].d]+=g;
            Yn[netlist[i].a][netlist[i].d]-=g;
            Yn[netlist[i].b][netlist[i].c]-=g;
        }
        else if (tipo=='I') {
            g=netlist[i].valor;
            Yn[netlist[i].a][nv+1]-=g;
            Yn[netlist[i].b][nv+1]+=g;
        }
        else if (tipo=='V') {
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].a]-=1;
            Yn[netlist[i].x][netlist[i].b]+=1;
            Yn[netlist[i].x][nv+1]-=netlist[i].valor;
        }
        else if (tipo=='E') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].a]-=1;
            Yn[netlist[i].x][netlist[i].b]+=1;
            Yn[netlist[i].x][netlist[i].c]+=g;
            Yn[netlist[i].x][netlist[i].d]-=g;
        }
        else if (tipo=='F') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].x]+=g;
            Yn[netlist[i].b][netlist[i].x]-=g;
            Yn[netlist[i].c][netlist[i].x]+=1;
            Yn[netlist[i].d][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].c]-=1;
            Yn[netlist[i].x][netlist[i].d]+=1;
        }
        else if (tipo=='H') {
            g=netlist[i].valor;
            Yn[netlist[i].a][netlist[i].y]+=1;
            Yn[netlist[i].b][netlist[i].y]-=1;
            Yn[netlist[i].c][netlist[i].x]+=1;
            Yn[netlist[i].d][netlist[i].x]-=1;
            Yn[netlist[i].y][netlist[i].a]-=1;
            Yn[netlist[i].y][netlist[i].b]+=1;
            Yn[netlist[i].x][netlist[i].c]-=1;
            Yn[netlist[i].x][netlist[i].d]+=1;
            Yn[netlist[i].y][netlist[i].x]+=g;
        }
        else if (tipo=='O') {
            Yn[netlist[i].a][netlist[i].x]+=1;
            Yn[netlist[i].b][netlist[i].x]-=1;
            Yn[netlist[i].x][netlist[i].c]+=1;
            Yn[netlist[i].x][netlist[i].d]-=1;
        }

#ifdef DEBUG
        /* Opcional: Mostra o sistema apos a montagem da estampa */
        cout << "Sistema apos a estampa de " << netlist[i].nome << endl;
        for (int k=1; k<=nv; k++) {
            for (int j=1; j<=nv+1; j++)
                if (Yn[k][j]!=0){
                    cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos;
                    cout << Yn[k][j] << " ";
                }
                else cout << " ... ";
            cout << endl;
        }
        cout << endl;
#endif

    }
    /* Resolve o sistema */
    if (solve(nv, Yn)) {
        cout << "FAILURE: Could not solve!" << endl;
        exitPolitely(EXIT_FAILURE);
    }

#ifdef DEBUG
    /* Opcional: Mostra o sistema resolvido */
    cout << "Sistema resolvido:" << endl;
    for (int i=1; i<=nv; i++) {
        for (int j=1; j<=nv+1; j++)
            if (Yn[i][j]!=0){
                cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos;
                cout << Yn[i][j] << " ";
            }
            else cout << " ... ";
        cout << endl;
    }
    cout << endl;
#endif

    /* Mostra solucao */
    cout << "Solucao:" << endl;
    txt = "Tensao";
    for (int i=1; i<=nv; i++) {
        if (i==nn+1)
            txt = "Corrente";
        cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl;
    }
	exitPolitely(EXIT_SUCCESS);
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
 *
 * 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 3 of the License, 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdlib>    // EXIT_SUCCESS, EXIT_FAILURE
#include <pybind11/embed.h>

#include "item.hpp"
#include "utils.hpp"
#include "components/command_line.hpp"
#include "components/searcher.hpp"
#include "version.hpp"

namespace py = pybind11;

int main(int argc, char *argv[])
{
    using valid_opts = std::initializer_list<string>;

    const auto main = command_line::option_group("Main", "necessarily inclusive arguments; at least one required")
        ("-a", "--author",    "Specify authors",   "AUTHOR")
        ("-t", "--title",     "Specify title",     "TITLE")
        ("-s", "--serie",     "Specify serie",     "SERIE")
        ("-p", "--publisher", "Specify publisher", "PUBLISHER");

    const auto excl = command_line::option_group("Exclusive", "cannot be combined with any other arguments")
        ("-d", "--ident",     "Specify an item identification (such as DOI, URL, etc.)", "IDENT");

    const auto exact = command_line::option_group("Exact", "all are optional")
        ("-y", "--year",      "Specify year of release. "
                              "A prefix modifier can be used to broaden the search. "
                              "Available prefixes are <, >, <=, >=.", "YEAR")
        ("-L", "--language",  "Specify text language",  "LANG")
        ("-e", "--edition",   "Specify item edition",   "EDITION")
        ("-E", "--extension", "Specify item extension", "EXT",
            valid_opts{"epub", "pdf", "djvu"})
        ("-i", "--isbn",      "Specify item ISBN", "ISBN");

    const auto misc = command_line::option_group("Miscellaneous")
        ("-h", "--help",      "Display this text and exit")
        ("-v", "--version",   "Print version information (" + build_info_short + ")")
        ("-D", "--debug",     "Set logging level to debug");

    const command_line::groups groups = {main, excl, exact, misc};

    auto logger = logger::create("main");
    logger->set_pattern("%l: %v");
    logger->set_level(spdlog::level::warn);
    spdlog::register_logger(logger);

    try {
        /* Parse command line arguments. */
        string progname = argv[0];
        vector<string> args(argv + 1, argv + argc);

        auto cli = cliparser::make(std::move(progname), std::move(groups));
        cli->process_arguments(args);

        if (cli->has("debug"))
            logger->set_level(spdlog::level::debug);

        logger->debug("the mighty eldwyrm has been summoned!");

        if (cli->has("help")) {
            cli->usage();
            return EXIT_SUCCESS;
        } else if (cli->has("version")) {
            print_build_info();
            return EXIT_SUCCESS;
        } else if (args.empty()) {
            cli->usage();
            return EXIT_FAILURE;
        }

        cli->validate_arguments();
        const auto err = utils::validate_download_dir(cli->get(0));
        if (err) {
            logger->error("invalid download directory: {}.", err.message());
            return EXIT_FAILURE;
        }

        /*
         * Start the Python interpreter and keep it alive until
         * program termination.
         */
        py::scoped_interpreter guard{};

        const bookwyrm::item wanted(cli);
        bookwyrm::searcher(wanted).search();

    } catch (const cli_error &err) {
        logger->error(err.what() + string("; see --help"));
        return EXIT_FAILURE;
    }

    logger->debug("terminating successfully...");
    return EXIT_SUCCESS;
}
<commit_msg>"hath" is cooler than "has"<commit_after>/*
 * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
 *
 * 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 3 of the License, 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdlib>    // EXIT_SUCCESS, EXIT_FAILURE
#include <pybind11/embed.h>

#include "item.hpp"
#include "utils.hpp"
#include "components/command_line.hpp"
#include "components/searcher.hpp"
#include "version.hpp"

namespace py = pybind11;

int main(int argc, char *argv[])
{
    using valid_opts = std::initializer_list<string>;

    const auto main = command_line::option_group("Main", "necessarily inclusive arguments; at least one required")
        ("-a", "--author",    "Specify authors",   "AUTHOR")
        ("-t", "--title",     "Specify title",     "TITLE")
        ("-s", "--serie",     "Specify serie",     "SERIE")
        ("-p", "--publisher", "Specify publisher", "PUBLISHER");

    const auto excl = command_line::option_group("Exclusive", "cannot be combined with any other arguments")
        ("-d", "--ident",     "Specify an item identification (such as DOI, URL, etc.)", "IDENT");

    const auto exact = command_line::option_group("Exact", "all are optional")
        ("-y", "--year",      "Specify year of release. "
                              "A prefix modifier can be used to broaden the search. "
                              "Available prefixes are <, >, <=, >=.", "YEAR")
        ("-L", "--language",  "Specify text language",  "LANG")
        ("-e", "--edition",   "Specify item edition",   "EDITION")
        ("-E", "--extension", "Specify item extension", "EXT",
            valid_opts{"epub", "pdf", "djvu"})
        ("-i", "--isbn",      "Specify item ISBN", "ISBN");

    const auto misc = command_line::option_group("Miscellaneous")
        ("-h", "--help",      "Display this text and exit")
        ("-v", "--version",   "Print version information (" + build_info_short + ")")
        ("-D", "--debug",     "Set logging level to debug");

    const command_line::groups groups = {main, excl, exact, misc};

    auto logger = logger::create("main");
    logger->set_pattern("%l: %v");
    logger->set_level(spdlog::level::warn);
    spdlog::register_logger(logger);

    try {
        /* Parse command line arguments. */
        string progname = argv[0];
        vector<string> args(argv + 1, argv + argc);

        auto cli = cliparser::make(std::move(progname), std::move(groups));
        cli->process_arguments(args);

        if (cli->has("debug"))
            logger->set_level(spdlog::level::debug);

        logger->debug("the mighty eldwyrm hath been summoned!");

        if (cli->has("help")) {
            cli->usage();
            return EXIT_SUCCESS;
        } else if (cli->has("version")) {
            print_build_info();
            return EXIT_SUCCESS;
        } else if (args.empty()) {
            cli->usage();
            return EXIT_FAILURE;
        }

        cli->validate_arguments();
        const auto err = utils::validate_download_dir(cli->get(0));
        if (err) {
            logger->error("invalid download directory: {}.", err.message());
            return EXIT_FAILURE;
        }

        /*
         * Start the Python interpreter and keep it alive until
         * program termination.
         */
        py::scoped_interpreter guard{};

        const bookwyrm::item wanted(cli);
        bookwyrm::searcher(wanted).search();

    } catch (const cli_error &err) {
        logger->error(err.what() + string("; see --help"));
        return EXIT_FAILURE;
    }

    logger->debug("terminating successfully...");
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <irrlicht.h>

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;

struct MyEventReceiver : IEventReceiver
{
  bool OnEvent(const SEvent &event)
  {
    // If input is of keyboard type  (KEY_INPUT)
    // and a pressed key
    // and the key is ESCAPE
    if (event.EventType == EET_KEY_INPUT_EVENT &&
        event.KeyInput.PressedDown &&
        event.KeyInput.Key == KEY_ESCAPE)
      exit(0);

    return false;
  }
};

int main()
{
  // Event Receiver
  MyEventReceiver receiver;
  // Initialization of the rendering system and window
  IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                        ic::dimension2d<u32>(640, 480),
                                        16, false, false, false, &receiver);

  iv::IVideoDriver  *driver = device->getVideoDriver();
  is::ISceneManager *smgr = device->getSceneManager();

//  // Loading a mesh
//  is::IAnimatedMesh *mesh = smgr->getMesh("data/tris.md2");

//  // Creating node from mesh
//  is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);

  is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya();
//  camera->setTarget(node->getPosition());

  while(device->run())
  {
    driver->beginScene(true, true, iv::SColor(0,50,100,255));

    // Draw the scene
    smgr->drawAll();
    //
    driver->endScene();
  }
  device->drop();

  return 0;
}
<commit_msg>ENH: first keyboard input for the character movement<commit_after>#include <irrlicht.h>

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;

class MyEventReceiver : public IEventReceiver
{
public:
    bool OnEvent(const SEvent &event)
    {
        // If input is of keyboard type  (KEY_INPUT)
        // and a pressed key
        // and the key is ESCAPE
        if (event.EventType == EET_KEY_INPUT_EVENT &&
                event.KeyInput.PressedDown &&
                event.KeyInput.Key == KEY_ESCAPE)
            exit(0);
        if (event.EventType == irr::EET_KEY_INPUT_EVENT)
            KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
        return false;
    }

    virtual bool IsKeyDown(EKEY_CODE keyCode) const
    {
        return KeyIsDown[keyCode];
    }
    MyEventReceiver()
    {
        for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)
            KeyIsDown[i] = false;
    }
private:
    //store the state of each key
    bool KeyIsDown[KEY_KEY_CODES_COUNT];
};

int main()
{
    // Event Receiver
    MyEventReceiver receiver;
    // Initialization of the rendering system and window
    IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                          ic::dimension2d<u32>(640, 480),
                                          16, false, false, false, &receiver);

    iv::IVideoDriver  *driver = device->getVideoDriver();
    is::ISceneManager *smgr = device->getSceneManager();

    //  // Loading a mesh
    is::IAnimatedMesh *mesh = smgr->getMesh("data/test_with_bones_and_skinweights_and_modif.x");

    //  // Creating node from mesh
    is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);
    //ic::vector3df scale(0.005,0.005,0.005);
    //node->setScale( scale );

    is::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS();
    //camera->setTarget(node->getPosition());
    //is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node, ic::vector3df(0,0,0),ic::vector3df(0,0,5),-1, true);

    // In order to do framerate independent movement, we have to know
    // how long it was since the last frame
    u32 then = device->getTimer()->getTime();

    // This is the movemen speed in units per second.
    const f32 movementSpeed = 5.f;

    while(device->run())
    {
        const u32 now = device->getTimer()->getTime();
        const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds
        int lastFPS = -1;
        then = now;
        driver->beginScene(true, true, iv::SColor(0,50,100,255));

        core::vector3df nodePosition = node->getPosition();

        if(receiver.IsKeyDown(irr::KEY_KEY_Q))
            nodePosition.X -= movementSpeed * frameDeltaTime;
        else if(receiver.IsKeyDown(irr::KEY_KEY_D))
            nodePosition.X += movementSpeed * frameDeltaTime;

        node->setPosition(nodePosition);

        // Draw the scene
        smgr->drawAll();
        driver->endScene();
        int fps = driver->getFPS();
        if (lastFPS != fps)
        {
            core::stringw tmp(L"Movement Example - Irrlicht Engine [");
            tmp += driver->getName();
            tmp += L"] fps: ";
            tmp += fps;

            device->setWindowCaption(tmp.c_str());
            lastFPS = fps;
        }
    }
    device->drop();

    return 0;
}
<|endoftext|>


<commit_before>#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/rect.h"
#include "geom/vector.h"
#include "geom/point.h"
#include "image/image.h"
#include "node/group/simple.h"
#include "node/solid/sphere.h"
#include "node/solid/infinite_plane.h"
#include "renderer/settings.h"
#include "renderer/serial/serial.h"
#include "renderer/parallel/parallel.h"
#include "supersampling/random.h"
#include "world/world.h"

#include <iostream>
#include <cmath>

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.max_thread_count = 4;
	settings.tile_size = Vector2i(100, 100);
	settings.max_sample_count = 20;
	settings.adaptive_sample_step = 2;

	SimpleGroup scene;

	InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0));
	scene.add(infinite_plane);

	Sphere* spheres[100];
	int i = 0;

	for (float x = -3.0; x < 3.0; x += 0.5)
	for (float z = 0.0; z < 6.0; z += 0.5)
	{
		spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0);
		scene.add(*spheres[i]);
		i++;
	}

	PerspectiveCamera camera(
		Point3(0.0, 0.75, -2.0),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		settings.whole_area.get_aspect_ratio(),
		M_PI/2.0);

	World world;
	world.scene = &scene;
	world.camera = &camera;

	CosineDebuggerEngine engine;
	ParallelRenderer renderer;
	//SerialRenderer renderer;
	RandomSuperSampling super_sampling(true);

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write(std::string("output.png"));

	return 0;
}
<commit_msg>Adaptive thread count<commit_after>#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/rect.h"
#include "geom/vector.h"
#include "geom/point.h"
#include "image/image.h"
#include "node/group/simple.h"
#include "node/solid/sphere.h"
#include "node/solid/infinite_plane.h"
#include "renderer/settings.h"
#include "renderer/serial/serial.h"
#include "renderer/parallel/parallel.h"
#include "supersampling/random.h"
#include "world/world.h"

#include <iostream>
#include <cmath>
#include <thread>

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.max_thread_count = std::thread::hardware_concurrency();
	settings.tile_size = Vector2i(100, 100);
	settings.max_sample_count = 20;
	settings.adaptive_sample_step = 2;

	SimpleGroup scene;

	InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0));
	scene.add(infinite_plane);

	Sphere* spheres[100];
	int i = 0;

	for (float x = -3.0; x < 3.0; x += 0.5)
	for (float z = 0.0; z < 6.0; z += 0.5)
	{
		spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0);
		scene.add(*spheres[i]);
		i++;
	}

	PerspectiveCamera camera(
		Point3(0.0, 0.75, -2.0),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		settings.whole_area.get_aspect_ratio(),
		M_PI/2.0);

	World world;
	world.scene = &scene;
	world.camera = &camera;

	CosineDebuggerEngine engine;
	ParallelRenderer renderer;
	//SerialRenderer renderer;
	RandomSuperSampling super_sampling(true);

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write(std::string("output.png"));

	return 0;
}
<|endoftext|>