<commit_before>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100

#include <Arduino.h>

#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>

enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } moveDirection = STOP;

MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_4, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;

int moveSpeed = 100;
int lineFollowFlag = 0;
bool start = false;
bool makeNoise = false;
bool obstacle = false;

unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();

DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

void forward() {
  motorL.run(-MOVESPEED);
  motorR.run(MOVESPEED);
}

void backward() {
  motorL.run(MOVESPEED);
  motorR.run(-MOVESPEED);
}

void turnLeft() {
  motorL.run(-MOVESPEED / 10);
  motorR.run(MOVESPEED);
}

void turnRight() {
  motorL.run(-MOVESPEED);
  motorR.run(MOVESPEED / 10);
}

void stop() {
  moveDirection = STOP;
  motorL.run(0);
  motorR.run(0);
}

bool distanceWarning(double distanceCmLimit) {
  if (ultrasonicSensor.distanceCm() < distanceCmLimit) {
    return true;
  } else {
    return false;
  }
}

void move() {
  if (distanceWarning(DISTANCECMCRITICAL)) {
    if (moveDirection == BACKWARD) {
      backward();
    } else {
      stop();
    }
  } else {
    switch (moveDirection) {
      case FORWARD:
      forward();
      break;
      case BACKWARD:
      backward();
      break;
      case LEFT:
      turnLeft();
      break;
      case RIGHT:
      turnRight();
      break;
      case STOP:
      stop();
      break;
    }
  }
}

void toggleStart() {
  start = !start;
  if (start) {
    rgbLed.setColor(1, 0, 10, 0);
    rgbLed.show();
  } else {
    rgbLed.setColor(1, 0, 0, 0);
    rgbLed.show();
    moveDirection = STOP;
  }
  delay(250);
}

void bottomCheck() {
  if (analogRead(A7) == 0) {
    toggleStart();
  }
}

void irCheck() {
  unsigned long value;

  if (ir.decode()) {
    value = ir.value;
    switch (value >> 16 & 0xff) {
      case IR_BUTTON_LEFT:
      moveDirection = LEFT;
      break;
      case IR_BUTTON_RIGHT:
      moveDirection = RIGHT;
      break;
      case IR_BUTTON_DOWN:
      moveDirection = BACKWARD;
      break;
      case IR_BUTTON_UP:
      moveDirection = FORWARD;
      break;
      case IR_BUTTON_SETTING:
      moveDirection = STOP;
      break;
      case IR_BUTTON_A:
      toggleStart();
      break;
    }
  }
}

void silent() {
  buzzer.noTone();
  rgbLed.setColor(2, 0, 0, 0);
  rgbLed.show();
}

void warning() {
  rgbLed.setColor(2, 0, 0, 10);
  rgbLed.show();
}

void alarm() {
  //buzzer.tone(262, 100);
  rgbLed.setColor(2, 10, 0, 0);
  rgbLed.show();
}

void noiseCheck() {
  if (start and distanceWarning(DISTANCECMCRITICAL)) {
    if (wait == false) {
      wait = true;
      waitTimer = millis();
    }
    if (wait and millis() - waitTimer > WAITINTERVAL) {
      makeNoise = true;
      alarm();
    } else {
      warning();
    }
  } else {
    wait = false;
    makeNoise = false;
    silent();
  }
}

void autonomous() {
  byte randNumber;

  randomSeed(analogRead(6));
  randNumber = random(2);
  if (!distanceWarning(DISTANCECMCRITICAL) and !obstacle) {
    moveDirection = FORWARD;
  } else {
    obstacle = true;
  }
  if (obstacle) {
    if (distanceWarning(DISTANCECMWARNING)) {
      moveDirection = BACKWARD;
    } else {
      switch (randNumber) {
        case 0:
        moveDirection = LEFT;
        turnLeft();
        delay(400);
        break;
        case 1:
        moveDirection = RIGHT;
        turnRight();
        delay(400);
        break;
      }
      obstacle = false;
    }
  }
}

void sendData() {
  if (millis() - publishTimer > PUBLSIHINTERVAL) {
    publishTimer = millis();
    root["start"] = start;
    root["moveDirection"] = moveDirection;
    root["wait"] = wait;
    root["makeNoise"] = makeNoise;
    root["distanceCm"] = ultrasonicSensor.distanceCm();
    root["lightSensor"] = lightSensor.read();
    root["temperature"] = temperature.temperature();
    root.prettyPrintTo(Serial);
    Serial << endl;
  }
}

void setup() {
  Serial.begin(115200);
  Serial << endl << endl;
  pinMode(A7, INPUT);
  ir.begin();
  rgbLed.setColor(0, 0, 0, 0);
  rgbLed.show();
}

void loop() {
  bottomCheck();
  irCheck();
  noiseCheck();
  sendData();
  move();
  if (start) {
    switch (lineFollower.readSensors()) {
      case S1_IN_S2_IN:
      tryFollowLine = true;
      moveDirection = FORWARD;
      lineFollowFlag = 10;
      break;
      case S1_IN_S2_OUT:
      tryFollowLine = true;
      moveDirection = FORWARD;
      if (lineFollowFlag > 1) lineFollowFlag--;
      break;
      case S1_OUT_S2_IN:
      tryFollowLine = true;
      moveDirection = FORWARD;
      if (lineFollowFlag < 20) lineFollowFlag++;
      break;
      case S1_OUT_S2_OUT:
      if (tryFollowLine) {
        tryFollowLine = !tryFollowLine;
        tryFollowLineTimer = millis();
      }
      if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
        if (lineFollowFlag == 10) moveDirection = BACKWARD;
        if (lineFollowFlag < 10) moveDirection = LEFT;
        if (lineFollowFlag > 10) moveDirection = RIGHT;
      } else {
        autonomous();
      }
      break;
    }
  }
}
<commit_msg>started pir support<commit_after>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100

#include <Arduino.h>

#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>

enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } moveDirection = STOP;

MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_4, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;
MePIRMotionSensor pirMotionSensor(PORT_1);

int moveSpeed = 100;
int lineFollowFlag = 0;
bool start = false;
bool makeNoise = false;
bool obstacle = false;

unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();

DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

void forward() {
  motorL.run(-MOVESPEED);
  motorR.run(MOVESPEED);
}

void backward() {
  motorL.run(MOVESPEED);
  motorR.run(-MOVESPEED);
}

void turnLeft() {
  motorL.run(-MOVESPEED / 10);
  motorR.run(MOVESPEED);
}

void turnRight() {
  motorL.run(-MOVESPEED);
  motorR.run(MOVESPEED / 10);
}

void stop() {
  moveDirection = STOP;
  motorL.run(0);
  motorR.run(0);
}

bool distanceWarning(double distanceCmLimit) {
  if (ultrasonicSensor.distanceCm() < distanceCmLimit) {
    return true;
  } else {
    return false;
  }
}

void move() {
  if (distanceWarning(DISTANCECMCRITICAL)) {
    if (moveDirection == BACKWARD) {
      backward();
    } else {
      stop();
    }
  } else {
    switch (moveDirection) {
      case FORWARD:
      forward();
      break;
      case BACKWARD:
      backward();
      break;
      case LEFT:
      turnLeft();
      break;
      case RIGHT:
      turnRight();
      break;
      case STOP:
      stop();
      break;
    }
  }
}

void toggleStart() {
  start = !start;
  if (start) {
    rgbLed.setColor(1, 0, 10, 0);
    rgbLed.show();
  } else {
    rgbLed.setColor(1, 0, 0, 0);
    rgbLed.show();
    moveDirection = STOP;
  }
  delay(250);
}

void bottomCheck() {
  if (analogRead(A7) == 0) {
    toggleStart();
  }
}

void irCheck() {
  unsigned long value;

  if (ir.decode()) {
    value = ir.value;
    switch (value >> 16 & 0xff) {
      case IR_BUTTON_LEFT:
      moveDirection = LEFT;
      break;
      case IR_BUTTON_RIGHT:
      moveDirection = RIGHT;
      break;
      case IR_BUTTON_DOWN:
      moveDirection = BACKWARD;
      break;
      case IR_BUTTON_UP:
      moveDirection = FORWARD;
      break;
      case IR_BUTTON_SETTING:
      moveDirection = STOP;
      break;
      case IR_BUTTON_A:
      toggleStart();
      break;
    }
  }
}

void silent() {
  buzzer.noTone();
  rgbLed.setColor(2, 0, 0, 0);
  rgbLed.show();
}

void warning() {
  rgbLed.setColor(2, 0, 0, 10);
  rgbLed.show();
}

void alarm() {
  //buzzer.tone(262, 100);
  rgbLed.setColor(2, 10, 0, 0);
  rgbLed.show();
}

void noiseCheck() {
  if (start and distanceWarning(DISTANCECMCRITICAL)) {
    if (wait == false) {
      wait = true;
      waitTimer = millis();
    }
    if (wait and millis() - waitTimer > WAITINTERVAL) {
      makeNoise = true;
      alarm();
    } else {
      warning();
    }
  } else {
    wait = false;
    makeNoise = false;
    silent();
  }
}

void autonomous() {
  byte randNumber;

  randomSeed(analogRead(6));
  randNumber = random(2);
  if (!distanceWarning(DISTANCECMCRITICAL) and !obstacle) {
    moveDirection = FORWARD;
  } else {
    obstacle = true;
  }
  if (obstacle) {
    if (distanceWarning(DISTANCECMWARNING)) {
      moveDirection = BACKWARD;
    } else {
      switch (randNumber) {
        case 0:
        moveDirection = LEFT;
        turnLeft();
        delay(400);
        break;
        case 1:
        moveDirection = RIGHT;
        turnRight();
        delay(400);
        break;
      }
      obstacle = false;
    }
  }
}

