<commit_before>/*
 * main.cpp
 *
 * "engine" of the game for now, subject to change
 * handles menu+options at start
 * generates game world for player
 * manages game interactions
*/

#include <iostream>
#include <algorithm>
#include "Entity.h"
#include "Monster.h"
#include "Player.h"
#include "Skill.h"
#include "Usable.h"
#include "Dungeon.h"

void dungeonSetupTest(std::string playerName);
void printTimeInfo(Dungeon& d);
void start(Dungeon& d);

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

	std::cout << "SOS! Surviving Open Source as a game experience" << std::endl;
	std::cout << "Currently an active project for CSCI2963" << std::endl;

	std::string playerName;
	std::cout << "Please enter a name:" << std::endl;
	std::cin >> playerName;
	Dungeon dastardlyDungeon(playerName);
	std::cout << std::endl << std::endl;
	std::cout << "Welcome to SOS, " << playerName << " the world in which you are the programmer and your groupmates are" << std::endl;
	std::cout << "trying their best, but are only making your life harder." << std::endl;
	std::cout << "You need to pull off a good grade and fix all the code that they create. Whatever" << std::endl;
	std::cout << "free time you have is up to you to use to the utmost. Don't forget studying and free time" << std::endl;
	std::cout << "are important!" << std::endl;
	//dungeonSetupTest(playerName);
	start(dastardlyDungeon);
	return 0;
}

void printTimeInfo(Dungeon& d){
	std::cout << d.getDay() << " " << d.getDaysPassed() << " " << d.numHrs() << std::endl;
}

void dungeonSetupTest(std::string playerName){
	Dungeon d(playerName);
	d.addPlayerSkill("HI", 4);
	d.addPlayerSkill("Yo", 4);
	d.addPlayerSkill("MEW 2", 4);
	d.addPlayerSkill("MEW 5", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("HI", 4);
	d.addPlayerSkill("Yo", 4);
	d.addPlayerSkill("MEW 2", 4);
	d.addPlayerSkill("MEW 5", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	std::cout << d.numHrs() << std::endl;
	std::cout << d.getDay() << std::endl;
	d.subtractHrs(49);
	std::cout << d.numHrs() << std::endl;
	std::cout << d.getDay() << std::endl;
	d.subtractHrs(10);
	std::cout << d.numHrs() << std::endl;
	d.subtractHrs(10);
	std::cout << d.numHrs() << std::endl;
	std::cout << d << std::endl;
}

void start(Dungeon& d){
	std::string cmd;
	while(d.getDaysPassed() < 30){
		std::cout << "enter what you want to do next: " << std::endl;
		std::cin >> cmd;
		std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
		if(cmd == "t" || cmd == "T"){
			printTimeInfo(d);
		}
		if(cmd == "study" || cmd == "s"){
			int hrs;
			std::cout << "For How many hours (int)? " << std::endl;
			std::cin >> hrs;
			while(std::cin.fail() || hrs > d.numHrs()){
				std::cout << "invalid input!" << std::endl;
				std::cin.clear();
				std::cin.ignore(10000, '\n');
				std::cin >> hrs;
			}
			//Post code
			d.subtractHrs(hrs);
			continue;
		} else if (cmd == "f" || cmd == "fight"){
			std::cout << *(d.getMonster()) << std::endl;
			d.subtractHrs(24);
		}else if(cmd != "t"){
			std::cout << "Unknown command try again" << std::endl;
			continue;
		}
	}

}

<commit_msg>Made some changes to 'main.cpp'<commit_after>/** main.cpp
 *  This file contains the main method for the game. It handles menu
 *  options, generates game world, and manages game interactions.
 */

#include <iostream>
#include <algorithm>
#include "Entity.h"
#include "Monster.h"
#include "Player.h"
#include "Skill.h"
#include "Usable.h"
#include "Dungeon.h"

// ----------------------------------------------------------------

void dungeonSetupTest(std::string playerName);
void printTimeInfo(Dungeon& d);
void run(Dungeon& d);   // I renamed it run because it seemed logical. NBD.

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

	std::cout << "SOS! Surviving Open Source as a game experience" << std::endl;
	std::cout << "Currently an active project for CSCI2963" << std::endl;

	std::string playerName;
	std::cout << "Please enter a name: ";
	std::cin >> playerName;
	Dungeon dastardlyDungeon(playerName);

	/*
	 *  This is a paragraph, so I think it looks cleaner if we do it like
	 *  this. I also tried to shorten the length of the lines a little to
	 *  make it prettier in the terminal.
	 */
	std::cout <<
		std::endl << "Welcome to SOS, " << playerName << ", the world in which you are the" <<
		std::endl << "programmer and your groupmates are trying their best but are" <<
		std::endl << "making your life harder. You need to pull off a good grade and" <<
		std::endl << "and fix all of the code that they create. You'll be able to " <<
		std::endl << "check the clock, fix their monstrous mistakes, and study. Time " <<
		std::endl << "is yours to control, but use it carefully. Good Luck!" << std::endl;

	/*
	 *  I had Andrew (he's my roommate, Ryan) test out the game. His
	 *  biggest complaint was not knowing what to type for action. I also
	 *  added a "Help" and "Quit" command. We can get rid of the quit
	 *  if you think it's better to not have it.
	 */
	std::cout << std::endl << "These are your options for input:" << std::endl <<
		"  \"Fight\" or \"f\" -> fight a monster" << std::endl <<
		"  \"Help\" or \"h\" -> print a the command list" << std::endl <<
		"  \"Quit\" or \"q\" -> quit the game before 30 days" << std::endl <<
		"  \"Study\" or \"s\" -> input a number greater than 0" << std::endl <<
		"  \"Time\" or \"t\" -> print the current time info" << std::endl << std::endl;

	// std::cout << "Welcome to SOS, " << playerName << " the world in which you are the programmer and your groupmates are" << std::endl;
	// std::cout << "trying their best, but are only making your life harder." << std::endl;
	// std::cout << "You need to pull off a good grade and fix all the code that they create. Whatever" << std::endl;
	// std::cout << "free time you have is up to you to use to the utmost. Don't forget studying and free time" << std::endl;
	// std::cout << "are important!" << std::endl << std::endl;
	//dungeonSetupTest(playerName);

	run(dastardlyDungeon);
	return 0;
}

// ----------------------------------------------------------------

/*
 *  Do we need this? I only saw it used in the "time" command. I changed
 *  what it printed a little, and I don't really see a need for this.
 */
void printTimeInfo(Dungeon& d){
	std::cout << d.getDay() << " " << d.getDaysPassed() << " " << d.numHrs() << std::endl;
}

// ----------------------------------------------------------------

/*
 *  Do we need this still?
 */
void dungeonSetupTest(std::string playerName){
	Dungeon d(playerName);
	d.addPlayerSkill("HI", 4);
	d.addPlayerSkill("Yo", 4);
	d.addPlayerSkill("MEW 2", 4);
	d.addPlayerSkill("MEW 5", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("HI", 4);
	d.addPlayerSkill("Yo", 4);
	d.addPlayerSkill("MEW 2", 4);
	d.addPlayerSkill("MEW 5", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	d.addPlayerSkill("next UP!", 4);
	std::cout << d.numHrs() << std::endl;
	std::cout << d.getDay() << std::endl;
	d.subtractHrs(49);
	std::cout << d.numHrs() << std::endl;
	std::cout << d.getDay() << std::endl;
	d.subtractHrs(10);
	std::cout << d.numHrs() << std::endl;
	d.subtractHrs(10);
	std::cout << d.numHrs() << std::endl;
	std::cout << d << std::endl;
}

// ----------------------------------------------------------------

/** Run the dungeon.
 *  @param d, the current Dungeon object
 *  @modifies d by performing the dungeon actions
 *  @effects Allows the user to loop through the dungeon object
 *           performing one action at a time until 30 days pass.
 */
void run(Dungeon& d) {
	std::string cmd;

	while ( d.getDaysPassed() < 30 ) {
		std::cout << "\nEnter what you want to do next: ";
		std::cin >> cmd;
		std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);

		if ( (cmd == "f") || (cmd == "fight") ) {
			std::cout << *(d.getMonster()) << std::endl;
			d.subtractHrs(24);
		} else if ( (cmd == "h") || (cmd == "help") ) {
			std::cout << "These are your options for input:" << std::endl <<
				"  \"Fight\" or \"f\" -> fight a monster" << std::endl <<
				"  \"Quit\" or \"q\" -> quit the game before 30 days" << std::endl <<
				"  \"Study\" or \"s\" -> input a number greater than 0" << std::endl <<
				"  \"Time\" or \"t\" -> print the current time info" << std::endl;
		} else if ( (cmd == "q") || (cmd == "quit") ) {
			break;
		} else if ( (cmd == "s") || (cmd == "study") ) {
			unsigned int hrs;
			std::cout << "For how many hours (between 0 and " << d.numHrs() << ")? ";
			std::cin >> hrs;
			while ( std::cin.fail() || hrs > d.numHrs() ) {
				std::cout << "Invalid input!" << std::endl;
				std::cin.clear();
				std::cin.ignore(10000, '\n');
				std::cin >> hrs;
			}
			// Post code
			d.subtractHrs(hrs);
			continue;
		} else if ( (cmd == "t") || (cmd == "time") ) {
			// printTimeInfo(d);
			// I think this will be a little more useful to the user.
			std::cout << "Day " << d.getDaysPassed() << "out of 30, Hour " << (24 - d.numHrs()) << std::endl;
		} else {
			std::cout << "Unknown command" << std::endl;
		}
	}

	std::cout << std::endl;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <ctime>

#include "hbshaper.h"
#include "freetypelib.h"

using namespace std;

vector<gl::Mesh*> meshes;

int main(int argc, char** argv) {
    srand(time(NULL));

    // the font rasterizing library
    FreeTypeLib lib;
    clock_t begin, end;

    HBShaper<FT_Face> latinShaper("fonts/DejaVuSerif.ttf", &lib);
    HBShaper<FT_Face> arabicShaper("fonts/amiri-regular.ttf", &lib);
    HBShaper<FT_Face> russianShaper("fonts/DejaVuSerif.ttf", &lib);
    HBShaper<FT_Face> hanShaper("fonts/fireflysung.ttf", &lib);

    latinShaper.init();
    arabicShaper.init();
    russianShaper.init();
    hanShaper.init();

    HBText hbt1 = {
        "ficellé fffffi. VAV.",
        "fr",
        HB_SCRIPT_LATIN,
        HB_DIRECTION_LTR
    };

    HBText hbt2 = {
        "الى ما شاسعة وقوعها، ليتسنّى. عل يتم",
        "ar",
        HB_SCRIPT_ARABIC,
        HB_DIRECTION_RTL
    };

    HBText hbt3 = {
        "Дуо вёжи дёжжэнтиюнт ут",
        "ru",
        HB_SCRIPT_CYRILLIC,
        HB_DIRECTION_LTR
    };

    HBText hbt4 = {
        "緳 踥踕",
        "ch",
        HB_SCRIPT_HAN,
        HB_DIRECTION_TTB
    };

    latinShaper.addFeature(HBFeature::KerningOn);

    gl::initGL(argc, argv);

    begin = clock();

    // ask for some meshes, this is not optimal since every glyph has its
    // own texture, should use an atlas than contains glyph inside
    for(auto mesh: latinShaper.drawText(hbt1, 20, 300)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: arabicShaper.drawText(hbt2, 20, 200)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: russianShaper.drawText(hbt3, 20, 100)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: hanShaper.drawText(hbt4, 700, 380)) {
        meshes.push_back(mesh);
    }

    end = clock();

    std::cout << (float) (end - begin) / CLOCKS_PER_SEC << " ms" << std::endl;

    gl::uploadMeshes(meshes);

    gl::loop(meshes);
    gl::finish();

    gl::deleteMeshes(meshes);

    return 0;
}<commit_msg>time in millis<commit_after>#include <iostream>
#include <cassert>
#include <ctime>

#include "hbshaper.h"
#include "freetypelib.h"

using namespace std;

vector<gl::Mesh*> meshes;

int main(int argc, char** argv) {
    srand(time(NULL));

    // the font rasterizing library
    FreeTypeLib lib;
    clock_t begin, end;

    HBShaper<FT_Face> latinShaper("fonts/DejaVuSerif.ttf", &lib);
    HBShaper<FT_Face> arabicShaper("fonts/amiri-regular.ttf", &lib);
    HBShaper<FT_Face> russianShaper("fonts/DejaVuSerif.ttf", &lib);
    HBShaper<FT_Face> hanShaper("fonts/fireflysung.ttf", &lib);

    latinShaper.init();
    arabicShaper.init();
    russianShaper.init();
    hanShaper.init();

    HBText hbt1 = {
        "ficellé fffffi. VAV.",
        "fr",
        HB_SCRIPT_LATIN,
        HB_DIRECTION_LTR
    };

    HBText hbt2 = {
        "الى ما شاسعة وقوعها، ليتسنّى. عل يتم",
        "ar",
        HB_SCRIPT_ARABIC,
        HB_DIRECTION_RTL
    };

    HBText hbt3 = {
        "Дуо вёжи дёжжэнтиюнт ут",
        "ru",
        HB_SCRIPT_CYRILLIC,
        HB_DIRECTION_LTR
    };

    HBText hbt4 = {
        "緳 踥踕",
        "ch",
        HB_SCRIPT_HAN,
        HB_DIRECTION_TTB
    };

    latinShaper.addFeature(HBFeature::KerningOn);

    gl::initGL(argc, argv);

    begin = clock();

    // ask for some meshes, this is not optimal since every glyph has its
    // own texture, should use an atlas than contains glyph inside
    for(auto mesh: latinShaper.drawText(hbt1, 20, 300)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: arabicShaper.drawText(hbt2, 20, 200)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: russianShaper.drawText(hbt3, 20, 100)) {
        meshes.push_back(mesh);
    }

    for(auto mesh: hanShaper.drawText(hbt4, 700, 380)) {
        meshes.push_back(mesh);
    }

    end = clock();

    std::cout << ((float) (end - begin) / CLOCKS_PER_SEC) * 1000 << " ms." << std::endl;

    gl::uploadMeshes(meshes);

    gl::loop(meshes);
    gl::finish();

    gl::deleteMeshes(meshes);

    return 0;
}<|endoftext|>


<commit_before>#include "SDL.h"
#include "SDL_opengl.h"

void drawScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(1.0f, 0.0f, 0.0f);
    glBegin(GL_TRIANGLES);
    glVertex3f(-0.5f, -0.7f, 0.0f);
    glVertex3f( 0.5f, -0.7f, 0.0f);
    glVertex3f( 0.0f,  0.7f, 0.0f);
    glEnd();

    SDL_GL_SwapBuffers();
}

void handleKey(SDL_keysym *key)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        SDL_Quit();
        exit(0);
        break;
    default:
        break;
    }
}