void sendData() {
  if (millis() - publishTimer > PUBLSIHINTERVAL) {
    publishTimer = millis();
    root["start"] = start;
    root["moveDirection"] = moveDirection;
    root["wait"] = wait;
    root["makeNoise"] = makeNoise;
    root["distanceCm"] = ultrasonicSensor.distanceCm();
    root["lightSensor"] = lightSensor.read();
    root["temperature"] = temperature.temperature();
    root["isHumanDetected"] = pirMotionSensor.isHumanDetected();
    root.prettyPrintTo(Serial);
    Serial << endl;
  }
}

void setup() {
  Serial.begin(115200);
  Serial << endl << endl;
  pinMode(A7, INPUT);
  ir.begin();
  pirMotionSensor.SetPirMotionMode(1);
  rgbLed.setColor(0, 0, 0, 0);
  rgbLed.show();
}

void loop() {
  bottomCheck();
  irCheck();
  noiseCheck();
  sendData();
  move();
  if (start) {
    switch (lineFollower.readSensors()) {
      case S1_IN_S2_IN:
      tryFollowLine = true;
      moveDirection = FORWARD;
      lineFollowFlag = 10;
      break;
      case S1_IN_S2_OUT:
      tryFollowLine = true;
      moveDirection = FORWARD;
      if (lineFollowFlag > 1) lineFollowFlag--;
      break;
      case S1_OUT_S2_IN:
      tryFollowLine = true;
      moveDirection = FORWARD;
      if (lineFollowFlag < 20) lineFollowFlag++;
      break;
      case S1_OUT_S2_OUT:
      if (tryFollowLine) {
        tryFollowLine = !tryFollowLine;
        tryFollowLineTimer = millis();
      }
      if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
        if (lineFollowFlag == 10) moveDirection = BACKWARD;
        if (lineFollowFlag < 10) moveDirection = LEFT;
        if (lineFollowFlag > 10) moveDirection = RIGHT;
      } else {
        autonomous();
      }
      break;
    }
  }
}
<|endoftext|>


<commit_before>/*
 *  main.cpp
 *  FaffoCue
 *
 *  Copyright (C) Simon Harris 2010-2013.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

// This is very rough-and-ready main.cpp, until we can get the mainloop
// integrated with Cocoa and Winforms/WPF.

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
#include <TCLAP/CmdLine.h>
#include <sstream>

////////////////////////////////////////////////////////////
// FaffoCue headers
////////////////////////////////////////////////////////////
#include "Text.hpp"
#include "Keys.hpp"
#include "Resources.hpp"

#include "App.hpp"

namespace fcmain
{
	unsigned int resWidth, resHeight;
	bool fullscreen;
	std::string script_file, font_file;
	double font_size;
	////////////////////////////////////////////////////////////
	// Command-line argument parsing
	//
	// -t --font: font name
	// -z --font-size
	// -r --resolution: screen resolution
	// -f --fullscreen: overrides resolution
	// -w --windowed: in case fullscreen is somehow the default
	// unlabeled: autocue script (extension .fcx for xml, .fct for text)
	////////////////////////////////////////////////////////////
	void parse_cmdline(int argc, char *argv[])
	{
		try {
			TCLAP::CmdLine cmd("These command-line arguments are not recommended for production setups.", ' ', "3.0");

			TCLAP::ValueArg<std::string>
			resolution("r", "resolution", "Screen resolution", true, "!", "<number>x<number>", cmd),
			font_file("t", "font", "Font names", true, "!", "string", cmd);

			TCLAP::ValueArg<float>
			font_size("z", "font-size", "Font size", false, 48.f, "positive number", cmd);

			TCLAP::SwitchArg
			fullscreen("f", "fullscreen", "Fullscreen", cmd),
			windowed("w", "windowed", "Windowed", cmd, true);

			TCLAP::UnlabeledValueArg<std::string>
			script_file("script-file", "Autocue script to load", false, "", "file path");

			cmd.parse(argc, argv);

			// fc-specific parsing time

			fcmain::fullscreen = fullscreen.getValue() && !windowed.getValue();
			fcmain::font_file = font_file.getValue();
			fcmain::font_size = font_size.getValue();
			fcmain::script_file = script_file.getValue();

			{
				std::stringstream ss(resolution.getValue());
				char dummy;
				/* try: */ ss >> fcmain::resWidth >> dummy >> fcmain::resHeight;
				if (!ss) throw TCLAP::ArgException("Bad resolution format (should be <number>x<number>)", "resolution");
			}
		}
		catch (TCLAP::ArgException& e) {
			std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
			exit(1);
		}

	}

}; // ns

////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
	//fcmain::parse_cmdline(argc, argv);
	// @HACK@
	fcmain::resWidth = 800; fcmain::resHeight = 600;
	fcmain::font_size = 14.f;
	fcmain::fullscreen = false;

    //sf::RenderWindow App(sf::VideoMode(640, 480), "FaffoCue");

	FaffoCue::App app(sf::VideoMode(fcmain::resWidth, fcmain::resHeight), false, false, fcmain::font_size);

	//App.SetFramerateLimit(60);
	//App.UseVerticalSync(true);

//	sf::Font fnt;
	fcmain::font_file = FaffoCue::_impl::resources_location() + "/AurulentSans-Bold.otf"; // @HACK@
	app.font().loadFromFile(fcmain::font_file);
	app.text().add_line("The quick brown fox jumps over the lazy dog. And here's another sentence because the last one wasn't really long enough to test the word wrap thoroughly. But this should be okay.");
	app.text().add_line("And now, for a limited time only, a second line of text!");

//	sf::View  &cxView  = app.cx().GetDefaultView();
//	const sf::Input &cxInput = app.cx().GetInput();

	double x = 0;
	bool fullscreen = false;

	app.main();

    return EXIT_SUCCESS;
}
<commit_msg>Added extra line to sample text<commit_after>/*
 *  main.cpp
 *  FaffoCue
 *
 *  Copyright (C) Simon Harris 2010-2013.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

// This is very rough-and-ready main.cpp, until we can get the mainloop
// integrated with Cocoa and Winforms/WPF.

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
#include <TCLAP/CmdLine.h>
#include <sstream>

////////////////////////////////////////////////////////////
// FaffoCue headers
////////////////////////////////////////////////////////////
#include "Text.hpp"
#include "Keys.hpp"
#include "Resources.hpp"

#include "App.hpp"

namespace fcmain
{
	unsigned int resWidth, resHeight;
	bool fullscreen;
	std::string script_file, font_file;
	double font_size;
	////////////////////////////////////////////////////////////
	// Command-line argument parsing
	//
	// -t --font: font name
	// -z --font-size
	// -r --resolution: screen resolution
	// -f --fullscreen: overrides resolution
	// -w --windowed: in case fullscreen is somehow the default
	// unlabeled: autocue script (extension .fcx for xml, .fct for text)
	////////////////////////////////////////////////////////////
	void parse_cmdline(int argc, char *argv[])
	{
		try {
			TCLAP::CmdLine cmd("These command-line arguments are not recommended for production setups.", ' ', "3.0");

			TCLAP::ValueArg<std::string>
			resolution("r", "resolution", "Screen resolution", true, "!", "<number>x<number>", cmd),
			font_file("t", "font", "Font names", true, "!", "string", cmd);

			TCLAP::ValueArg<float>
			font_size("z", "font-size", "Font size", false, 48.f, "positive number", cmd);

			TCLAP::SwitchArg
			fullscreen("f", "fullscreen", "Fullscreen", cmd),
			windowed("w", "windowed", "Windowed", cmd, true);

			TCLAP::UnlabeledValueArg<std::string>
			script_file("script-file", "Autocue script to load", false, "", "file path");

			cmd.parse(argc, argv);

			// fc-specific parsing time

			fcmain::fullscreen = fullscreen.getValue() && !windowed.getValue();
			fcmain::font_file = font_file.getValue();
			fcmain::font_size = font_size.getValue();
			fcmain::script_file = script_file.getValue();

			{
				std::stringstream ss(resolution.getValue());
				char dummy;
				/* try: */ ss >> fcmain::resWidth >> dummy >> fcmain::resHeight;
				if (!ss) throw TCLAP::ArgException("Bad resolution format (should be <number>x<number>)", "resolution");
			}
		}
		catch (TCLAP::ArgException& e) {
			std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
			exit(1);
		}

	}

}; // ns

////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
	//fcmain::parse_cmdline(argc, argv);
	// @HACK@
	fcmain::resWidth = 800; fcmain::resHeight = 600;
	fcmain::font_size = 14.f;
	fcmain::fullscreen = false;

    //sf::RenderWindow App(sf::VideoMode(640, 480), "FaffoCue");

	FaffoCue::App app(sf::VideoMode(fcmain::resWidth, fcmain::resHeight), false, false, fcmain::font_size);

	//App.SetFramerateLimit(60);
	//App.UseVerticalSync(true);

//	sf::Font fnt;
	fcmain::font_file = FaffoCue::_impl::resources_location() + "/AurulentSans-Bold.otf"; // @HACK@
	app.font().loadFromFile(fcmain::font_file);
	app.text().add_line("The quick brown fox jumps over the lazy dog. And here's another sentence because the last one wasn't really long enough to test the word wrap thoroughly. But this should be okay.");
	app.text().add_line("And now, for a limited time only, a second line of text!");
	app.text().add_line("0 1 2 3 4 5 6 7 8 9");

//	sf::View  &cxView  = app.cx().GetDefaultView();
//	const sf::Input &cxInput = app.cx().GetInput();

	double x = 0;
	bool fullscreen = false;

	app.main();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*

This file is part of VROOM.

Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "structures/typedefs.h"
#include "structures/vroom/input/input.h"
#include "utils/exception.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