int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;
    bool done = false;
    SDL_Event event;
    int flags;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    while (!done) {
        drawScene();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                handleKey(&event.key.keysym);
                break;
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    SDL_Quit();
    return 0;
}
<commit_msg>Got simple perspective demo working.<commit_after>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>

void drawScene(void)
{
    int x, y;
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
    glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
    glTranslatef(0.0f, 0.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);

    glColor3f(1.0f, 0.0f, 0.0f);
    glBegin(GL_TRIANGLES);
    for (x = -5; x <= 5; ++x) {
        for (y = -5; y <= 5; ++y) {
            glVertex3f(2*x - 0.5f, 2*y - 0.7f, 0.0f);
            glVertex3f(2*x + 0.5f, 2*y - 0.7f, 0.0f);
            glVertex3f(2*x + 0.0f, 2*y + 0.7f, 0.0f);
        }
    }
    glEnd();

    SDL_GL_SwapBuffers();
}

void handleKey(SDL_keysym *key)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        SDL_Quit();
        exit(0);
        break;
    default:
        break;
    }
}

int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;
    bool done = false;
    SDL_Event event;
    int flags;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    while (!done) {
        drawScene();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                handleKey(&event.key.keysym);
                break;
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// 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 software's owners 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 HOLDER 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.
//
// (This is the BSD 3-clause license)

#include "mainwindow.h"
#include "ptview.h"

#include <QtCore/QDataStream>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtOpenGL/QGLFormat>

#include "argparse.h"
#include "config.h"
#include "displazserver.h"

QStringList g_initialFileNames;
static int storeFileName (int argc, const char *argv[])
{
    for(int i = 0; i < argc; ++i)
        g_initialFileNames.push_back (argv[i]);
    return 0;
}

/// Set up search paths to our application directory for Qt's file search
/// mechanism.
///
/// This allows us to use "shaders:points_default.glsl" as a path to a shader
/// in the rest of the code, regardless of the system-specific details of how
/// the install directories are laid out.
static void setupQFileSearchPaths()
{
    QString installBinDir = QCoreApplication::applicationDirPath();
    if (!installBinDir.endsWith("/bin"))
    {
        std::cerr << "WARNING: strange install location detected "
                     "- shaders will not be found\n";
        return;
    }
    QString installBaseDir = installBinDir;
    installBaseDir.chop(4);
    QDir::addSearchPath("shaders", installBaseDir + "/" + DISPLAZ_SHADER_DIR);
    QDir::addSearchPath("doc", installBaseDir + "/" + DISPLAZ_DOC_DIR);
}

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

    ArgParse::ArgParse ap;
    bool printVersion = false;
    bool printHelp = false;
    int maxPointCount = 200000000;
    std::string serverName;

    std::string shaderName;
    bool remoteMode = true;

    ap.options(
        "displaz - A lidar point cloud viewer\n"
        "Usage: displaz [opts] [file1.las ...]",
        "%*", storeFileName, "",
        "--maxpoints %d", &maxPointCount, "Maximum number of points to load at a time",
        "--noremote %!",  &remoteMode,    "Don't attempt to open files in existing window",
        "--server %s",    &serverName,    "Name of displaz instance to message on startup",
        "--shader %s",    &shaderName,    "Name of shader file to load on startup",
        "--version",      &printVersion,  "Print version number",
        "--help",         &printHelp,     "Print command line usage help",
        NULL
    );

    attachToParentConsole();
    if(ap.parse(argc, const_cast<const char**>(argv)) < 0)
    {
        ap.usage();
        std::cerr << "ERROR: " << ap.geterror() << std::endl;
        return EXIT_FAILURE;
    }

    if (printVersion)
    {
        std::cout << "version " DISPLAZ_VERSION_STRING "\n";
        return EXIT_SUCCESS;
    }
    if (printHelp)
    {
        ap.usage();
        return EXIT_SUCCESS;
    }

    setupQFileSearchPaths();

    // TODO: Factor out this socket comms code - sending and recieving of
    // messages should happen in a centralised place.
    QString socketName = DisplazServer::socketName(QString::fromStdString(serverName));
    if (remoteMode)
    {
        QDir currentDir = QDir::current();
        QLocalSocket socket;
        // Attempt to locate a running displaz instance
        socket.connectToServer(socketName);
        if (socket.waitForConnected(100))
        {
            QByteArray command;
            if (g_initialFileNames.empty())
            {
                std::cerr << "WARNING: Existing window found, but no remote "
                             "command specified - exiting\n";
                // Since we opened the connection, close it nicely by sending a
                // zero-length message to say goodbye.
                command = "";
            }
            else
            {
                command = "OPEN_FILES";
                for (int i = 0; i < g_initialFileNames.size(); ++i)
                {
                    command += "\n";
                    command += currentDir.absoluteFilePath(g_initialFileNames[i]).toUtf8();
                }
            }
            QDataStream stream(&socket);
            // Writes length as big endian uint32 followed by raw bytes
            stream.writeBytes(command.data(), command.length());
            socket.disconnectFromServer();
            socket.waitForDisconnected(10000);
            //std::cerr << "Opening files in existing displaz instance\n";
            return EXIT_SUCCESS;
        }
    }
    // If we didn't find any other running instance, start up a server to
    // accept incoming connections, if desired
    std::unique_ptr<DisplazServer> server;
    if (remoteMode)
        server.reset(new DisplazServer(socketName));

    // Multisampled antialiasing - this makes rendered point clouds look much
    // nicer, but also makes the render much slower, especially on lower
    // powered graphics cards.
    //QGLFormat f = QGLFormat::defaultFormat();
    //f.setSampleBuffers(true);
    //QGLFormat::setDefaultFormat(f);

    PointViewerMainWindow window;
    if (remoteMode)
    {
        QObject::connect(server.get(), SIGNAL(messageReceived(QByteArray)),
                         &window, SLOT(runCommand(QByteArray)));
    }
    window.captureStdout();
    window.pointView().setMaxPointCount(maxPointCount);
    if (!shaderName.empty())
        window.openShaderFile(QString::fromStdString(shaderName));
    window.show();

    // Open initial files only after event loop has started.  Use a small but
    // nonzero timeout to give the GUI a chance to draw itself which makes
    // things slightly less ugly.
    QTimer::singleShot(200, &window, SLOT(openInitialFiles()));

    return app.exec();
}