void display_usage() {
  std::string usage = "VROOM Copyright (C) 2015-2018, Julien Coupey\n";
  usage += "Version: " + vroom::get_version() + "\n";
  usage += "Usage:\n\tvroom [OPTION]... \"INPUT\"";
  usage += "\n\tvroom [OPTION]... -i FILE\n";
  usage += "Options:\n";
  usage += "\t-a PROFILE:HOST (=" + vroom::DEFAULT_PROFILE +
           ":0.0.0.0)\t Routing server\n";
  usage += "\t-p PROFILE:PORT (=" + vroom::DEFAULT_PROFILE +
           ":5000),\t Routing server port\n";
  usage += "\t-g,\t\t\t add detailed route geometry and indicators\n";
  usage += "\t-i FILE,\t\t read input from FILE rather than from stdin\n";
  usage += "\t-o OUTPUT,\t\t output file name\n";
  usage += "\t-r ROUTER (=osrm),\t osrm or libosrm\n";
  usage += "\t-t THREADS (=4),\t number of threads to use\n";
  usage += "\t-x EXPLORE (=5),\t exploration level to use (0..5)";
  std::cout << usage << std::endl;
  exit(0);
}

int main(int argc, char** argv) {
  // Load default command-line options.
  vroom::io::CLArgs cl_args;

  // Parsing command-line arguments.
  const char* optString = "a:gi:o:p:r:t:x:h?";
  int opt = getopt(argc, argv, optString);

  std::string router_arg;
  std::string nb_threads_arg = std::to_string(cl_args.nb_threads);
  std::string exploration_level_arg = std::to_string(cl_args.exploration_level);

  while (opt != -1) {
    switch (opt) {
    case 'a':
      vroom::io::update_host(cl_args.servers, optarg);
      break;
    case 'g':
      cl_args.geometry = true;
      break;
    case 'h':
      display_usage();
      break;
    case 'i':
      cl_args.input_file = optarg;
      break;
    case 'o':
      cl_args.output_file = optarg;
      break;
    case 'p':
      vroom::io::update_port(cl_args.servers, optarg);
      break;
    case 'r':
      router_arg = optarg;
      break;
    case 't':
      nb_threads_arg = optarg;
      break;
    case 'x':
      exploration_level_arg = optarg;
      break;
    default:
      break;
    }
    opt = getopt(argc, argv, optString);
  }

  try {
    // Needs to be done after previous switch to make sure the
    // appropriate output file is set.
    cl_args.nb_threads = std::stoul(nb_threads_arg);
    cl_args.exploration_level = std::stoul(exploration_level_arg);

    cl_args.exploration_level =
      std::min(cl_args.exploration_level, cl_args.max_exploration_level);
  } catch (const std::exception& e) {
    std::string message = "Invalid numerical value.";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    std::string message = "Invalid routing engine: " + router_arg;
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }

  // Add default server if none provided in input.
  if (cl_args.servers.empty()) {
    cl_args.servers.emplace(vroom::DEFAULT_PROFILE, vroom::Server());
  }

  if (cl_args.input_file.empty()) {
    // Getting input from command-line.
    if (argc == optind) {
      // Missing argument!
      display_usage();
    }
    cl_args.input = argv[optind];
  } else {
    // Getting input from provided file.
    std::ifstream ifs(cl_args.input_file);
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    cl_args.input = buffer.str();
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol =
      problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.get_message() << std::endl;
    vroom::io::write_to_json({1, e.get_message()}, false, cl_args.output_file);
    exit(1);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({1, e.what()}, false, cl_args.output_file);
    exit(1);
  }

  return 0;
}
<commit_msg>Cleanup usage output.<commit_after>/*

This file is part of VROOM.

Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "structures/typedefs.h"
#include "structures/vroom/input/input.h"
#include "utils/exception.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

void display_usage() {
  std::string usage = "VROOM Copyright (C) 2015-2018, Julien Coupey\n";
  usage += "Version: " + vroom::get_version() + "\n";
  usage += "Usage:\n\tvroom [OPTION]... \"INPUT\"";
  usage += "\n\tvroom [OPTION]... -i FILE\n";
  usage += "Options:\n";
  usage += "\t-a PROFILE:HOST (=" + vroom::DEFAULT_PROFILE +
           ":0.0.0.0)\t routing server\n";
  usage += "\t-p PROFILE:PORT (=" + vroom::DEFAULT_PROFILE +
           ":5000),\t routing server port\n";
  usage += "\t-g,\t\t\t\t add detailed route geometry and indicators\n";
  usage += "\t-i FILE,\t\t\t read input from FILE rather than from stdin\n";
  usage += "\t-o OUTPUT,\t\t\t output file name\n";
  usage += "\t-r ROUTER (=osrm),\t\t osrm or libosrm\n";
  usage += "\t-t THREADS (=4),\t\t number of threads to use\n";
  usage += "\t-x EXPLORE (=5),\t\t exploration level to use (0..5)";
  std::cout << usage << std::endl;
  exit(0);
}

int main(int argc, char** argv) {
  // Load default command-line options.
  vroom::io::CLArgs cl_args;

  // Parsing command-line arguments.
  const char* optString = "a:gi:o:p:r:t:x:h?";
  int opt = getopt(argc, argv, optString);

  std::string router_arg;
  std::string nb_threads_arg = std::to_string(cl_args.nb_threads);
  std::string exploration_level_arg = std::to_string(cl_args.exploration_level);

  while (opt != -1) {
    switch (opt) {
    case 'a':
      vroom::io::update_host(cl_args.servers, optarg);
      break;
    case 'g':
      cl_args.geometry = true;
      break;
    case 'h':
      display_usage();
      break;
    case 'i':
      cl_args.input_file = optarg;
      break;
    case 'o':
      cl_args.output_file = optarg;
      break;
    case 'p':
      vroom::io::update_port(cl_args.servers, optarg);
      break;
    case 'r':
      router_arg = optarg;
      break;
    case 't':
      nb_threads_arg = optarg;
      break;
    case 'x':
      exploration_level_arg = optarg;
      break;
    default:
      break;
    }
    opt = getopt(argc, argv, optString);
  }

  try {
    // Needs to be done after previous switch to make sure the
    // appropriate output file is set.
    cl_args.nb_threads = std::stoul(nb_threads_arg);
    cl_args.exploration_level = std::stoul(exploration_level_arg);

    cl_args.exploration_level =
      std::min(cl_args.exploration_level, cl_args.max_exploration_level);
  } catch (const std::exception& e) {
    std::string message = "Invalid numerical value.";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    std::string message = "Invalid routing engine: " + router_arg;
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }

  // Add default server if none provided in input.
  if (cl_args.servers.empty()) {
    cl_args.servers.emplace(vroom::DEFAULT_PROFILE, vroom::Server());
  }

  if (cl_args.input_file.empty()) {
    // Getting input from command-line.
    if (argc == optind) {
      // Missing argument!
      display_usage();
    }
    cl_args.input = argv[optind];
  } else {
    // Getting input from provided file.
    std::ifstream ifs(cl_args.input_file);
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    cl_args.input = buffer.str();
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol =
      problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.get_message() << std::endl;
    vroom::io::write_to_json({1, e.get_message()}, false, cl_args.output_file);
    exit(1);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({1, message}, false, cl_args.output_file);
    exit(1);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({1, e.what()}, false, cl_args.output_file);
    exit(1);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "libtg.hpp"

using namespace std;

// argv[0]
string exe;

void usage() {
  cerr << "Usage mode: " << exe << " [options...] \n";
  cerr << endl;
  cerr << "I/O options:\n";
  cerr << "\t-i\t<file path>\tRead formula from file.\n";
  cerr << "\t-oinfo\t<file path>\tAppend formula information to file.\n";
  cerr << "\t-ocnf\t<file path>\tWrite CNF to file.\n";
  cerr << "\t-oproof\t<file path>\tWrite proof formula to file.\n";
  cerr << endl;
  cerr << "Pipeline options:\n";
  cerr << "\t-f\tFlat ((p|(q|r)|s) ---> (p|q|r|s)). Before DAG.\n";
  cerr << "\t-m\tMinimize DAG edges ((p&q)|(p&r&q) ---> (p&q)|((p&q)&r)).\n";
  cerr << "\t-a\t<algorithm number>\tSelect renaming algorithm.\n";
  cerr << "\t-s\tSimplify CNF. (see note 1)\n";
  cerr << "\t-ionly\tOnly compute formula information.\n";
  cerr << endl;
  cerr << "Additional options:\n";
  cerr << "\t-h\tDisplay usage mode.\n";
  cerr << "\t-syntax\tDisplay formula syntax.\n";
  cerr << endl;
  cerr << "Renaming algorithms (see note 2):\n";
  cerr << "\t1\tKnapsack 0-1 based algorithm.\n";
  cerr << "\t2\tBoy de la Tour's algorithm.\n";
  cerr << endl;
  cerr << "Notes:\n";
  cerr << "\t1) CNF simplification removes tautologies, repeated literals\n";
  cerr << "\tand repeated clauses.\n";
  cerr << "\t2) If option -a is not set or an invalid algorithm is passed,\n";
  cerr << "\tthen no renaming will happen at all.\n";
  cerr << "\t3) Formula information format:\n";
  cerr << "\t<file path>,<size>,<number of clauses>,<number of symbols>,\\n\n";
  cerr << endl;
  exit(-1);
}

void syntax() {
  cerr << exe << ": Formula syntax.\n";
  cerr << endl;
  cerr << "Propositional symbols are strings of one or more of the following\n";
  cerr << "ASCII characters:\n";
  cerr << "\t_\t(underscore)\n";
  cerr << "\t0 to 9\t(decimal digits)\n";
  cerr << "\ta to z\t(lowercase letters)\n";
  cerr << "\tA to Z\t(uppercase letters)\n";
  cerr << endl;
  cerr << "Logic connectives are the following strings of ASCII characters:\n";
  cerr << "\t~\t(tilde)\t\t\t\t\t\tNegation.\n";
  cerr << "\t&\t(ampersand)\t\t\t\t\tConjunction.\n";
  cerr << "\t|\t(pipe)\t\t\t\t\t\tDisjunction.\n";
  cerr << "\t=>\t(equals and greater than signs)\t\t\tImplication.\n";
  cerr << "\t<=>\t(less than, equals and greater than signs)\tEquivalence.\n";
  cerr << endl;
  cerr << "Notes:\n";
  cerr << "\t1) Only one line is read by the parser.\n";
  cerr << "\t2) Whitespaces and multiple parentheses are completely ignored.\n";
  cerr << "\tExample:\n";
  cerr << "\t\t(((p => q)))\tis the same as\t\tp=>q\n";
  cerr << endl;
  exit(-1);
}

class Args {
  private:
    int argc;
    char** argv;
    unordered_map<string,int> idx;
  public:
    void init(int argc, char** argv) {
      this->argc = argc;
      this->argv = argv;
      for (int i = argc-1; 1 <= i; i--) idx[argv[i]] = i;
    }
    bool find(const string& str) const {
      return idx.find(str) != idx.end();
    }
    template <typename T>
    T opt(const string& name) const {
      auto it = idx.find(name);
      if (it == idx.end()) usage();
      int i = it->second+1;
      if (argc <= i) usage();
      stringstream ss;
      ss << argv[i];
      T ret;
      ss >> ret;
      if (ss.fail()) usage();
      return ret;
    }
    void checkflag(const string& name) const {
      if (!find(name)) usage();
    }
    template <typename T>
    void checkopt(const string& name, bool required = false) const {
      if (find(name)) opt<T>(name);
      else if (required) usage();
    }
} args;

// files
unordered_map<string,fstream*> files;
ostream& get_output_stream(const string& name, bool append = false) {
  if (!args.find("-o"+name)) return cout;
  string fn = args.opt<string>("-o"+name);
  auto it = files.find(fn);
  if (it != files.end()) return (ostream&)*it->second;
  fstream::openmode md = fstream::out;
  if (append) md = md | fstream::app;
  fstream* file = new fstream(fn,md);
  if (!file->is_open()) {
    cerr << exe << ": ";
    cerr << "error opening `" << fn << "' for " << name << " output.\n";
    exit(-1);
  }
  files[fn] = file;
  return (ostream&)*file;
}
void close_files() {
  for (auto& kv : files) {
    kv.second->close();
    delete kv.second;
  }
}

int main(int argc, char** argv) {
  // init args
  exe = argv[0];
  args.init(argc,argv);

  // display help
  if (args.find("-h")) usage();
  if (args.find("-syntax")) syntax();

  // init input stream
  string in_fn = "stdin";
  if (args.find("-i")) {
    in_fn = args.opt<string>("-i");
    if (!freopen(in_fn.c_str(),"r",stdin)) {
      cerr << exe << ": `" << in_fn << "' not found.\n";
      return -1;
    }
    reverse(in_fn.begin(),in_fn.end());
    auto pos = in_fn.find("/");
    if (pos != string::npos) in_fn = in_fn.substr(0,pos);
    reverse(in_fn.begin(),in_fn.end());
  }

  // init output streams
  ostream& info_stream  = get_output_stream("info", true);
  ostream& cnf_stream   = get_output_stream("cnf");
  ostream& proof_stream = get_output_stream("proof");

  // additional argument checks
  args.checkopt<int>("-a");

  // input
  getline(cin,raw);
  parse();

  // info only
  if (args.find("-ionly")) {
    info_stream << in_fn << ",";
    info_stream << size(T) << ",";
    info_stream << clauses(T) << ",";
    info_stream << symbols(T) << ",\n";
    close_files();
    return 0;
  }

  // pipeline
  nnf();
  if (args.find("-f")) flat();
  dag();
  if (args.find("-m")) mindag();
  if (args.find("-a")) switch (args.opt<int>("-a")) {
    case 1: knapsack();     break;
    case 2: boydelatour();  break;
  }
  rename();
  if (args.find("-s")) simplecnf();
  else cnf();

  // output
  info_stream << in_fn << ",";
  info_stream << CNF.size() << ",";
  info_stream << CNF.clauses() << ",";
  info_stream << CNF.symbols() << ",\n";
  cnf_stream << CNF << endl;
  proof_stream << "(" << raw << ") <=> (" << CNF << ")\n";

  close_files();

  return 0;
}
<commit_msg>Update usage mode<commit_after>#include "libtg.hpp"

using namespace std;

// argv[0]
string exe;

void usage() {
  cerr << "Usage mode: " << exe << " [options...] \n";
  cerr << endl;
  cerr << "I/O options:\n";
  cerr << "\t-i\t<file path>\tRead formula from file.\n";
  cerr << "\t-oinfo\t<file path>\tAppend formula information to file.\n";
  cerr << "\t-ocnf\t<file path>\tWrite CNF to file.\n";
  cerr << "\t-oproof\t<file path>\tWrite proof formula to file.\n";
  cerr << endl;
  cerr << "Pipeline options:\n";
  cerr << "\t-f\tFlat ((p|(q|r)|s) ---> (p|q|r|s)). Before DAG.\n";
  cerr << "\t-m\tMinimize DAG edges ((p&q)|(p&r&q) ---> (p&q)|((p&q)&r)).\n";
  cerr << "\t-a\t<algorithm number>\tSelect renaming algorithm.\n";
  cerr << "\t-s\tSimplify CNF. (see note 1)\n";
  cerr << "\t-ionly\tOnly compute formula information.\n";
  cerr << endl;
  cerr << "Additional options:\n";
  cerr << "\t-h\tDisplay usage mode.\n";
  cerr << "\t-syntax\tDisplay formula syntax.\n";
  cerr << endl;
  cerr << "Renaming algorithms (see note 2):\n";
  cerr << "\t1\tKnapsack 0-1 based algorithm.\n";
  cerr << "\t2\tBoy de la Tour's algorithm.\n";
  cerr << endl;
  cerr << "Notes:\n";
  cerr << "\t1) CNF simplification removes tautologies, repeated literals\n";
  cerr << "\tand repeated clauses.\n";
  cerr << "\t2) If option -a is not set or an invalid algorithm is passed,\n";
  cerr << "\tthen no renaming will happen at all.\n";
  cerr << "\t3) Formula information format:\n";
  cerr << "\t<file path>,<size>,<number of clauses>,<number of symbols>,\n";
  cerr << endl;
  exit(-1);
}

void syntax() {
  cerr << exe << ": Formula syntax.\n";
  cerr << endl;
  cerr << "Propositional symbols are strings of one or more of the following\n";
  cerr << "ASCII characters:\n";
  cerr << "\t_\t(underscore)\n";
  cerr << "\t0 to 9\t(decimal digits)\n";
  cerr << "\ta to z\t(lowercase letters)\n";
  cerr << "\tA to Z\t(uppercase letters)\n";
  cerr << endl;
  cerr << "Logic connectives are the following strings of ASCII characters:\n";
  cerr << "\t~\t(tilde)\t\t\t\t\t\tNegation.\n";
  cerr << "\t&\t(ampersand)\t\t\t\t\tConjunction.\n";
  cerr << "\t|\t(pipe)\t\t\t\t\t\tDisjunction.\n";
  cerr << "\t=>\t(equals and greater than signs)\t\t\tImplication.\n";
  cerr << "\t<=>\t(less than, equals and greater than signs)\tEquivalence.\n";
  cerr << endl;
  cerr << "Notes:\n";
  cerr << "\t1) Only one line is read by the parser.\n";
  cerr << "\t2) Whitespaces and multiple parentheses are completely ignored.\n";
  cerr << "\tExample:\n";
  cerr << "\t\t(((p => q)))\tis the same as\t\tp=>q\n";
  cerr << endl;
  exit(-1);
}

class Args {
  private:
    int argc;
    char** argv;
    unordered_map<string,int> idx;
  public:
    void init(int argc, char** argv) {
      this->argc = argc;
      this->argv = argv;
      for (int i = argc-1; 1 <= i; i--) idx[argv[i]] = i;
    }
    bool find(const string& str) const {
      return idx.find(str) != idx.end();
    }
    template <typename T>
    T opt(const string& name) const {
      auto it = idx.find(name);
      if (it == idx.end()) usage();
      int i = it->second+1;
      if (argc <= i) usage();
      stringstream ss;
      ss << argv[i];
      T ret;
      ss >> ret;
      if (ss.fail()) usage();
      return ret;
    }
    void checkflag(const string& name) const {
      if (!find(name)) usage();
    }
    template <typename T>
    void checkopt(const string& name, bool required = false) const {
      if (find(name)) opt<T>(name);
      else if (required) usage();
    }
} args;

// files
unordered_map<string,fstream*> files;
ostream& get_output_stream(const string& name, bool append = false) {
  if (!args.find("-o"+name)) return cout;
  string fn = args.opt<string>("-o"+name);
  auto it = files.find(fn);
  if (it != files.end()) return (ostream&)*it->second;
  fstream::openmode md = fstream::out;
  if (append) md = md | fstream::app;
  fstream* file = new fstream(fn,md);
  if (!file->is_open()) {
    cerr << exe << ": ";
    cerr << "error opening `" << fn << "' for " << name << " output.\n";
    exit(-1);
  }
  files[fn] = file;
  return (ostream&)*file;
}
void close_files() {
  for (auto& kv : files) {
    kv.second->close();
    delete kv.second;
  }
}

int main(int argc, char** argv) {
  // init args
  exe = argv[0];
  args.init(argc,argv);

  // display help
  if (args.find("-h")) usage();
  if (args.find("-syntax")) syntax();

  // init input stream
  string in_fn = "stdin";
  if (args.find("-i")) {
    in_fn = args.opt<string>("-i");
    if (!freopen(in_fn.c_str(),"r",stdin)) {
      cerr << exe << ": `" << in_fn << "' not found.\n";
      return -1;
    }
    reverse(in_fn.begin(),in_fn.end());
    auto pos = in_fn.find("/");
    if (pos != string::npos) in_fn = in_fn.substr(0,pos);
    reverse(in_fn.begin(),in_fn.end());
  }

  // init output streams
  ostream& info_stream  = get_output_stream("info", true);
  ostream& cnf_stream   = get_output_stream("cnf");
  ostream& proof_stream = get_output_stream("proof");

  // additional argument checks
  args.checkopt<int>("-a");

  // input
  getline(cin,raw);
  parse();

  // info only
  if (args.find("-ionly")) {
    info_stream << in_fn << ",";
    info_stream << size(T) << ",";
    info_stream << clauses(T) << ",";
    info_stream << symbols(T) << ",\n";
    close_files();
    return 0;
  }

  // pipeline
  nnf();
  if (args.find("-f")) flat();
  dag();
  if (args.find("-m")) mindag();
  if (args.find("-a")) switch (args.opt<int>("-a")) {
    case 1: knapsack();     break;
    case 2: boydelatour();  break;
  }
  rename();
  if (args.find("-s")) simplecnf();
  else cnf();

  // output
  info_stream << in_fn << ",";
  info_stream << CNF.size() << ",";
  info_stream << CNF.clauses() << ",";
  info_stream << CNF.symbols() << ",\n";
  cnf_stream << CNF << endl;
  proof_stream << "(" << raw << ") <=> (" << CNF << ")\n";

  close_files();

  return 0;
}
<|endoftext|>


<commit_before>/*
*
*  Copyright 2016 Carmine Dodaro.
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*/
#include "EnumerationSolver.h"
#include "glucose-syrup/core/Dimacs.h"

int main(int argc, char** argv)
{
    EnumerationSolver s;
    gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
    if (in == NULL)
        printf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);

    parse_DIMACS(in, s);
    gzclose(in);
    s.enumerate();
}
<commit_msg>Removed main.<commit_after><|endoftext|>


<commit_before>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>
#include <limits>

#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <Path.h>
#include <String.h>

#include <fs_attr.h>

BString handleAttribute(BString name, const void *data)
{
	if (name == "META:url") {
		std::cout << " HREF=\"" << (const char*)data << "\"";
	} else if (name == "META:title") {
		return BString((const char *)data);
	}
	return NULL;
}

status_t doFile(BFile& file, int indent)
{
	size_t bufferSize = std::max(B_MIME_TYPE_LENGTH, B_ATTR_NAME_LENGTH);
	BNodeInfo nodeInfo(&file);
	char* buffer = new (std::nothrow) char[bufferSize];
	if (buffer == NULL)
		return B_NO_MEMORY;
	nodeInfo.GetType(buffer);

	if (BString(buffer) != "application/x-vnd.Be-bookmark") {
		delete[] buffer;
		return B_BAD_VALUE;
	}

	BString ind;
	ind.Append(' ', indent);
	std::cout << ind << "
<A";

	BString title;

	struct attr_info info;
	while (file.GetNextAttrName(buffer) == B_OK) {
		if (file.GetAttrInfo(buffer, &info) != B_OK)
			continue;

		uint8_t* data = new (std::nothrow) uint8_t[info.size];
		if (data == NULL)
			continue;

		if (file.ReadAttr(buffer, info.type, 0, data, info.size) ==
			info.size) {

			BString maybeTitle = handleAttribute(BString(buffer),
				data);

			if (maybeTitle != NULL)
				title = maybeTitle;
		}
		delete[] data;
	}
	delete[] buffer;
	if (title == NULL)
		title = "Unknown";

	std::cout << ">" << title << "" << std::endl;

	return B_OK;
}