<commit_msg>Rename option --noremote to --noserver for clarity<commit_after>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// 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 software's owners 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 HOLDER 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.
//
// (This is the BSD 3-clause license)

#include "mainwindow.h"
#include "ptview.h"

#include <QtCore/QDataStream>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtOpenGL/QGLFormat>

#include "argparse.h"
#include "config.h"
#include "displazserver.h"

QStringList g_initialFileNames;
static int storeFileName (int argc, const char *argv[])
{
    for(int i = 0; i < argc; ++i)
        g_initialFileNames.push_back (argv[i]);
    return 0;
}

/// Set up search paths to our application directory for Qt's file search
/// mechanism.
///
/// This allows us to use "shaders:points_default.glsl" as a path to a shader
/// in the rest of the code, regardless of the system-specific details of how
/// the install directories are laid out.
static void setupQFileSearchPaths()
{
    QString installBinDir = QCoreApplication::applicationDirPath();
    if (!installBinDir.endsWith("/bin"))
    {
        std::cerr << "WARNING: strange install location detected "
                     "- shaders will not be found\n";
        return;
    }
    QString installBaseDir = installBinDir;
    installBaseDir.chop(4);
    QDir::addSearchPath("shaders", installBaseDir + "/" + DISPLAZ_SHADER_DIR);
    QDir::addSearchPath("doc", installBaseDir + "/" + DISPLAZ_DOC_DIR);
}

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

    ArgParse::ArgParse ap;
    bool printVersion = false;
    bool printHelp = false;
    int maxPointCount = 200000000;
    std::string serverName;

    std::string shaderName;
    bool useServer = true;

    ap.options(
        "displaz - A lidar point cloud viewer\n"
        "Usage: displaz [opts] [file1.las ...]",
        "%*", storeFileName, "",
        "--maxpoints %d", &maxPointCount, "Maximum number of points to load at a time",
        "--noserver %!",  &useServer,     "Don't attempt to open files in existing window",
        "--server %s",    &serverName,    "Name of displaz instance to message on startup",
        "--shader %s",    &shaderName,    "Name of shader file to load on startup",
        "--version",      &printVersion,  "Print version number",
        "--help",         &printHelp,     "Print command line usage help",
        NULL
    );

    attachToParentConsole();
    if(ap.parse(argc, const_cast<const char**>(argv)) < 0)
    {
        ap.usage();
        std::cerr << "ERROR: " << ap.geterror() << std::endl;
        return EXIT_FAILURE;
    }

    if (printVersion)
    {
        std::cout << "version " DISPLAZ_VERSION_STRING "\n";
        return EXIT_SUCCESS;
    }
    if (printHelp)
    {
        ap.usage();
        return EXIT_SUCCESS;
    }

    setupQFileSearchPaths();

    // TODO: Factor out this socket comms code - sending and recieving of
    // messages should happen in a centralised place.
    QString socketName = DisplazServer::socketName(QString::fromStdString(serverName));
    if (useServer)
    {
        QDir currentDir = QDir::current();
        QLocalSocket socket;
        // Attempt to locate a running displaz instance
        socket.connectToServer(socketName);
        if (socket.waitForConnected(100))
        {
            QByteArray command;
            if (g_initialFileNames.empty())
            {
                std::cerr << "WARNING: Existing window found, but no remote "
                             "command specified - exiting\n";
                // Since we opened the connection, close it nicely by sending a
                // zero-length message to say goodbye.
                command = "";
            }
            else
            {
                command = "OPEN_FILES";
                for (int i = 0; i < g_initialFileNames.size(); ++i)
                {
                    command += "\n";
                    command += currentDir.absoluteFilePath(g_initialFileNames[i]).toUtf8();
                }
            }
            QDataStream stream(&socket);
            // Writes length as big endian uint32 followed by raw bytes
            stream.writeBytes(command.data(), command.length());
            socket.disconnectFromServer();
            socket.waitForDisconnected(10000);
            //std::cerr << "Opening files in existing displaz instance\n";
            return EXIT_SUCCESS;
        }
    }
    // If we didn't find any other running instance, start up a server to
    // accept incoming connections, if desired
    std::unique_ptr<DisplazServer> server;
    if (useServer)
        server.reset(new DisplazServer(socketName));

    // Multisampled antialiasing - this makes rendered point clouds look much
    // nicer, but also makes the render much slower, especially on lower
    // powered graphics cards.
    //QGLFormat f = QGLFormat::defaultFormat();
    //f.setSampleBuffers(true);
    //QGLFormat::setDefaultFormat(f);

    PointViewerMainWindow window;
    if (useServer)
    {
        QObject::connect(server.get(), SIGNAL(messageReceived(QByteArray)),
                         &window, SLOT(runCommand(QByteArray)));
    }
    window.captureStdout();
    window.pointView().setMaxPointCount(maxPointCount);
    if (!shaderName.empty())
        window.openShaderFile(QString::fromStdString(shaderName));
    window.show();

    // Open initial files only after event loop has started.  Use a small but
    // nonzero timeout to give the GUI a chance to draw itself which makes
    // things slightly less ugly.
    QTimer::singleShot(200, &window, SLOT(openInitialFiles()));

    return app.exec();
}

<|endoftext|>


<commit_before>/////////////
// Imports //
#include <iostream>

#include "image.hpp"
#include "pixel.hpp"

//////////
// Code //

// Loading an image from the filesystem.
Image* loadImage(char* path) {
    std::cout << "Loading image " << path << ".\n";
    Image* img = new Image(std::string(path));
    if (img->error) {
        std::cerr << "Failed to load image " << path << ".\n";
        delete img;
        return nullptr;
    }

    return img;
}

// Loading a set of images.
Image** loadImages(char** argv) {
    Image** imgs = new Image*[3];

    Image* img1 = loadImage(argv[1]);
    if (img1 == nullptr) {
        delete[] imgs;
        return nullptr;
    }

    Image* img2 = loadImage(argv[2]);
    if (img2 == nullptr) {
        delete[] imgs;
        delete img1;
        return nullptr;
    }

    Image* img3 = loadImage(argv[3]);
    if (img3 == nullptr) {
        delete[] imgs;
        delete img1;
        delete img2;
        return nullptr;
    }

    imgs[0] = img1;
    imgs[1] = img2;
    imgs[2] = img3;

    return imgs;
}

// Placeholder main.
int main(int argc, char** argv) {
    // Checking for argument validity.
    if (argc != 5) {
        std::cout << "Proper usage: tentons <input image 1> <input image 2> "
                  << "<input image 3> <output image>\n";

        return 1;
    }

    // Loading each Image.
    Image** imgs = loadImages(argv);
    if (imgs == nullptr)
        return 2;

    // Processing the output image.
    std::cout << "Processing output image...\n";
    Image* out = processImages(imgs[0], imgs[1], imgs[2]);

    // Writing the output image.
    if (out != nullptr) {
        std::cout << "Writing output image...\n";
        out->save(std::string(argv[4]));
    } else {
        std::cout << "Cannot write out null output image!\n";
    }

    // Cleaning up memory.
    std::cout << "Cleaning up memory...\n";
    for (int i = 0; i < 3; i++)
        if (imgs[i] != nullptr)
            delete imgs[i];

    delete[] imgs;

    if (out != nullptr)
        delete out;

    return 0;
}
<commit_msg>Made loading more than just 3 images.<commit_after>/////////////
// Imports //
#include <iostream>

#include "image.hpp"
#include "pixel.hpp"

//////////
// Code //

// Loading an image from the filesystem.
Image* loadImage(char* path) {
    std::cout << "Loading image " << path << ".\n";
    Image* img = new Image(std::string(path));
    if (img->error) {
        std::cerr << "Failed to load image " << path << ".\n";
        delete img;
        return nullptr;
    }

    return img;
}

// Loading a set of images.
Image** loadImages(int argc, char** argv) {
    Image** imgs = new Image*[argc - 2];

    for (int i = 1; i < argc - 1; i++) {
        imgs[i - 1] = loadImage(argv[i]);
        if (imgs[i - 1] == nullptr) {
            std::cerr << "Could not load image " << argv[i] << "!\n";
            for (int j = 1; j < i; i++)
                delete imgs[j];
            delete[] imgs;

            return nullptr;
        }
    }

    return imgs;
}