status_t getLastChanged(BDirectory* dir, time_t* out)
{
	if (dir == NULL || out == NULL)
		return B_BAD_VALUE;

	time_t latest = std::numeric_limits<time_t>::min(), cTime;
	BEntry current;
	bool any = false;

	while (dir->GetNextEntry(&current) == B_OK) {
		if (current.GetCreationTime(&cTime) == B_OK && cTime > latest) {
			any = true;
			latest = cTime;
		}
	}

	if (any) {
		*out = latest;
		return B_OK;
	}
	return B_ERROR;
}

status_t doDirectory(BDirectory& dir, const char* name, int indent)
{
	BString ind;
	ind.Append(' ', indent);

	if (indent > 0) {
		std::cout << ind << "
<H3";
		time_t addDate;
		if (dir.GetCreationTime(&addDate) == B_OK) {
			std::cout << " ADD_DATE=\"" << addDate << "\" ";

			time_t lastModified = addDate;
			getLastChanged(&dir, &lastModified);

			std::cout << "LAST_MODIFIED=\"" << lastModified << "\"";
		}
		std::cout << ">" << name << "
" << std::endl << ind << "

"
			<< std::endl;
	}

	BEntry current;
	dir.Rewind();
	while (dir.GetNextEntry(&current) == B_OK) {
		if (current.IsDirectory()) {
			BDirectory subdir(&current);

			char buffer[B_FILE_NAME_LENGTH];
			if (current.GetName(buffer) == B_OK)
				doDirectory(subdir, buffer, indent + 4);
			else
				doDirectory(subdir, "Unknown", indent + 4);
		}
		else if (current.IsFile()) {
			BFile subfile(&current, B_READ_ONLY);
			doFile(subfile, indent + 4);
		}
	}

	if (indent > 0)
		std::cout << ind << "

" << std::endl;

	return B_OK;
}

status_t extract(const char* path)
{
	std::cout	<< "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << std::endl
				<< "" << std::endl
				<< "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;"
				<< " charset=UTF-8\">" << std::endl
				<< "<TITLE>Bookmarks</TITLE>" << std::endl
				<< "
Bookmarks
" << std::endl
				<< "

" << std::endl;

	BDirectory parent(path);
	if (parent.InitCheck() != B_OK)
		return B_ERROR;

	doDirectory(parent, NULL, 0);

	std::cout << "

" << std::endl;
}

int main(int argc, char* argv[])
{
	BPath dir;
	switch (argc) {
		case 1:
			if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
				BString dest(dir.Path());
				dest << "/WebPositive/Bookmarks/";
				extract(dest.String());
				break;
			}
			std::cerr << "Could not find settings directory." << std::endl;
			break;
		case 2:
			extract(argv[1]);
			break;
		default:
			std::cerr << "Too many arguments." << std::endl;
			return 1;
	}
	return 0;
}

<commit_msg>Revert changes regarding data buffers<commit_after>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>
#include <limits>

#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <Path.h>
#include <String.h>

#include <fs_attr.h>

BString handleAttribute(BString name, const void *data)
{
	if (name == "META:url") {
		std::cout << " HREF=\"" << (const char*)data << "\"";
	} else if (name == "META:title") {
		return BString((const char *)data);
	}
	return NULL;
}

status_t doFile(BFile& file, int indent)
{
	BNodeInfo nodeInfo(&file);

	char buffer[B_MIME_TYPE_LENGTH];
	nodeInfo.GetType(buffer);

	if (BString(buffer) != "application/x-vnd.Be-bookmark")
		return B_BAD_VALUE;

	BString ind;
	ind.Append(' ', indent);
	std::cout << ind << "
<A";

	BString title;

	struct attr_info info;
	char attrBuffer[B_ATTR_NAME_LENGTH];
	while (file.GetNextAttrName(attrBuffer) == B_OK) {
		if (file.GetAttrInfo(attrBuffer, &info) != B_OK)
			continue;

		uint8_t* data = new (std::nothrow) uint8_t[info.size];
		if (data == NULL)
			continue;

		if (file.ReadAttr(attrBuffer, info.type, 0, data, info.size) ==
			info.size) {

			BString maybeTitle = handleAttribute(BString(attrBuffer),
				data);

			if (maybeTitle != NULL)
				title = maybeTitle;
		}
		delete[] data;
	}
	if (title == NULL)
		title = "Unknown";

	std::cout << ">" << title << "" << std::endl;

	return B_OK;
}

status_t getLastChanged(BDirectory* dir, time_t* out)
{
	if (dir == NULL || out == NULL)
		return B_BAD_VALUE;

	time_t latest = std::numeric_limits<time_t>::min(), cTime;
	BEntry current;
	bool any = false;

	while (dir->GetNextEntry(&current) == B_OK) {
		if (current.GetCreationTime(&cTime) == B_OK && cTime > latest) {
			any = true;
			latest = cTime;
		}
	}

	if (any) {
		*out = latest;
		return B_OK;
	}
	return B_ERROR;
}

status_t doDirectory(BDirectory& dir, const char* name, int indent)
{
	BString ind;
	ind.Append(' ', indent);

	if (indent > 0) {
		std::cout << ind << "
<H3";
		time_t addDate;
		if (dir.GetCreationTime(&addDate) == B_OK) {
			std::cout << " ADD_DATE=\"" << addDate << "\" ";

			time_t lastModified = addDate;
			getLastChanged(&dir, &lastModified);

			std::cout << "LAST_MODIFIED=\"" << lastModified << "\"";
		}
		std::cout << ">" << name << "
" << std::endl << ind << "

"
			<< std::endl;
	}

	BEntry current;
	dir.Rewind();
	while (dir.GetNextEntry(&current) == B_OK) {
		if (current.IsDirectory()) {
			BDirectory subdir(&current);

			char buffer[B_FILE_NAME_LENGTH];
			if (current.GetName(buffer) == B_OK)
				doDirectory(subdir, buffer, indent + 4);
			else
				doDirectory(subdir, "Unknown", indent + 4);
		}
		else if (current.IsFile()) {
			BFile subfile(&current, B_READ_ONLY);
			doFile(subfile, indent + 4);
		}
	}

	if (indent > 0)
		std::cout << ind << "

" << std::endl;

	return B_OK;
}