// Placeholder main.
int main(int argc, char** argv) {
    // Checking for argument validity.
    if (argc == 1) {
        std::cout << "Proper usage: tentons <img 1> <img 2> ... "
                  << "<output image>\n";
        return 1;
    }

    // Loading each Image.
    Image** imgs = loadImages(argc, argv);
    if (imgs == nullptr)
        return 2;

    // Processing the output image.
    std::cout << "Processing output image...\n";
    Image* out = processImages(imgs[0], imgs[1], imgs[2]);

    // Writing the output image.
    if (out != nullptr) {
        std::cout << "Writing output image...\n";
        out->save(std::string(argv[4]));
    } else {
        std::cout << "Cannot write out null output image!\n";
    }

    // Cleaning up memory.
    std::cout << "Cleaning up memory...\n";
    for (int i = 0; i < 3; i++)
        if (imgs[i] != nullptr)
            delete imgs[i];

    delete[] imgs;

    if (out != nullptr)
        delete out;

    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file request.cpp
 * @brief Generic request interface
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/request.h"
#include "mega/command.h"

namespace mega {
void Request::add(Command* c)
{
    cmds.push_back(c);
}

int Request::cmdspending() const
{
    return cmds.size();
}

void Request::get(string* req) const
{
    // concatenate all command objects, resulting in an API request
    *req = "[";

    for (int i = 0; i < (int)cmds.size(); i++)
    {
        req->append(i ? ",{" : "{");
        req->append(cmds[i]->getstring());
        req->append("}");
    }

    req->append("]");
}

void Request::procresult(MegaClient* client)
{
    client->json.enterarray();

    for (int i = 0; i < (int)cmds.size(); i++)
    {
        client->restag = cmds[i]->tag;

        cmds[i]->client = client;

        if (client->json.enterobject())
        {
            cmds[i]->procresult();
            client->json.leaveobject();
        }
        else if (client->json.enterarray())
        {
            cmds[i]->procresult();
            client->json.leavearray();
        }
        else
        {
            cmds[i]->procresult();
        }

        if (!cmds[i]->persistent)
        {
            delete cmds[i];
        }
    }

    cmds.clear();
}

void Request::clear()
{
    for (int i = (int)cmds.size(); i--; )
    {
        if (!cmds[i]->persistent)
        {
            delete cmds[i];
        }
    }
    cmds.clear();
}
} // namespace
<commit_msg>Protection against clients calling logout() during a callback<commit_after>/**
 * @file request.cpp
 * @brief Generic request interface
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/request.h"
#include "mega/command.h"

namespace mega {
void Request::add(Command* c)
{
    cmds.push_back(c);
}

int Request::cmdspending() const
{
    return cmds.size();
}

void Request::get(string* req) const
{
    // concatenate all command objects, resulting in an API request
    *req = "[";

    for (int i = 0; i < (int)cmds.size(); i++)
    {
        req->append(i ? ",{" : "{");
        req->append(cmds[i]->getstring());
        req->append("}");
    }

    req->append("]");
}

void Request::procresult(MegaClient* client)
{
    client->json.enterarray();

    for (int i = 0; i < (int)cmds.size(); i++)
    {
        client->restag = cmds[i]->tag;

        cmds[i]->client = client;

        if (client->json.enterobject())
        {
            cmds[i]->procresult();
            client->json.leaveobject();
        }
        else if (client->json.enterarray())
        {
            cmds[i]->procresult();
            client->json.leavearray();
        }
        else
        {
            cmds[i]->procresult();
        }

        if(!cmds.size())
        {
            return;
        }

        if (!cmds[i]->persistent)
        {
            delete cmds[i];
        }
    }

    cmds.clear();
}

void Request::clear()
{
    for (int i = (int)cmds.size(); i--; )
    {
        if (!cmds[i]->persistent)
        {
            delete cmds[i];
        }
    }
    cmds.clear();
}
} // namespace
<|endoftext|>


<commit_before><commit_msg>Pcbnew: add send msg to Eeschema when move module<commit_after><|endoftext|>


<commit_before>/*
 * File:   yoshiko_main.cpp
 * Author: emanuellaude, gunnar klau
 *
 * Created on 26. August 2012, 20:07
 */

#include <iostream>

#include <lemon/lgf_writer.h>
#include <lemon/adaptors.h>
#include <lemon/bin_heap.h>
#include <lemon/arg_parser.h>

#include "ClusterEditingInstance.h"
#include "ClusterReductionInstance.h"
#include "ClusterEditingSolutions.h"
#include "CoreAlgorithm.h"
#include "Globals.h"

#include "output/ClusterEditingOutput.h"

#include "input/JENAInput.h"
#include "input/SIFInput.h"
#include "input/RowSimInput.h"
#include "input/StreamInput.h"

using namespace std;
using namespace lemon;
using namespace ysk;
using namespace yskInput;

/*
 =========================================================================
 TODO
 =========================================================================
 * validate input data. !!! -> Now part of the separate input classes
 * heuristik, set starting value
 * separation triangles
 * separation partition cuts
 * separation (mueller)
 * enumerating optimal solutions (isnt this already implemented?)
 *
 * check whether new code produces same sol as old code (in presence of partition constraints) (Which old code, yosh 1.0?)
 * check partition constraints (--> paper!)
 *
 * svn link with Xcode (still needed?)
 * document... how? -> doxygen. on it!
 * layout graphs...? -> use cytoscape pretty much done
 * Setup unified logging system and streamline all cout//exception calls, apply verbosity globally
 * put in NINA
 * edge index. make faster by directly computing index from i and j. think about (common) solution for directed and undirected graphs
 *
 * K Cluster Approaches
 * Strictly ILP (Add additional constraints)
 * Add k Cluster Centers with M +e Cost (Sum of edge weights)
 * Specify/Choose clusters
 * Merge/Cut clusters
 */

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

  //Register time at the beginning of the execution
  clock_t startTime = clock();

  // Initialize the argument parser
  ArgParser ap(argc, argv);
  string inputFilename, outputFilename;
  string graphLabel = "cluster_solution";
  int inputFileFormat = 0;
  int outputFileFormat = 0;
  bool exportLP = false;

  YParameterSet parameter;

  // Add a string option with storage reference for file name
  ap.refOption("f", "Name of file that contains input []", inputFilename, true);
  //ap.refOption("F", "input file format, 0 = Jena, 1 = Clever, 2 = SIF []", inputFileFormat, false);
  ap.refOption("F", "input file format, 0 = Jena, 1 = SIF, 2 = RowSim [0]", inputFileFormat, false);
  ap.refOption("o", "Name of output file(s) []", outputFilename, false);
  ap.refOption("O", "output file format 0 = csv, 1 = table (line one: number of nodes, line two: number of clusters, column one: node name, column two: cluster ID), 2 = gml, 3 = xgmml (Cytoscape) 4 = Pajek [0], 5 = table (Cytoscape app), 6 = TransClust Format", outputFileFormat, false);
  ap.refOption("v", "verbosity, 0 = silent, 5 = full [0]", verbosity, false);
  ap.refOption("H", "utilize heuristic instead of ILP, [false]", parameter.useHeuristic, false);
  ap.refOption("T", "CPU time limit (s) for the ILP component, -1 = no limit [-1]", time_limit, false);
  ap.refOption("t", "Threshold for RowSim format, Should be in range 0 <= t <= 1 [0.5]",threshold,false);
  ap.refOption("threads", "number of threads [max]", no_threads, false);
  ap.refOption("e", "export LP [false]", exportLP, false);
  ap.refOption("st", "separate triangles [false]", parameter.separateTriangles, false);
  ap.refOption("sp", "separate partition cuts [false]", parameter.separatePartitionCuts, false);
  ap.refOption("n", "number of optimal solutions [1]", parameter.nrOptimalSolutions, false);
  ap.refOption("m", "multiplicative factor for real valued edge weights in SimilarNeighborhoodRule (the higher the better the reduction results and the slower the performance) [1]", parameter.multiplicativeFactor, false);
  ap.refOption("g", "graph label []", graphLabel, false);
  ap.refOption("r", "explicitly turn on/off reduction rules, bit string (right to left): bit 0 = CliqueRule, bit 1 = CriticalCliqueRule, bit 2 = AlmostCliqueRule, bit 3 = HeavyEdgeRule3in1, bit 4 = ParameterDependentReductionRule, bit 5 = SimilarNeighborhoodRule [111111]", parameter.rulesBitMask, false);
  ap.refOption("k", "[EXPERIMENTAL!!!]define the number of desired clusters, -1 determines this value automatically [-1]",parameter.targetClusterCount,false);

  // Perform the parsing process
  // (in case of any error it terminates the program) -> tb improved
  ap.parse();

  // Check each option if it has been given and print its value
  if (verbosity > 2) {

    std::cout << "Parameters of '" << ap.commandName() << "':\n";

    std::cout << "      -f: " << inputFilename << std::endl;
    std::cout << "      -F: " << inputFileFormat << std::endl;
    std::cout << "      -o: " << outputFilename << std::endl;
    std::cout << "      -O: " << outputFileFormat << std::endl;
    std::cout << "      -v: " << verbosity << std::endl;
    std::cout << "      -H: " << parameter.useHeuristic << std::endl;
    std::cout << "      -T: " << time_limit << std::endl;
    std::cout << "      -t  " << threshold << std::endl;
    if (ap.given("t") && inputFileFormat != 2){
    	std::cout << "Threshold parameter is ignored! Only relevant for SimRow format." << endl;
    }
    std::cout << "-threads: " << no_threads << std::endl;
    std::cout << "      -e: " << exportLP << std::endl;
    std::cout << "      -st: " << parameter.separateTriangles << std::endl;
    std::cout << "      -sp: " << parameter.separatePartitionCuts << std::endl;
    std::cout << "      -n: " << parameter.nrOptimalSolutions << std::endl;
    std::cout << "      -m: " << parameter.multiplicativeFactor << std::endl;
    std::cout << "      -g: " << graphLabel << std::endl;
    std::cout << "      -r: " << parameter.rulesBitMask << std::endl;
    std::cout << "      -k: " << parameter.targetClusterCount << std::endl;
  }

  ifstream is(inputFilename.c_str());

  if (!is.is_open()) {
    cerr << "file '" << inputFilename << "' not found!" << endl;
    exit(-1);
  }

  //Determine which input format is to be parsed and generate a ClusterEditingInstance accordingly

  ClusterEditingInstance* instance = new ClusterEditingInstance();
  StreamInput* input;

  switch (inputFileFormat) {
  	  //JENA
  	  case 0:
  		  input = new JENAInput(instance);
  		  break;
      //SIF
  	  case 1:
  		  input = new SIFInput(instance);
  		  break;
  	  //ROW SIM
  	  case 2:
  		  input = new RowSimInput(instance,threshold);
  		  break;
  	  default:
  		  //Should never be reached
  		  cout << endl<<"Warning: Input Format not specified, assuming JENA"<<endl;
  		  input = new JENAInput(instance);
  		  break;
  }

  if (!input->parseInput(is)){
	  std::cout << endl << "Parsing failed! Terminating ...";
	  return 1;
  }
  is.close(); //Close input stream

  instance = input->getProblemInstance();

  CoreAlgorithm* core = new CoreAlgorithm(
		  instance,
		  parameter
  );

  ClusterEditingSolutions* ces = core->run();

  //Output generation
  ClusterEditingOutput* output;
  output = ClusterEditingOutput::newInstance(
		  *instance,
		  *ces,
		  outputFilename,
		  graphLabel,
		  outputFileFormat
		  );

  if (output != nullptr){
	  output->write();
  }

  //Final cleanup
  delete core;
  delete instance;
  delete input;
  delete ces;
  delete output;

  if (verbosity > 2) cout << "Total runtime: " << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

  //Termination
  return 0;
}
<commit_msg>nothing<commit_after>/*
 * File:   yoshiko_main.cpp
 * Author: emanuellaude, gunnar klau
 *
 * Created on 26. August 2012, 20:07
 */