status_t extract(const char* path)
{
	std::cout	<< "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << std::endl
				<< "" << std::endl
				<< "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;"
				<< " charset=UTF-8\">" << std::endl
				<< "<TITLE>Bookmarks</TITLE>" << std::endl
				<< "
Bookmarks
" << std::endl
				<< "

" << std::endl;

	BDirectory parent(path);
	if (parent.InitCheck() != B_OK)
		return B_ERROR;

	doDirectory(parent, NULL, 0);

	std::cout << "

" << std::endl;
}

int main(int argc, char* argv[])
{
	BPath dir;
	switch (argc) {
		case 1:
			if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
				BString dest(dir.Path());
				dest << "/WebPositive/Bookmarks/";
				extract(dest.String());
				break;
			}
			std::cerr << "Could not find settings directory." << std::endl;
			break;
		case 2:
			extract(argv[1]);
			break;
		default:
			std::cerr << "Too many arguments." << std::endl;
			return 1;
	}
	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <time.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../sdk/stb/stb_image_write.h"

#include "renderer.h"

// おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。
// 4分33秒以内に自動で終了してください。

#define WIDTH 256
#define HEIGHT 256

#define OUTPUT_INTERVAL 30
#define FINISH_TIME (4 * 60 + 33)
#define FINISH_MARGIN 2

void save(const double *data, unsigned char *buf, const char *filename, int steps)
{
	const double coeff = 1.0 / (10.1 * (double)steps);
	#pragma omp parallel for
	for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
		double tmp = 1.0 - exp(-data[i] * coeff);// tone mapping
		buf[i] = (unsigned char)(pow(tmp, 1.0/2.2) * 255.999);// gamma correct
	}

	// save
	int w = WIDTH;
	int h = HEIGHT;
	int comp = 3; // RGB
	int stride_in_bytes = 3 * w;
	int result = stbi_write_png(filename, w, h, comp, buf, stride_in_bytes);
}

int main()
{
	time_t t0 = time(NULL);
	time_t t_last = 0;
	int count = 0;

	unsigned char *image = new unsigned char[3 * WIDTH * HEIGHT];

	// frame buffer の初期化
	int current = 0;
	double *fb[2];
	fb[0] = new double[3 * WIDTH * HEIGHT];
	fb[1] = new double[3 * WIDTH * HEIGHT];
	double *fb0 = fb[0], *fb1 = fb[1];
	#pragma omp parallel for
	for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
		fb0[i] = fb1[i] = 0;
	}

	renderer *pRenderer = new renderer(WIDTH, HEIGHT);

	do
	{
		// fb[1-current] を読み込んで fb[current]にレンダリング
		std::this_thread::sleep_for(std::chrono::seconds(1));
		int steps = pRenderer->update(fb[1 - current], fb[current]);

		// swap
		current = 1 - current;

		// 30 秒ごとに出力
		time_t t = time(NULL) - t0;
		int c = (int)(t / OUTPUT_INTERVAL);
		if (count < c) {
			char filename[256];
			snprintf(filename, 256, "%d.png", c);
			save(fb[1 - current], image, filename, steps);
			count++;
		}

		// 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する
		if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break;

		t_last = t;
	}while (true);

	delete pRenderer;
	delete[] image;
	delete[] fb[0];
	delete[] fb[1];

	return 0;
}

<commit_msg>full hd<commit_after>#include <iostream>
#include <thread>
#include <time.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../sdk/stb/stb_image_write.h"

#include "renderer.h"

// おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。
// 4分33秒以内に自動で終了してください。

#define WIDTH 1980
#define HEIGHT 1080

#define OUTPUT_INTERVAL 30
#define FINISH_TIME (4 * 60 + 33)
#define FINISH_MARGIN 2

void save(const double *data, unsigned char *buf, const char *filename, int steps)
{
	const double coeff = 1.0 / (10.1 * (double)steps);
	#pragma omp parallel for
	for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
		double tmp = 1.0 - exp(-data[i] * coeff);// tone mapping
		buf[i] = (unsigned char)(pow(tmp, 1.0/2.2) * 255.999);// gamma correct
	}

	// save
	int w = WIDTH;
	int h = HEIGHT;
	int comp = 3; // RGB
	int stride_in_bytes = 3 * w;
	int result = stbi_write_png(filename, w, h, comp, buf, stride_in_bytes);
}

int main()
{
	time_t t0 = time(NULL);
	time_t t_last = 0;
	int count = 0;

	unsigned char *image = new unsigned char[3 * WIDTH * HEIGHT];

	// frame buffer の初期化
	int current = 0;
	double *fb[2];
	fb[0] = new double[3 * WIDTH * HEIGHT];
	fb[1] = new double[3 * WIDTH * HEIGHT];
	double *fb0 = fb[0], *fb1 = fb[1];
	#pragma omp parallel for
	for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
		fb0[i] = fb1[i] = 0;
	}

	renderer *pRenderer = new renderer(WIDTH, HEIGHT);

	do
	{
		// fb[1-current] を読み込んで fb[current]にレンダリング
		std::this_thread::sleep_for(std::chrono::seconds(1));
		int steps = pRenderer->update(fb[1 - current], fb[current]);

		// swap
		current = 1 - current;

		// 30 秒ごとに出力
		time_t t = time(NULL) - t0;
		int c = (int)(t / OUTPUT_INTERVAL);
		if (count < c) {
			char filename[256];
			snprintf(filename, 256, "%d.png", c);
			save(fb[1 - current], image, filename, steps);
			count++;
		}

		// 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する
		if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break;

		t_last = t;
	}while (true);

	delete pRenderer;
	delete[] image;
	delete[] fb[0];
	delete[] fb[1];

	return 0;
}

<|endoftext|>


<commit_before>/**
 *  main.cpp
 *  This file is part of MultitouchPadOsc
 *
 *
 *  The MIT License
 *  Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
 *  All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 *  and  associated documentation files  (the "Software"),  to deal in the Software without
 *  restriction, including without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 *  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 *  @plattform        MacOs 10.6+
 *                    Win XXX
 *                    Linux XXX
 *  @openFrameworks   0071
 *  @dependencies
 *  @modified         2012.07.15
 *  @version          0.1.2
 */

#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"

int main() {
    ofAppGlutWindow window;
	ofSetupOpenGL(&window, 500, 400, OF_WINDOW); // setup the GL context

	if (NSApp){
        NSMenu      *menu;
        NSMenuItem  *menuItem;

        [NSApp setMainMenu:[[NSMenu alloc] init]];

		// Appname menu
		menu = [[NSMenu alloc] initWithTitle:@""];
		[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];

		[menu addItem:[NSMenuItem separatorItem]];

		[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];

		menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
		[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];

		[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];

		[menu addItem:[NSMenuItem separatorItem]];

		[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];

		// Put menu into the menubar
		menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
		[menuItem setSubmenu:menu];
		[[NSApp mainMenu] addItem:menuItem];
		// Tell the application object that this is now the application menu
		//[NSApp setMainMenu:menu];

    }

	// this kicks off the running of my app can be
	// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
	ofRunApp(new MultitouchPadOscApp());
}
<commit_msg>clean up code<commit_after>/**
 *  main.cpp
 *  This file is part of MultitouchPadOsc
 *
 *
 *  The MIT License
 *  Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
 *  All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 *  and  associated documentation files  (the "Software"),  to deal in the Software without
 *  restriction, including without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 *  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 *  @plattform        MacOs 10.6+
 *                    Win XXX
 *                    Linux XXX
 *  @openFrameworks   0071
 *  @dependencies
 *  @modified         2012.07.15
 *  @version          0.1.2
 */

#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"

int main() {
    ofAppGlutWindow window;
	ofSetupOpenGL(&window, 500, 400, OF_WINDOW); // setup the GL context

	if (NSApp){
        NSMenu      *menu;
        NSMenuItem  *menuItem;
        [NSApp setMainMenu:[[NSMenu alloc] init]];
		// Appname menu
		menu = [[NSMenu alloc] initWithTitle:@""];
		[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
		[menu addItem:[NSMenuItem separatorItem]];
		[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];
		menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
		[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
		[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
		[menu addItem:[NSMenuItem separatorItem]];
		[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];
		// Put menu into the menubar
		menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
		[menuItem setSubmenu:menu];
		[[NSApp mainMenu] addItem:menuItem];
    }

	// this kicks off the running of my app can be
	// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
	ofRunApp(new MultitouchPadOscApp());
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"

const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_WINDOWEVENT:
            if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
                screen_width  = event->window.data1;
                screen_height = event->window.data2;
            }
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                case SDLK_UP:
                    view_direction.theta -= 0.01f;
                    break;
                case SDLK_DOWN:
                    view_direction.theta += 0.01f;
                    break;
                case SDLK_LEFT:
                    view_direction.phi -= 0.01f;
                    break;
                case SDLK_RIGHT:
                    view_direction.phi += 0.01f;
                    break;
                default:
                    break;
            }
        case SDL_MOUSEMOTION:
            if ( button_set ) {
                delta.phi = -( event->button.x - px ) / 100.0f;
                delta.theta = ( event->button.y - py ) / 100.0f;
                px = event->button.x;
                py = event->button.y;
                view_direction += delta;
            }
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    if ( button_set == false ) {
                        px = event->button.x;
                        py = event->button.y;
                    }
                    break;
                default:
                    break;
            }
            button_set = true;
            break;
        case SDL_MOUSEBUTTONUP:
            button_set = false;
            break;
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void game_render( void ) {
    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
}

int main( int argc, char * argv[] ) {
    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<commit_msg>[add] get_fps(), font; [upd] scroll<commit_after>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"
#include "font.hpp"

const char * game_name = "Game Of Life On Surface";
const wchar_t tmp_str[] = L"FPS: %.2f";
int screen_width = 640;
int screen_height = 640;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;
font_table_t * ft = NULL;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

float get_fps( void ) {
    static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f;
    static int FrameCount = 0;

    NewCount = (float) SDL_GetTicks();
    if ( ( NewCount - LastCount ) > 1000.0f ) {
        FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount );
        LastCount = NewCount;
        FrameCount = 0;
    }
    FrameCount++;
    return FpsRate;
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_WINDOWEVENT:
            if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
                screen_width  = event->window.data1;
                screen_height = event->window.data2;
            }
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                case SDLK_UP:
                    view_direction.theta -= 0.01f;
                    break;
                case SDLK_DOWN:
                    view_direction.theta += 0.01f;
                    break;
                case SDLK_LEFT:
                    view_direction.phi -= 0.01f;
                    break;
                case SDLK_RIGHT:
                    view_direction.phi += 0.01f;
                    break;
                default:
                    break;
            }
        case SDL_MOUSEMOTION:
            if ( button_set ) {
                delta.phi = ( event->button.x - px ) / 100.0f;
                delta.theta = ( event->button.y - py ) / 100.0f;
                px = event->button.x;
                py = event->button.y;
                view_direction -= delta;
            }
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    if ( button_set == false ) {
                        px = event->button.x;
                        py = event->button.y;
                    }
                    break;
                default:
                    break;
            }
            button_set = true;
            break;
        case SDL_MOUSEBUTTONUP:
            button_set = false;
            break;
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void game_render( void ) {
    const size_t BUFFER_SIZE = 128;
    wchar_t buffer[BUFFER_SIZE];

    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
    swprintf( buffer, BUFFER_SIZE, tmp_str, get_fps() );
    font_draw( render, ft, buffer, 5, screen_height - 16 );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    font_destroy( ft );
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
    font_load( render, &ft, "./data/font.cfg" );
}