#include <iostream>

#include <lemon/lgf_writer.h>
#include <lemon/adaptors.h>
#include <lemon/bin_heap.h>
#include <lemon/arg_parser.h>

#include "ClusterEditingInstance.h"
#include "ClusterReductionInstance.h"
#include "ClusterEditingSolutions.h"
#include "CoreAlgorithm.h"
#include "Globals.h"

#include "output/ClusterEditingOutput.h"

#include "input/JENAInput.h"
#include "input/SIFInput.h"
#include "input/RowSimInput.h"
#include "input/StreamInput.h"

using namespace std;
using namespace lemon;
using namespace ysk;
using namespace yskInput;

/*
 =========================================================================
 TODO
 =========================================================================
 * validate input data. !!! -> Now part of the separate input classes
 * heuristik, set starting value
 * separation triangles
 * separation partition cuts
 * separation (mueller)
 * enumerating optimal solutions (isnt this already implemented?)
 *
 * check whether new code produces same sol as old code (in presence of partition constraints) (Which old code, yosh 1.0?)
 * check partition constraints (--> paper!)
 *
 * svn link with Xcode (still needed?)
 * document... how? -> doxygen. on it!
 * layout graphs...? -> use cytoscape pretty much done
 * Setup unified logging system and streamline all cout//exception calls, apply verbosity globally
 * put in NINA
 * edge index. make faster by directly computing index from i and j. think about (common) solution for directed and undirected graphs
 *
 * K Cluster Approaches
 * Strictly ILP (Add additional constraints)
 * Add k Cluster Centers with M +e Cost (Sum of edge weights)
 * Specify/Choose clusters
 * Merge/Cut clusters
 */

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

  //Register time at the beginning of the execution
  clock_t startTime = clock();

  // Initialize the argument parser
  ArgParser ap(argc, argv);
  string inputFilename, outputFilename;
  string graphLabel = "cluster_solution";
  int inputFileFormat = 0;
  int outputFileFormat = 0;
  bool exportLP = false;

  YParameterSet parameter;

  // Add a string option with storage reference for file name
  ap.refOption("f", "Name of file that contains input []", inputFilename, true);
  //ap.refOption("F", "input file format, 0 = Jena, 1 = Clever, 2 = SIF []", inputFileFormat, false);
  ap.refOption("F", "input file format, 0 = Jena, 1 = SIF, 2 = RowSim [0]", inputFileFormat, false);
  ap.refOption("o", "Name of output file(s) []", outputFilename, false);
  ap.refOption("O", "output file format 0 = csv, 1 = table (line one: number of nodes, line two: number of clusters, column one: node name, column two: cluster ID), 2 = gml, 3 = xgmml (Cytoscape) 4 = Pajek [0], 5 = table (Cytoscape app), 6 = TransClust Format", outputFileFormat, false);
  ap.refOption("v", "verbosity, 0 = silent, 5 = full [0]", verbosity, false);
  ap.refOption("H", "utilize heuristic instead of ILP, [false]", parameter.useHeuristic, false);
  ap.refOption("T", "CPU time limit (s) for the ILP component, -1 = no limit [-1]", time_limit, false);
  ap.refOption("t", "Threshold for RowSim format, Should be in range 0 <= t <= 1 [0.5]",threshold,false);
  ap.refOption("threads", "number of threads [max]", no_threads, false);
  ap.refOption("e", "export LP [false]", exportLP, false);
  ap.refOption("st", "separate triangles [false]", parameter.separateTriangles, false);
  ap.refOption("sp", "separate partition cuts [false]", parameter.separatePartitionCuts, false);
  ap.refOption("n", "number of optimal solutions [1]", parameter.nrOptimalSolutions, false);
  ap.refOption("m", "multiplicative factor for real valued edge weights in SimilarNeighborhoodRule (the higher the better the reduction results and the slower the performance) [1]", parameter.multiplicativeFactor, false);
  ap.refOption("g", "graph label []", graphLabel, false);
  ap.refOption("r", "explicitly turn on/off reduction rules, bit string (right to left): bit 0 = CliqueRule, bit 1 = CriticalCliqueRule, bit 2 = AlmostCliqueRule, bit 3 = HeavyEdgeRule3in1, bit 4 = ParameterDependentReductionRule, bit 5 = SimilarNeighborhoodRule [111111]", parameter.rulesBitMask, false);
  ap.refOption("k", "[EXPERIMENTAL!!!] define the number of clusters, -1 determines this value automatically [-1]",parameter.targetClusterCount,false);

  // Perform the parsing process
  // (in case of any error it terminates the program) -> tb improved
  ap.parse();

  // Check each option if it has been given and print its value
  if (verbosity > 2) {

    std::cout << "Parameters of '" << ap.commandName() << "':\n";

    std::cout << "      -f: " << inputFilename << std::endl;
    std::cout << "      -F: " << inputFileFormat << std::endl;
    std::cout << "      -o: " << outputFilename << std::endl;
    std::cout << "      -O: " << outputFileFormat << std::endl;
    std::cout << "      -v: " << verbosity << std::endl;
    std::cout << "      -H: " << parameter.useHeuristic << std::endl;
    std::cout << "      -T: " << time_limit << std::endl;
    std::cout << "      -t  " << threshold << std::endl;
    if (ap.given("t") && inputFileFormat != 2){
    	std::cout << "Threshold parameter is ignored! Only relevant for SimRow format." << endl;
    }
    std::cout << "-threads: " << no_threads << std::endl;
    std::cout << "      -e: " << exportLP << std::endl;
    std::cout << "      -st: " << parameter.separateTriangles << std::endl;
    std::cout << "      -sp: " << parameter.separatePartitionCuts << std::endl;
    std::cout << "      -n: " << parameter.nrOptimalSolutions << std::endl;
    std::cout << "      -m: " << parameter.multiplicativeFactor << std::endl;
    std::cout << "      -g: " << graphLabel << std::endl;
    std::cout << "      -r: " << parameter.rulesBitMask << std::endl;
    std::cout << "      -k: " << parameter.targetClusterCount << std::endl;
  }

  ifstream is(inputFilename.c_str());

  if (!is.is_open()) {
    cerr << "file '" << inputFilename << "' not found!" << endl;
    exit(-1);
  }

  //Determine which input format is to be parsed and generate a ClusterEditingInstance accordingly

  ClusterEditingInstance* instance = new ClusterEditingInstance();
  StreamInput* input;

  switch (inputFileFormat) {
  	  //JENA
  	  case 0:
  		  input = new JENAInput(instance);
  		  break;
      //SIF
  	  case 1:
  		  input = new SIFInput(instance);
  		  break;
  	  //ROW SIM
  	  case 2:
  		  input = new RowSimInput(instance,threshold);
  		  break;
  	  default:
  		  //Should never be reached
  		  cout << endl<<"Warning: Input Format not specified, assuming JENA"<<endl;
  		  input = new JENAInput(instance);
  		  break;
  }

  if (!input->parseInput(is)){
	  std::cout << endl << "Parsing failed! Terminating ...";
	  return 1;
  }
  is.close(); //Close input stream

  instance = input->getProblemInstance();

  CoreAlgorithm* core = new CoreAlgorithm(
		  instance,
		  parameter
  );

  ClusterEditingSolutions* ces = core->run();

  //Output generation
  ClusterEditingOutput* output;
  output = ClusterEditingOutput::newInstance(
		  *instance,
		  *ces,
		  outputFilename,
		  graphLabel,
		  outputFileFormat
		  );

  if (output != nullptr){
	  output->write();
  }

  //Final cleanup
  delete core;
  delete instance;
  delete input;
  delete ces;
  delete output;

  if (verbosity > 2) cout << "Total runtime: " << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

  //Termination
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <signal.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <string.h>

#include "bpforc.h"
#include "bpftrace.h"
#include "clang_parser.h"
#include "codegen_llvm.h"
#include "driver.h"
#include "list.h"
#include "printer.h"
#include "semantic_analyser.h"
#include "tracepoint_format_parser.h"

using namespace bpftrace;

void usage()
{
  std::cerr << "USAGE:" << std::endl;
  std::cerr << "    bpftrace [options] filename" << std::endl;
  std::cerr << "    bpftrace [options] -e 'program'" << std::endl << std::endl;
  std::cerr << "OPTIONS:" << std::endl;
  std::cerr << "    -B MODE        output buffering mode ('line', 'full', or 'none')" << std::endl;
  std::cerr << "    -d             debug info dry run" << std::endl;
  std::cerr << "    -dd            verbose debug info dry run" << std::endl;
  std::cerr << "    -e 'program'   execute this program" << std::endl;
  std::cerr << "    -h             show this help message" << std::endl;
  std::cerr << "    -l [search]    list probes" << std::endl;
  std::cerr << "    -p PID         enable USDT probes on PID" << std::endl;
  std::cerr << "    -c 'CMD'       run CMD and enable USDT probes on resulting process" << std::endl;
  std::cerr << "    -v             verbose messages" << std::endl;
  std::cerr << "    --version      bpftrace version" << std::endl << std::endl;
  std::cerr << "ENVIRONMENT:" << std::endl;
  std::cerr << "    BPFTRACE_STRLEN           [default: 64] bytes on BPF stack per str()" << std::endl;
  std::cerr << "    BPFTRACE_NO_CPP_DEMANGLE  [default: 0] disable C++ symbol demangling" << std::endl;
  std::cerr << "    BPFTRACE_MAP_KEYS_MAX     [default: 4096] max keys in a map" << std::endl << std::endl;
  std::cerr << "EXAMPLES:" << std::endl;
  std::cerr << "bpftrace -l '*sleep*'" << std::endl;
  std::cerr << "    list probes containing \"sleep\"" << std::endl;
  std::cerr << "bpftrace -e 'kprobe:do_nanosleep { printf(\"PID %d sleeping...\\n\", pid); }'" << std::endl;
  std::cerr << "    trace processes calling sleep" << std::endl;
  std::cerr << "bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'" << std::endl;
  std::cerr << "    count syscalls by process name" << std::endl;
}