int main( int argc, char * argv[] ) {
    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include "ftdi.hpp"
#include "dionysus.hpp"

#define PROGRAM_NAME "dionysus-ftdi"

using namespace Ftdi;

#define DEFAULT_ARGUMENTS     \
{                             \
  .vendor = DIONYSUS_VID,     \
  .product = DIONYSUS_PID,    \
  .debug = false              \
}

struct arguments {
  int vendor;
  int product;
  bool debug;
};

static double TimevalDiff(const struct timeval *a, const struct timeval *b)
{
    return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
}

static void usage (int exit_status){
  fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr,
      "\n"
      "USAGE: %s [-v <vendor>] [-p <product>] [-d]\n"
      "\n"
      "Options:\n"
      " -h, --help\n"
      "\tPrints this helpful message\n"
      " -d, --debug\n"
      "\tEnable Debug output\n"
      " -v, --vendor\n"
      "\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n"
      " -p, --product\n"
      "\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n"
      ,
      PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID);
  exit(exit_status);
}

static void parse_args(struct arguments* args, int argc, char *const argv[]){
  int print_usage = 0;
  const char shortopts[] = "hdv:p:";
  struct option longopts[5];
  longopts[0].name = "help";
  longopts[0].has_arg = no_argument;
  longopts[0].flag = NULL;
  longopts[0].val = 'h';

  longopts[1].name = "debug";
  longopts[1].has_arg = no_argument;
  longopts[1].flag = NULL;
  longopts[1].val = 'd';

  longopts[2].name = "vendor";
  longopts[2].has_arg = required_argument;
  longopts[2].flag = NULL;
  longopts[2].val = 'v';

  longopts[3].name = "help";
  longopts[3].has_arg = required_argument;
  longopts[3].flag = NULL;
  longopts[3].val = 'p';

  longopts[4].name = 0;
  longopts[4].has_arg = 0;
  longopts[4].flag = 0;
  longopts[4].val = 0;
  while (1) {
    int option_idx = 0;
    int c = getopt_long(argc, argv, shortopts, longopts, &option_idx);
    if (c == -1){
      break;
    }
    switch (c){
      case 0:
          /* no arguments */
        if (print_usage){
          usage(EXIT_SUCCESS);
        }
        break;
      case 'h':
        usage(EXIT_SUCCESS);
        break;
      case 'd':
        printf ("debug enabled\n");
        args->debug = true;
        break;
      case 'v':
        args->vendor = strtol(optarg, (char**)0, 16);
        break;
      case 'p':
        args->product = strtol(optarg, (char**)0, 16);
        break;
      case '?': /* Fall through */
      default:
        printf ("Unknown Command\n");
        usage (EXIT_FAILURE);
        break;
    }
  }
}

int main(int argc, char **argv){
  struct arguments args;
  args.vendor = DIONYSUS_VID;
  args.product = DIONYSUS_PID;
  args.debug = false;
  uint8_t* buffer = new uint8_t [8196];

  uint32_t num_devices;
  uint32_t device_type = 0;
  uint32_t device_addres = 0;
  uint32_t device_size = 0;
  bool memory_device = false;
  bool fail = false;
  uint32_t fail_count = 0;
  struct timeval start;
  struct timeval end;
  double interval = 1.0;
  double mem_size;
  double rate = 0;
  uint32_t memory_device_index = 0;

  parse_args(&args, argc, argv);

  //Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug);
  Dionysus dionysus = Dionysus(args.debug);

  dionysus.open(args.vendor, args.product);
  if (dionysus.is_open()){
    dionysus.reset();
    //dionysus.program_fpga();
    //dionysus.soft_reset();
    gettimeofday(&start, NULL);
    dionysus.ping();
    gettimeofday(&end, NULL);
    interval = TimevalDiff(&end, &start);
    rate = 9 / interval;  //Megabytes/Sec
    printf ("Time difference: %f\n", interval);
    printf ("Ping Rate: %.2f Bytes/Sec\n", rate);

    printf ("Reading from the DRT\n");
    //dionysus.read_periph_data(0, 0, buffer, 32);
    dionysus.read_drt();
    for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
      printf ("Device %d:\n", i);
      printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i));
      printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i));
      printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i));
      if (dionysus.is_memory_device(i)){
        printf ("\t\tOn the memory bus\n");
      }
    }
    //Buffer Data:
    //for (int i = 0; i < 32; i++){
    //  printf ("%02X ", buffer[i]);
    //}
    printf ("\n");
    //dionysus.read_periph_data(0, 0, buffer, 4096);
    printf ("Peripheral Write Test. read a lot of data from the DRT\n");
    printf ("\t(DRT will just ignore this data)\n");
    dionysus.write_periph_data(0, 0, buffer, 8192);

    printf ("Peripheral Read Test. Read a lot of data from the DRT\n");
    printf ("\t(Data from the DRT will just loop)\n");
    dionysus.read_periph_data(0, 0, buffer, 8192);
    delete(buffer);

    printf ("Look for a memory device\n");

    for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
      if (dionysus.get_drt_device_type(i) == 5){
        memory_device_index = i;
      }
    }
    if (memory_device_index > 0){
      printf ("Found a memory device at position: %d\n", memory_device_index);

      printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index));

      buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)];
      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        buffer[i] = i;
      }
      printf ("Testing Full Memory Write Time...\n");
      gettimeofday(&start, NULL);
      dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
      gettimeofday(&end, NULL);
      interval = TimevalDiff(&end, &start);
      mem_size = dionysus.get_drt_device_size(memory_device_index);
      rate = mem_size/ interval / 1e6;  //Megabytes/Sec
      printf ("Time difference: %f\n", interval);
      printf ("Write Rate: %.2f MB/Sec\n", rate);

      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        buffer[i] = 0;
      }
      gettimeofday(&start, NULL);
      dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
      gettimeofday(&end, NULL);
      interval = TimevalDiff(&end, &start);
      mem_size = dionysus.get_drt_device_size(memory_device_index);
      rate = mem_size/ interval / 1e6;  //Megabytes/Sec
      printf ("Time difference: %f\n", interval);
      printf ("Read Rate: %.2f MB/Sec\n", rate);

      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        if (buffer[i] != i % 256){
          if (!fail){
            if (fail_count > 16){
              fail = true;
            }
            fail_count += 1;
            printf ("Failed @ 0x%08X\n", i);
            printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]);
          }
        }
      }
      if (!fail){
        printf ("Memory Test Passed!\n");
      }

      delete (buffer);
    }

    dionysus.close();
  }
  return 0;
}

<commit_msg>Added support for testing the GPIO driver<commit_after>#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include "ftdi.hpp"
#include "dionysus.hpp"
#include "gpio.hpp"
#include "arduino.hpp"

#define PROGRAM_NAME "dionysus-ftdi"

#define MEMORY_TEST false
//5 seconds
#define GPIO_TEST_WAIT 10

using namespace Ftdi;

#define DEFAULT_ARGUMENTS     \
{                             \
  .vendor = DIONYSUS_VID,     \
  .product = DIONYSUS_PID,    \
  .debug = false              \
}

struct arguments {
  int vendor;
  int product;
  bool debug;
};

static double TimevalDiff(const struct timeval *a, const struct timeval *b)
{
    return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
}

static void usage (int exit_status){
  fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr,
      "\n"
      "USAGE: %s [-v <vendor>] [-p <product>] [-d]\n"
      "\n"
      "Options:\n"
      " -h, --help\n"
      "\tPrints this helpful message\n"
      " -d, --debug\n"
      "\tEnable Debug output\n"
      " -v, --vendor\n"
      "\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n"
      " -p, --product\n"
      "\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n"
      ,
      PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID);
  exit(exit_status);
}