static void enforce_infinite_rlimit() {
  struct rlimit rl = {};
  int err;

  rl.rlim_max = RLIM_INFINITY;
  rl.rlim_cur = rl.rlim_max;
  err = setrlimit(RLIMIT_MEMLOCK, &rl);
  if (err)
    std::cerr << std::strerror(err)<<": couldn't set RLIMIT for bpftrace. " <<
        "If your program is not loading, you can try " <<
        "\"ulimit -l 8192\" to fix the problem" << std::endl;
}

bool is_root()
{
  if (geteuid() != 0)
  {
    std::cerr << "ERROR: bpftrace currently only supports running as the root user." << std::endl;
    return false;
  }
  else
    return true;
}

bool is_numeric(char* string)
{
  while(char current_char = *string++)
  {
    if (!isdigit(current_char))
      return false;
  }
  return true;
}

int main(int argc, char *argv[])
{
  int err;
  char *pid_str = nullptr;
  char *cmd_str = nullptr;
  bool listing = false;

  if (argc > 1 && strcmp(argv[1], "--version") == 0)
  {
    std::cout << "bpftrace " << BPFTRACE_VERSION<< "\n" << std::endl;
    return 0;
  }

  std::string script, search, file_name;
  int c;
  while ((c = getopt(argc, argv, "dB:e:hlp:vc:")) != -1)
  {
    switch (c)
    {
      case 'd':
        bt_debug++;
        if (bt_debug == DebugLevel::kNone) {
          usage();
          return 1;
        }
        break;
      case 'v':
        bt_verbose = true;
        break;
      case 'B':
        if (std::strcmp(optarg, "line") == 0) {
          std::setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
        } else if (std::strcmp(optarg, "full") == 0) {
          std::setvbuf(stdout, NULL, _IOFBF, BUFSIZ);
        } else if (std::strcmp(optarg, "none") == 0) {
          std::setvbuf(stdout, NULL, _IONBF, BUFSIZ);
        } else {
          std::cerr << "USAGE: -B must be either 'line', 'full', or 'none'." << std::endl;
          return 1;
        }
        break;
      case 'e':
        script = optarg;
        break;
      case 'p':
        pid_str = optarg;
        break;
      case 'l':
        listing = true;
        break;
      case 'c':
        cmd_str = optarg;
        break;
      case 'h':
        usage();
        return 0;
      default:
        usage();
        return 1;
    }
  }

  if (argc == 1) {
    usage();
    return 1;
  }

  if (bt_verbose && (bt_debug != DebugLevel::kNone))
  {
    // TODO: allow both
    std::cerr << "USAGE: Use either -v or -d." << std::endl;
    return 1;
  }

  if (cmd_str && pid_str)
  {
    std::cerr << "USAGE: Cannot use both -c and -p." << std::endl;
    usage();
    return 1;
  }

  BPFtrace bpftrace;
  Driver driver(bpftrace);

  // PID is currently only used for USDT probes that need enabling. Future work:
  // - make PID a filter for all probe types: pass to perf_event_open(), etc.
  // - provide PID in USDT probe specification as a way to override -p.
  bpftrace.pid_ = 0;
  if (pid_str)
  {
    if (!is_numeric(pid_str))
    {
      std::cerr << "ERROR: pid '" << pid_str << "' is not a valid number." << std::endl;
      return 1;
    }
    bpftrace.pid_ = strtol(pid_str, NULL, 10);
  }

  // Listing probes
  if (listing)
  {
    if (!is_root())
      return 1;

    if (optind == argc-1)
      list_probes(argv[optind], bpftrace.pid_);
    else if (optind == argc)
      list_probes("", bpftrace.pid_);
    else
    {
      usage();
    }
    return 0;
  }

  if (script.empty())
  {
    // Script file
    if (argv[optind] == nullptr)
    {
      std::cerr << "USAGE: filename or -e 'program' required." << std::endl;
      return 1;
    }
    file_name = std::string(argv[optind]);
    err = driver.parse_file(file_name);
    optind++;
  }
  else
  {
    // Script is provided as a command line argument
    err = driver.parse_str(script);
  }

  if (!is_root())
    return 1;

  if (err)
    return err;

  // FIXME (mmarchini): maybe we don't want to always enforce an infinite
  // rlimit?
  enforce_infinite_rlimit();

  // positional parameters
  while (optind < argc) {
    bpftrace.add_param(argv[optind]);
    optind++;
  }

  // defaults
  bpftrace.join_argnum_ = 16;
  bpftrace.join_argsize_ = 1024;

  if(const char* env_p = std::getenv("BPFTRACE_STRLEN")) {
    uint64_t proposed;
    std::istringstream stringstream(env_p);
    if (!(stringstream >> proposed)) {
      std::cerr << "Env var 'BPFTRACE_STRLEN' did not contain a valid uint64_t, or was zero-valued." << std::endl;
      return 1;
    }

    // in practice, the largest buffer I've seen fit into the BPF stack was 240 bytes.
    // I've set the bar lower, in case your program has a deeper stack than the one from my tests,
    // in the hope that you'll get this instructive error instead of getting the BPF verifier's error.
    if (proposed > 200) {
      // the verifier errors you would encounter when attempting larger allocations would be:
      // >240=  <Looks like the BPF stack limit of 512 bytes is exceeded. Please move large on stack variables into BPF per-cpu array map.>
      // ~1024= <A call to built-in function 'memset' is not supported.>
      std::cerr << "'BPFTRACE_STRLEN' " << proposed << " exceeds the current maximum of 200 bytes." << std::endl
      << "This limitation is because strings are currently stored on the 512 byte BPF stack." << std::endl
      << "Long strings will be pursued in: https://github.com/iovisor/bpftrace/issues/305" << std::endl;
      return 1;
    }
    bpftrace.strlen_ = proposed;
  }

  if (const char* env_p = std::getenv("BPFTRACE_NO_CPP_DEMANGLE"))
  {
    if (std::string(env_p) == "1")
      bpftrace.demangle_cpp_symbols = false;
    else if (std::string(env_p) == "0")
      bpftrace.demangle_cpp_symbols = true;
    else
    {
      std::cerr << "Env var 'BPFTRACE_NO_CPP_DEMANGLE' did not contain a valid value (0 or 1)." << std::endl;
      return 1;
    }
  }

  if (const char* env_p = std::getenv("BPFTRACE_MAP_KEYS_MAX"))
  {
    uint64_t proposed;
    std::istringstream stringstream(env_p);
    if (!(stringstream >> proposed)) {
      std::cerr << "Env var 'BPFTRACE_MAP_KEYS_MAX' did not contain a valid uint64_t, or was zero-valued." << std::endl;
      return 1;
    }
    // no maximum is enforced. Imagine a map recording a timestamp by struct page *: this could exceed 10M entries.
    bpftrace.mapmax_ = proposed;
  }

  if (cmd_str)
    bpftrace.cmd_ = cmd_str;

  if (TracepointFormatParser::parse(driver.root_) == false)
    return 1;

  if (bt_debug != DebugLevel::kNone)
  {
    ast::Printer p(std::cout);
    driver.root_->accept(p);
    std::cout << std::endl;
  }

  ClangParser clang;
  std::vector<std::string> extra_flags;
  {
    struct utsname utsname;
    uname(&utsname);
    std::string ksrc, kobj;
    auto kdirs = get_kernel_dirs(utsname);
    ksrc = std::get<0>(kdirs);
    kobj = std::get<1>(kdirs);

    if (ksrc != "")
      extra_flags = get_kernel_cflags(utsname.machine, ksrc, kobj);
  }
  clang.parse(driver.root_, bpftrace, extra_flags);

  if (script.empty())
  {
    err = driver.parse_file(file_name);
  }
  else
  {
    err = driver.parse_str(script);
  }

  if (err)
    return err;

  ast::SemanticAnalyser semantics(driver.root_, bpftrace);
  err = semantics.analyse();
  if (err)
    return err;

  err = semantics.create_maps(bt_debug != DebugLevel::kNone);
  if (err)
    return err;

  ast::CodegenLLVM llvm(driver.root_, bpftrace);
  auto bpforc = llvm.compile(bt_debug);

  if (bt_debug != DebugLevel::kNone)
    return 0;

  // Empty signal handler for cleanly terminating the program
  struct sigaction act = {};
  act.sa_handler = [](int) { };
  sigaction(SIGINT, &act, NULL);

  int num_probes = bpftrace.num_probes();
  if (num_probes == 0)
  {
    std::cout << "No probes to attach" << std::endl;
    return 1;
  }
  else if (num_probes == 1)
    std::cout << "Attaching " << bpftrace.num_probes() << " probe..." << std::endl;
  else
    std::cout << "Attaching " << bpftrace.num_probes() << " probes..." << std::endl;

  err = bpftrace.run(move(bpforc));
  if (err)
    return err;

  std::cout << "\n\n";

  err = bpftrace.print_maps();
  if (err)
    return err;

  return 0;
}
<commit_msg>Use getopt_long instead of getopt<commit_after>#include <iostream>
#include <signal.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <string.h>
#include <getopt.h>

#include "bpforc.h"
#include "bpftrace.h"
#include "clang_parser.h"
#include "codegen_llvm.h"
#include "driver.h"
#include "list.h"
#include "printer.h"
#include "semantic_analyser.h"
#include "tracepoint_format_parser.h"

using namespace bpftrace;

void usage()
{
  std::cerr << "USAGE:" << std::endl;
  std::cerr << "    bpftrace [options] filename" << std::endl;
  std::cerr << "    bpftrace [options] -e 'program'" << std::endl << std::endl;
  std::cerr << "OPTIONS:" << std::endl;
  std::cerr << "    -B MODE        output buffering mode ('line', 'full', or 'none')" << std::endl;
  std::cerr << "    -d             debug info dry run" << std::endl;
  std::cerr << "    -dd            verbose debug info dry run" << std::endl;
  std::cerr << "    -e 'program'   execute this program" << std::endl;
  std::cerr << "    -h, --help     show this help message" << std::endl;
  std::cerr << "    -l [search]    list probes" << std::endl;
  std::cerr << "    -p PID         enable USDT probes on PID" << std::endl;
  std::cerr << "    -c 'CMD'       run CMD and enable USDT probes on resulting process" << std::endl;
  std::cerr << "    -v             verbose messages" << std::endl;
  std::cerr << "    -V, --version  bpftrace version" << std::endl << std::endl;
  std::cerr << "ENVIRONMENT:" << std::endl;
  std::cerr << "    BPFTRACE_STRLEN           [default: 64] bytes on BPF stack per str()" << std::endl;
  std::cerr << "    BPFTRACE_NO_CPP_DEMANGLE  [default: 0] disable C++ symbol demangling" << std::endl;
  std::cerr << "    BPFTRACE_MAP_KEYS_MAX     [default: 4096] max keys in a map" << std::endl << std::endl;
  std::cerr << "EXAMPLES:" << std::endl;
  std::cerr << "bpftrace -l '*sleep*'" << std::endl;
  std::cerr << "    list probes containing \"sleep\"" << std::endl;
  std::cerr << "bpftrace -e 'kprobe:do_nanosleep { printf(\"PID %d sleeping...\\n\", pid); }'" << std::endl;
  std::cerr << "    trace processes calling sleep" << std::endl;
  std::cerr << "bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'" << std::endl;
  std::cerr << "    count syscalls by process name" << std::endl;
}