static void parse_args(struct arguments* args, int argc, char *const argv[]){
  int print_usage = 0;
  const char shortopts[] = "hdv:p:";
  struct option longopts[5];
  longopts[0].name = "help";
  longopts[0].has_arg = no_argument;
  longopts[0].flag = NULL;
  longopts[0].val = 'h';

  longopts[1].name = "debug";
  longopts[1].has_arg = no_argument;
  longopts[1].flag = NULL;
  longopts[1].val = 'd';

  longopts[2].name = "vendor";
  longopts[2].has_arg = required_argument;
  longopts[2].flag = NULL;
  longopts[2].val = 'v';

  longopts[3].name = "help";
  longopts[3].has_arg = required_argument;
  longopts[3].flag = NULL;
  longopts[3].val = 'p';

  longopts[4].name = 0;
  longopts[4].has_arg = 0;
  longopts[4].flag = 0;
  longopts[4].val = 0;
  while (1) {
    int option_idx = 0;
    int c = getopt_long(argc, argv, shortopts, longopts, &option_idx);
    if (c == -1){
      break;
    }
    switch (c){
      case 0:
          /* no arguments */
        if (print_usage){
          usage(EXIT_SUCCESS);
        }
        break;
      case 'h':
        usage(EXIT_SUCCESS);
        break;
      case 'd':
        printf ("debug enabled\n");
        args->debug = true;
        break;
      case 'v':
        args->vendor = strtol(optarg, (char**)0, 16);
        break;
      case 'p':
        args->product = strtol(optarg, (char**)0, 16);
        break;
      case '?': /* Fall through */
      default:
        printf ("Unknown Command\n");
        usage (EXIT_FAILURE);
        break;
    }
  }
}

void breath(GPIO *g, uint32_t timeout){
  struct timeval test_start;
  struct timeval test_now;
  double interval = 1.0;
  gettimeofday(&test_start, NULL);
  gettimeofday(&test_now, NULL);
  uint32_t period;
  uint32_t max_val = 10;
  uint32_t current = 0;
  uint32_t position = 0;
  uint32_t delay_count = 0;
  uint32_t delay = 0;
  uint8_t direction = 1;
  printf ("Breath\n");

  printf ("Max value: %d\n", max_val);

  while (interval < GPIO_TEST_WAIT){
    if (direction){
      if (current < max_val){
        if (position < max_val) {
          //printf ("pos++\n");
          position++;
        }
        else {
          //printf ("position = 0\n");
          position = 0;
          if (delay_count < delay){
            delay_count++;
          }
          else {
            //printf ("increment count\n");
            delay_count = 0;
            current++;
          }
        }
      }
      else {
        //printf ("go down\n");
        direction = 0;
      }
    }
    else {
      if (current > 0){
        if (position < max_val){
          position++;
        }
        else {
          position = 0;
          if (delay_count < delay){
            delay_count++;
          }
          else {
            delay_count = 0;
            current--;
          }
        }
      }
      else {
        //printf ("go up\n");
        direction = 1;
      }
    }

    if (position < current){
      //printf ("HI\n");
      //g->digitalWrite(0, LOW);
      g->set_gpios(0x00000002);
    }
    else {
      //printf ("LOW\n");
      g->set_gpios(0x00000001);
      //g->digitalWrite(0, HIGH);
    }
    gettimeofday(&test_now, NULL);
    interval = TimevalDiff(&test_now, &test_start);
  }
};

void test_gpios(Nysa *nysa, uint32_t dev_index, bool debug){
  if (dev_index == 0){
    printf ("Device index == 0!, this is the DRT!");
  }
  struct timeval test_start;
  struct timeval test_now;
  double interval = 1.0;

  double led_interval = 1.0;
  printf ("Setting up new gpio device\n");
  //Setup GPIO
  GPIO *gpio = new GPIO(nysa, dev_index, debug);
  printf ("Got new GPIO Device\n");
  try {
    gpio->pinMode(0, OUTPUT); //LED 0
    gpio->pinMode(1, OUTPUT); //LED 1

    gpio->pinMode(2, INPUT); //Button 0
    gpio->pinMode(3, INPUT); //Button 1
  }
  catch (int e) {
    printf ("Error while setting pinMode: Error: %d\n", e);
  }
  printf ("set pin modes!\n");

  //Length of GPIO tests
  gettimeofday(&test_start, NULL);
  gettimeofday(&test_now, NULL);

  //Pulse width of the LED

  interval = TimevalDiff(&test_now, &test_start);
  printf ("Interval: %f\n", interval);
  breath(gpio, GPIO_TEST_WAIT);

  /*
  while (interval < GPIO_TEST_WAIT){

    gpio->toggle(0);
    usleep(1000000);

    gettimeofday(&test_now, NULL);
    interval = TimevalDiff(&test_now, &test_start);
  //printf ("Interval: %f\n", interval);
  }
  */
  //Loop for about two seconds
  printf ("Set 0 to high\n");
  gpio->digitalWrite(0, LOW);
  gpio->digitalWrite(1, LOW);
}

int main(int argc, char **argv){
  struct arguments args;
  args.vendor = DIONYSUS_VID;
  args.product = DIONYSUS_PID;
  args.debug = false;
  uint8_t* buffer = new uint8_t [8196];

  uint32_t num_devices;
  uint32_t device_type = 0;
  uint32_t device_addres = 0;
  uint32_t device_size = 0;
  bool memory_device = false;
  bool fail = false;
  uint32_t fail_count = 0;
  struct timeval start;
  struct timeval end;
  double interval = 1.0;
  double mem_size;
  double rate = 0;
  uint32_t memory_device_index = 0;

  parse_args(&args, argc, argv);

  //Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug);
  Dionysus dionysus = Dionysus(args.debug);

  dionysus.open(args.vendor, args.product);
  if (dionysus.is_open()){
    dionysus.reset();
    //dionysus.program_fpga();
    //dionysus.soft_reset();
    gettimeofday(&start, NULL);
    dionysus.ping();
    gettimeofday(&end, NULL);
    interval = TimevalDiff(&end, &start);
    rate = 9 / interval;  //Megabytes/Sec
    printf ("Time difference: %f\n", interval);
    printf ("Ping Rate: %.2f Bytes/Sec\n", rate);

    printf ("Reading from the DRT\n");
    //dionysus.read_periph_data(0, 0, buffer, 32);
    dionysus.read_drt();
    for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
      printf ("Device %d:\n", i);
      printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i));
      printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i));
      printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i));
      if (dionysus.is_memory_device(i)){
        printf ("\t\tOn the memory bus\n");
      }
    }
    //Buffer Data:
    //for (int i = 0; i < 32; i++){
    //  printf ("%02X ", buffer[i]);
    //}
    printf ("\n");
    //dionysus.read_periph_data(0, 0, buffer, 4096);
    printf ("Peripheral Write Test. read a lot of data from the DRT\n");
    printf ("\t(DRT will just ignore this data)\n");
    dionysus.write_periph_data(0, 0, buffer, 8192);

    printf ("Peripheral Read Test. Read a lot of data from the DRT\n");
    printf ("\t(Data from the DRT will just loop)\n");
    dionysus.read_periph_data(0, 0, buffer, 8192);
    delete(buffer);

    printf ("Look for a memory device\n");

    if (MEMORY_TEST){
      for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
        if (dionysus.get_drt_device_type(i) == 5){
          memory_device_index = i;
        }
      }
    }

    if (memory_device_index > 0){
      printf ("Found a memory device at position: %d\n", memory_device_index);

      printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index));

      buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)];
      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        buffer[i] = i;
      }
      printf ("Testing Full Memory Write Time...\n");
      gettimeofday(&start, NULL);
      dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
      gettimeofday(&end, NULL);
      interval = TimevalDiff(&end, &start);
      mem_size = dionysus.get_drt_device_size(memory_device_index);
      rate = mem_size/ interval / 1e6;  //Megabytes/Sec
      printf ("Time difference: %f\n", interval);
      printf ("Write Rate: %.2f MB/Sec\n", rate);

      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        buffer[i] = 0;
      }
      gettimeofday(&start, NULL);
      dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
      gettimeofday(&end, NULL);
      interval = TimevalDiff(&end, &start);
      mem_size = dionysus.get_drt_device_size(memory_device_index);
      rate = mem_size/ interval / 1e6;  //Megabytes/Sec
      printf ("Time difference: %f\n", interval);
      printf ("Read Rate: %.2f MB/Sec\n", rate);

      for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
        if (buffer[i] != i % 256){
          if (!fail){
            if (fail_count > 16){
              fail = true;
            }
            fail_count += 1;
            printf ("Failed @ 0x%08X\n", i);
            printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]);
          }
        }
      }
      if (!fail){
        printf ("Memory Test Passed!\n");
      }

      delete (buffer);
    }
    uint32_t gpio_device = 0;
    for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
      if (dionysus.get_drt_device_type(i) == get_gpio_device_type()){
        gpio_device = i;
      }
    }
    if (gpio_device > 0){
      test_gpios(&dionysus, gpio_device, args.debug);
    }

    dionysus.close();
  }
  return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "DFA.h"
using namespace std;
int main()
{
	DFA DFA_each;
	DFA_each.InputRegex();//
	DFA_each.InsertNode();//
	DFA_each.RegextoPost();//תΪ׺ʽ
	DFA_each.GetEdgeNumber();//ɨ沨ʽгַĿ
	DFA_each.Thompson();//Thompson취NFA
	DFA_each.NFAtoDFA();//Ӽ취 NFADFA
	DFA_each.Hopcroft();//СDFA㷨
	DFA_each.InputString();//Ҫƥַ
	DFA_each.Match();//ƥ
	system("pause");
	return 0;
}
<commit_msg>update<commit_after>#include <iostream>
#include "DFA.h"
using namespace std;
int main()
{
	  DFA DFA_each;
	  DFA_each.InputRegex();//
	  DFA_each.InsertNode();//
	  DFA_each.RegextoPost();//תΪ׺ʽ
	  DFA_each.GetEdgeNumber();//ɨ沨ʽгַĿ
	  DFA_each.Thompson();//Thompson취NFA
	  DFA_each.NFAtoDFA();//Ӽ취 NFADFA
	  DFA_each.Hopcroft();//СDFA㷨
	  DFA_each.InputString();//Ҫƥַ
	  DFA_each.Match();//ƥ
    cout<<"quit!        "<<endl;
	return 0;
}
<|endoftext|>