static void enforce_infinite_rlimit() {
  struct rlimit rl = {};
  int err;

  rl.rlim_max = RLIM_INFINITY;
  rl.rlim_cur = rl.rlim_max;
  err = setrlimit(RLIMIT_MEMLOCK, &rl);
  if (err)
    std::cerr << std::strerror(err)<<": couldn't set RLIMIT for bpftrace. " <<
        "If your program is not loading, you can try " <<
        "\"ulimit -l 8192\" to fix the problem" << std::endl;
}

bool is_root()
{
  if (geteuid() != 0)
  {
    std::cerr << "ERROR: bpftrace currently only supports running as the root user." << std::endl;
    return false;
  }
  else
    return true;
}

bool is_numeric(char* string)
{
  while(char current_char = *string++)
  {
    if (!isdigit(current_char))
      return false;
  }
  return true;
}

int main(int argc, char *argv[])
{
  int err;
  char *pid_str = nullptr;
  char *cmd_str = nullptr;
  bool listing = false;
  std::string script, search, file_name;
  int c;

  const char* const short_options = "dB:e:hlp:vc:V";
  option long_options[] = {
    option{"help", no_argument, nullptr, 'h'},
    option{"version", no_argument, nullptr, 'V'},
    option{nullptr, 0, nullptr, 0},  // Must be last
  };
  while ((c = getopt_long(
              argc, argv, short_options, long_options, nullptr)) != -1)
  {
    switch (c)
    {
      case 'd':
        bt_debug++;
        if (bt_debug == DebugLevel::kNone) {
          usage();
          return 1;
        }
        break;
      case 'v':
        bt_verbose = true;
        break;
      case 'B':
        if (std::strcmp(optarg, "line") == 0) {
          std::setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
        } else if (std::strcmp(optarg, "full") == 0) {
          std::setvbuf(stdout, NULL, _IOFBF, BUFSIZ);
        } else if (std::strcmp(optarg, "none") == 0) {
          std::setvbuf(stdout, NULL, _IONBF, BUFSIZ);
        } else {
          std::cerr << "USAGE: -B must be either 'line', 'full', or 'none'." << std::endl;
          return 1;
        }
        break;
      case 'e':
        script = optarg;
        break;
      case 'p':
        pid_str = optarg;
        break;
      case 'l':
        listing = true;
        break;
      case 'c':
        cmd_str = optarg;
        break;
      case 'h':
        usage();
        return 0;
      case 'V':
        std::cout << "bpftrace " << BPFTRACE_VERSION << std::endl;
        return 0;
      default:
        usage();
        return 1;
    }
  }

  if (argc == 1) {
    usage();
    return 1;
  }

  if (bt_verbose && (bt_debug != DebugLevel::kNone))
  {
    // TODO: allow both
    std::cerr << "USAGE: Use either -v or -d." << std::endl;
    return 1;
  }

  if (cmd_str && pid_str)
  {
    std::cerr << "USAGE: Cannot use both -c and -p." << std::endl;
    usage();
    return 1;
  }

  BPFtrace bpftrace;
  Driver driver(bpftrace);

  // PID is currently only used for USDT probes that need enabling. Future work:
  // - make PID a filter for all probe types: pass to perf_event_open(), etc.
  // - provide PID in USDT probe specification as a way to override -p.
  bpftrace.pid_ = 0;
  if (pid_str)
  {
    if (!is_numeric(pid_str))
    {
      std::cerr << "ERROR: pid '" << pid_str << "' is not a valid number." << std::endl;
      return 1;
    }
    bpftrace.pid_ = strtol(pid_str, NULL, 10);
  }

  // Listing probes
  if (listing)
  {
    if (!is_root())
      return 1;

    if (optind == argc-1)
      list_probes(argv[optind], bpftrace.pid_);
    else if (optind == argc)
      list_probes("", bpftrace.pid_);
    else
    {
      usage();
    }
    return 0;
  }

  if (script.empty())
  {
    // Script file
    if (argv[optind] == nullptr)
    {
      std::cerr << "USAGE: filename or -e 'program' required." << std::endl;
      return 1;
    }
    file_name = std::string(argv[optind]);
    err = driver.parse_file(file_name);
    optind++;
  }
  else
  {
    // Script is provided as a command line argument
    err = driver.parse_str(script);
  }

  if (!is_root())
    return 1;

  if (err)
    return err;

  // FIXME (mmarchini): maybe we don't want to always enforce an infinite
  // rlimit?
  enforce_infinite_rlimit();

  // positional parameters
  while (optind < argc) {
    bpftrace.add_param(argv[optind]);
    optind++;
  }

  // defaults
  bpftrace.join_argnum_ = 16;
  bpftrace.join_argsize_ = 1024;

  if(const char* env_p = std::getenv("BPFTRACE_STRLEN")) {
    uint64_t proposed;
    std::istringstream stringstream(env_p);
    if (!(stringstream >> proposed)) {
      std::cerr << "Env var 'BPFTRACE_STRLEN' did not contain a valid uint64_t, or was zero-valued." << std::endl;
      return 1;
    }

    // in practice, the largest buffer I've seen fit into the BPF stack was 240 bytes.
    // I've set the bar lower, in case your program has a deeper stack than the one from my tests,
    // in the hope that you'll get this instructive error instead of getting the BPF verifier's error.
    if (proposed > 200) {
      // the verifier errors you would encounter when attempting larger allocations would be:
      // >240=  <Looks like the BPF stack limit of 512 bytes is exceeded. Please move large on stack variables into BPF per-cpu array map.>
      // ~1024= <A call to built-in function 'memset' is not supported.>
      std::cerr << "'BPFTRACE_STRLEN' " << proposed << " exceeds the current maximum of 200 bytes." << std::endl
      << "This limitation is because strings are currently stored on the 512 byte BPF stack." << std::endl
      << "Long strings will be pursued in: https://github.com/iovisor/bpftrace/issues/305" << std::endl;
      return 1;
    }
    bpftrace.strlen_ = proposed;
  }

  if (const char* env_p = std::getenv("BPFTRACE_NO_CPP_DEMANGLE"))
  {
    if (std::string(env_p) == "1")
      bpftrace.demangle_cpp_symbols = false;
    else if (std::string(env_p) == "0")
      bpftrace.demangle_cpp_symbols = true;
    else
    {
      std::cerr << "Env var 'BPFTRACE_NO_CPP_DEMANGLE' did not contain a valid value (0 or 1)." << std::endl;
      return 1;
    }
  }

  if (const char* env_p = std::getenv("BPFTRACE_MAP_KEYS_MAX"))
  {
    uint64_t proposed;
    std::istringstream stringstream(env_p);
    if (!(stringstream >> proposed)) {
      std::cerr << "Env var 'BPFTRACE_MAP_KEYS_MAX' did not contain a valid uint64_t, or was zero-valued." << std::endl;
      return 1;
    }
    // no maximum is enforced. Imagine a map recording a timestamp by struct page *: this could exceed 10M entries.
    bpftrace.mapmax_ = proposed;
  }

  if (cmd_str)
    bpftrace.cmd_ = cmd_str;

  if (TracepointFormatParser::parse(driver.root_) == false)
    return 1;

  if (bt_debug != DebugLevel::kNone)
  {
    ast::Printer p(std::cout);
    driver.root_->accept(p);
    std::cout << std::endl;
  }

  ClangParser clang;
  std::vector<std::string> extra_flags;
  {
    struct utsname utsname;
    uname(&utsname);
    std::string ksrc, kobj;
    auto kdirs = get_kernel_dirs(utsname);
    ksrc = std::get<0>(kdirs);
    kobj = std::get<1>(kdirs);

    if (ksrc != "")
      extra_flags = get_kernel_cflags(utsname.machine, ksrc, kobj);
  }
  clang.parse(driver.root_, bpftrace, extra_flags);

  if (script.empty())
  {
    err = driver.parse_file(file_name);
  }
  else
  {
    err = driver.parse_str(script);
  }

  if (err)
    return err;

  ast::SemanticAnalyser semantics(driver.root_, bpftrace);
  err = semantics.analyse();
  if (err)
    return err;

  err = semantics.create_maps(bt_debug != DebugLevel::kNone);
  if (err)
    return err;

  ast::CodegenLLVM llvm(driver.root_, bpftrace);
  auto bpforc = llvm.compile(bt_debug);

  if (bt_debug != DebugLevel::kNone)
    return 0;

  // Empty signal handler for cleanly terminating the program
  struct sigaction act = {};
  act.sa_handler = [](int) { };
  sigaction(SIGINT, &act, NULL);

  int num_probes = bpftrace.num_probes();
  if (num_probes == 0)
  {
    std::cout << "No probes to attach" << std::endl;
    return 1;
  }
  else if (num_probes == 1)
    std::cout << "Attaching " << bpftrace.num_probes() << " probe..." << std::endl;
  else
    std::cout << "Attaching " << bpftrace.num_probes() << " probes..." << std::endl;

  err = bpftrace.run(move(bpforc));
  if (err)
    return err;

  std::cout << "\n\n";

  err = bpftrace.print_maps();
  if (err)
    return err;

  return 0;
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <SD.h>

#include "session.h"
#include "bits.h"

#include "config.h"

void init_session_header(uint8_t* buf, uint64_t timestamp, uint16_t channels)
{
	buf[0] = 0xec; // Magic #1.
	buf[1] = 0x09; // Magic #2.
	buf[2] = 0x00; // Format epoch.
	buf[3] = 0x00; // Unused 1.
	buf[4] = 0x00; // Unused 2.
	buf[5] = 0x00; // Unused 3.
	uint16_t be_channels = swap_endian_16(channels);
	memcpy(buf+6, &be_channels, 2);
	// Last eight bytes are for the timestamp.
	// XXX: this assumes we're compiled little-endian. Better to make it
	//      endianness-agnostic.
	uint64_t be_ts = swap_endian_64(timestamp);
	memcpy(buf+8, &be_ts, 8);
}

int session_write(session *s, uint8_t *buf, size_t len)
{
	int written = s->fh.write(buf, len);
	s->fh.flush();
	return written;
}

// Values in data and delta_t should both be big-endian.
int session_write_frame(session *s, uint8_t *data, uint32_t delta_t)
{
	uint8_t frame[FRAME_SIZE];
	frame[0] = s->counter; // Frame counter
	s->counter++;
	s->frame_time = delta_t;
	memcpy(frame+1, &delta_t, 4); // Time since session start
	memset(frame+5, 0, 3); // Unused bytes
	// Memory usage can be reduced here if needed.
	memcpy(frame+8, data, FRAME_SAMPLE_SIZE + CHANNELS); // ECG samples
	return session_write(s, frame, FRAME_SIZE);
}

// Given a *char of length at least 11, get_fname stores a string of the
// form "ecgses.XXX", where XXX is a hexadecimal integer between 0x0 and
// 0xfff. If no such unused filename exists -1 will be returned,
// otherwise the value of the integer used for the suffix plus one
// (assuming contiguity of session files, this is likely to be valid for
// the next one).
int get_fname(char *fname, int base_suffix)
{
	int suf = base_suffix;
	strncpy(fname, "ecgses.", 7);
	char valid = 0;
	while (!valid && suf < 0x1000) {
		snprintf(fname+7, 4, "%03x", suf);
		if (!SD.exists(fname)) {
			valid = 1;
		}
		suf++;
	}
	return (valid ? suf : -1);
}

session* session_init(uint64_t timestamp, uint16_t channels)
{
	session *s = (session*) malloc(sizeof(session));
	if (s == NULL) {
		return NULL;
	}
	char fname[11];
	int next_suffix = get_fname(fname, 0);
	if (next_suffix < 0) {
		#ifdef DEBUG
		Serial.println("Could not find an unused filename.");
		Serial.println("Is the SD card full?");
		#endif
		free(s);
		return NULL;
	}
	s->next_suffix = next_suffix;
	s->init_time = timestamp;
	s->fh = SD.open(fname, FILE_WRITE);
	if (!s->fh) {
		#ifdef DEBUG
		Serial.print("Could not open file ");
		Serial.print(fname);
		Serial.println(" for writing.");
		#endif
		free(s);
		return NULL;
	}
	uint8_t buf[SESSION_HEADER_SIZE];
	#ifdef DEBUG
	Serial.print("Writing session header: ");
	for (int i = 0; i < 16; i++) {
		Serial.print(buf[i], HEX);
	}
	Serial.print('\n');
	#endif
	init_session_header(buf, timestamp, channels);
	session_write(s, buf, SESSION_HEADER_SIZE);
	return s;
}

void session_close(session *s)
{
	s->fh.close();
	free(s);
}
<commit_msg>More comments<commit_after>#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <SD.h>

#include "session.h"
#include "bits.h"

#include "config.h"

void init_session_header(uint8_t* buf, uint64_t timestamp, uint16_t channels)
{
	buf[0] = 0xec; // Magic #1.
	buf[1] = 0x09; // Magic #2.
	buf[2] = 0x00; // Format epoch.
	buf[3] = 0x00; // Unused 1.
	buf[4] = 0x00; // Unused 2.
	buf[5] = 0x00; // Unused 3.
	uint16_t be_channels = swap_endian_16(channels);
	memcpy(buf+6, &be_channels, 2);
	// Last eight bytes are for the timestamp.
	// XXX: this assumes we're compiled little-endian. Better to make it
	//      endianness-agnostic.
	uint64_t be_ts = swap_endian_64(timestamp);
	memcpy(buf+8, &be_ts, 8);
}

// Write `len` bytes from `buf` to the session file.
int session_write(session *s, uint8_t *buf, size_t len)
{
	int written = s->fh.write(buf, len);
	s->fh.flush();
	return written;
}

// Write a frame the session file. `data` should contain `CHANNELS`
// samples from the device.
// Values in data and delta_t should both be big-endian.
int session_write_frame(session *s, uint8_t *data, uint32_t delta_t)
{
	uint8_t frame[FRAME_SIZE];
	frame[0] = s->counter; // Frame counter
	s->counter++;
	s->frame_time = delta_t;
	memcpy(frame+1, &delta_t, 4); // Time since session start
	memset(frame+5, 0, 3); // Unused bytes
	// Memory usage can be reduced here if needed.
	memcpy(frame+8, data, FRAME_SAMPLE_SIZE + CHANNELS); // ECG samples
	return session_write(s, frame, FRAME_SIZE);
}

// Given a *char of length at least 11, get_fname stores a string of the
// form "ecgses.XXX", where XXX is a hexadecimal integer between 0x0 and
// 0xfff. If no such unused filename exists -1 will be returned,
// otherwise the value of the integer used for the suffix plus one
// (assuming contiguity of session files, this is likely to be valid for
// the next one).
int get_fname(char *fname, int base_suffix)
{
	int suf = base_suffix;
	strncpy(fname, "ecgses.", 7);
	char valid = 0;
	while (!valid && suf < 0x1000) {
		snprintf(fname+7, 4, "%03x", suf);
		if (!SD.exists(fname)) {
			valid = 1;
		}
		suf++;
	}
	return (valid ? suf : -1);
}

// Initialize a session file and returns a session pointer. NULL on
// error.
session* session_init(uint64_t timestamp, uint16_t channels)
{
	session *s = (session*) malloc(sizeof(session));
	if (s == NULL) {
		return NULL;
	}
	char fname[11];
	int next_suffix = get_fname(fname, 0);
	if (next_suffix < 0) {
		#ifdef DEBUG
		Serial.println("Could not find an unused filename.");
		Serial.println("Is the SD card full?");
		#endif
		free(s);
		return NULL;
	}
	s->next_suffix = next_suffix;
	s->init_time = timestamp;
	s->fh = SD.open(fname, FILE_WRITE);
	if (!s->fh) {
		#ifdef DEBUG
		Serial.print("Could not open file ");
		Serial.print(fname);
		Serial.println(" for writing.");
		#endif
		free(s);
		return NULL;
	}
	uint8_t buf[SESSION_HEADER_SIZE];
	#ifdef DEBUG
	Serial.print("Writing session header: ");
	for (int i = 0; i < 16; i++) {
		Serial.print(buf[i], HEX);
	}
	Serial.print('\n');
	#endif
	init_session_header(buf, timestamp, channels);
	session_write(s, buf, SESSION_HEADER_SIZE);
	return s;
}

// Close session file, free heap memory.
void session_close(session *s)
{
	s->fh.close();
	free(s);
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager.
#pragma once

#include <vector>
#include <random>
#include "vector.hpp"

namespace lsh {
  class mask {
    private:
      /**
       * The number of dimensions in vector projections.
       */
      unsigned int width_;

      /**
       * The randomly chosen indices to pick for vector projections.
       */
      std::vector<unsigned int> indices_;

    public:
      /**
       * Construct a new mask.
       *
       * @param dimensionality The dimensionality of vectors to mask.
       * @param width The number of dimensions in vector projections.
       */
      mask(unsigned int dimensions, unsigned int width);

      /**
       * Project a vector, reducing it to a dimensionality specified by this mask.
       *
       * @param vector The vector to project.
       * @return The projected vector.
       */
      vector project(const vector& vector) const;
  };
}
<commit_msg>Add comment to mask class<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager.
#pragma once

#include <vector>
#include <random>
#include "vector.hpp"

namespace lsh {
  /**
   * The mask class acts as sort of a bit mask that can reduce the dimensionality of
   * vectors by a random projection.
   */
  class mask {
    private:
      /**
       * The number of dimensions in vector projections.
       */
      unsigned int width_;

      /**
       * The randomly chosen indices to pick for vector projections.
       */
      std::vector<unsigned int> indices_;

    public:
      /**
       * Construct a new mask.
       *
       * @param dimensionality The dimensionality of vectors to mask.
       * @param width The number of dimensions in vector projections.
       */
      mask(unsigned int dimensions, unsigned int width);

      /**
       * Project a vector, reducing it to a dimensionality specified by this mask.
       *
       * @param vector The vector to project.
       * @return The projected vector.
       */
      vector project(const vector& vector) const;
  };
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WriterFilterDllApi.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2006-10-24 09:27:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_WRITERFILTERDLLAPI_H
#define INCLUDED_WRITERFILTERDLLAPI_H

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif

#if defined(WRITERFILTER_DLLIMPLEMENTATION)
#define WRITERFILTER_DLLPUBLIC  SAL_DLLPUBLIC_EXPORT
#else
#define WRITERFILTER_DLLPUBLIC  SAL_DLLPUBLIC_IMPORT
#endif
#define WRITERFILTER_DLLPRIVATE SAL_DLLPRIVATE

#endif /* INCLUDED_WRITERFILTERDLLAPI_H */
<commit_msg>INTEGRATION: CWS changefileheader (1.3.36); FILE MERGED 2008/04/01 16:06:40 thb 1.3.36.2: #i85898# Stripping all external header guards 2008/03/28 15:52:56 rt 1.3.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: WriterFilterDllApi.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_WRITERFILTERDLLAPI_H
#define INCLUDED_WRITERFILTERDLLAPI_H

#include "sal/types.h"

#if defined(WRITERFILTER_DLLIMPLEMENTATION)
#define WRITERFILTER_DLLPUBLIC  SAL_DLLPUBLIC_EXPORT
#else
#define WRITERFILTER_DLLPUBLIC  SAL_DLLPUBLIC_IMPORT
#endif
#define WRITERFILTER_DLLPRIVATE SAL_DLLPRIVATE

#endif /* INCLUDED_WRITERFILTERDLLAPI_H */
<|endoftext|>