text stringlengths 54 60.6k |
|---|
<commit_before>8284049c-ad58-11e7-b13d-ac87a332f658<commit_msg>having coffee<commit_after>83200607-ad58-11e7-be23-ac87a332f658<|endoftext|> |
<commit_before>f45be8e1-327f-11e5-8a39-9cf387a8033e<commit_msg>f461dc5c-327f-11e5-8fca-9cf387a8033e<commit_after>f461dc5c-327f-11e5-8fca-9cf387a8033e<|endoftext|> |
<commit_before>fe874e5e-2e4e-11e5-b57b-28cfe91dbc4b<commit_msg>fe95954a-2e4e-11e5-9480-28cfe91dbc4b<commit_after>fe95954a-2e4e-11e5-9480-28cfe91dbc4b<|endoftext|> |
<commit_before>ea67122e-313a-11e5-b570-3c15c2e10482<commit_msg>ea6cfdf8-313a-11e5-aff5-3c15c2e10482<commit_after>ea6cfdf8-313a-11e5-aff5-3c15c2e10482<|endoftext|> |
<commit_before>8431fbf9-2d15-11e5-af21-0401358ea401<commit_msg>8431fbfa-2d15-11e5-af21-0401358ea401<commit_after>8431fbfa-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>ebab47e8-2e4e-11e5-88d4-28cfe91dbc4b<commit_msg>ebb84935-2e4e-11e5-aaa5-28cfe91dbc4b<commit_after>ebb84935-2e4e-11e5-aaa5-28cfe91dbc4b<|endoftext|> |
<commit_before>e5a8fc05-327f-11e5-bdfb-9cf387a8033e<commit_msg>e5af0fae-327f-11e5-946a-9cf387a8033e<commit_after>e5af0fae-327f-11e5-946a-9cf387a8033e<|endoftext|> |
<commit_before>/* File: main.cpp
* Contains base main function and usually all the other stuff that avr does...
*/
/* Copyright (c) 2012-2013 Domen Ipavec (domen.ipavec@z-v.si)
*
* 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.
*/
#define F_CPU 8000000UL // 8 MHz
//#include <util/delay.h>
#define UINT16_MAX 65535
#include <avr/io.h>
#include <avr/interrupt.h>
//#include <avr/pgmspace.h>
//#include <avr/eeprom.h>
#include <stdint.h>
#include "bitop.h"
//#include "shiftOut.h"
#include "io.h"
volatile uint8_t flags = 0;
#define MS_FLAG 0
#define VOLTAGE_WARNING 1
#define VOLTAGE_CUTOFF 2
volatile uint8_t ir_count = 0;
int main() {
// INIT
// soft power button
SETBIT(DDRA, PA3);
SETBIT(PORTA, PA3);
SETBIT(PORTA, PA1);
// timer 1 for 1 ms interrupts and pwm for one led
TCCR1A = 0b01000000;
TCCR1B = 0b00001001; // CTC mode
OCR1A = 105; // clear
TIMSK1 = 0b00000010; // ocie1a interrupt
// pwm for leds
// 0
//SETBIT(DDRA, PA7);
// 1
//SETBIT(DDRB, PB2);
// 2
//SETBIT(DDRA, PA6);
TCCR0A = 0b01010010;
TCCR0B = 0b00000001;
OCR0A = 105;
OCR0B = 105;
// adc measurement
ADMUX = 0b10000010;
ADCSRA = 0b10001111;
DIDR0 = BIT(ADC2D);
// led output pin
avr_cpp_lib::OutputPin ledOut(&DDRA, &PORTA, PA0);
// enable interrupts
sei();
uint16_t button_state = 0;
uint8_t pwm_state = 0;
uint16_t adc_state = 0;
uint16_t led_state = 0;
uint16_t shutdown_timeout = UINT16_MAX;
uint8_t ir_state = 0;
for (;;) {
// ir state machine
switch (ir_state) {
case 0: // start first led
SETBIT(DDRA, PA7);
ir_state = 1;
ir_count = 0;
break;
case 1: // stop led
if (ir_count >= 20) {
CLEARBIT(DDRA, PA7);
ir_state = 2;
}
break;
case 2: // wait till after possible beginning (just)
if (ir_count >= 64) {
ir_state = 3;
}
break;
case 3: // check for signal and timeout
if (BITCLEAR(PINB, PB1)) {
ir_state = 4;
}
if (ir_count >= 130) {
ir_count = 0;
ir_state = 15;
}
break;
case 4: // wait till end of signal
if (BITSET(PINB, PB1)) {
ir_state = 5;
ir_count = 0;
}
break;
case 5: // wait for required time and transmit
if (ir_count >= 24) {
ir_state = 6;
SETBIT(DDRB, PB2);
ir_count = 0;
}
break;
case 6: // stop signal
if (ir_count >= 20) {
CLEARBIT(DDRB, PB2);
ir_state = 7;
}
break;
case 7: // wait till just after possible start
if (ir_count >= 64) {
ir_state = 8;
}
break;
case 8: // check for signal and timeout
if (BITCLEAR(PINB, PB0)) {
ir_state = 9;
}
if (ir_count >= 130) {
ir_count = 0;
ir_state = 15;
}
break;
case 9: // wait till end of signal
if (BITSET(PINB, PB0)) {
ir_state = 10;
ir_count = 0;
}
break;
case 10: // wait required time, transmit
if (ir_count >= 24) {
ir_state = 11;
SETBIT(DDRA, PA6);
ir_count = 0;
}
break;
case 11:
if (ir_count >= 20) { // stop led
CLEARBIT(DDRA, PA6);
ir_state = 12;
}
break;
case 12:
if (ir_count >= 64) { // wait to make sure signal stops at other end
ir_state = 0;
shutdown_timeout = UINT16_MAX;
}
break;
case 15: // timeout
if (ir_count >= 100) {
ir_state = 0;
}
break;
}
if (BITSET(flags, MS_FLAG)) {
CLEARBIT(flags, MS_FLAG);
// shutdown
if (shutdown_timeout > 0) {
shutdown_timeout--;
} else {
break;
}
// adc
if (adc_state == 2000) {
adc_state = 0;
SETBIT(ADCSRA, ADSC);
} else {
adc_state++;
}
// voltage cutoff
if (BITSET(flags, VOLTAGE_CUTOFF)) {
break;
}
// pwm of leds
if (pwm_state < 3) {
if (pwm_state == 0) {
if (BITSET(flags, VOLTAGE_WARNING)) {
led_state++;
if (led_state > 300) {
ledOut.set();
if (led_state > 400) {
led_state = 0;
}
}
} else {
ledOut.set();
}
} else if (pwm_state == 1) {
ledOut.clear();
}
pwm_state++;
} else {
pwm_state = 0;
}
// button
if (BITSET(PINA, PA1)) {
button_state = 0;
} else {
shutdown_timeout = UINT16_MAX;
// shutdown if pressed for 1s
if (button_state >= 1000) {
break;
}
// button pressed
button_state++;
}
}
}
// going to shutdown, turn off led
ledOut.clear();
// wait for button release
while (BITCLEAR(PINA, PA1));
CLEARBIT(PORTA, PA3);
}
ISR(TIM1_COMPA_vect) {
ir_count++;
static uint8_t c = 75;
if (c > 0) {
c--;
} else {
c = 75;
SETBIT(flags, MS_FLAG);
}
}
ISR(ADC_vect) {
static uint8_t count = 0;
static uint16_t accumulator = 0;
accumulator += ADC;
count++;
if (count > 59) {
accumulator /= 60;
if (accumulator < 900) {
SETBIT(flags, VOLTAGE_WARNING);
if (accumulator < 850) {
SETBIT(flags, VOLTAGE_CUTOFF);
}
}
count = 0;
accumulator = 0;
} else {
SETBIT(ADCSRA, ADSC);
}
}
<commit_msg>Some optimization<commit_after>/* File: main.cpp
* Contains base main function and usually all the other stuff that avr does...
*/
/* Copyright (c) 2012-2013 Domen Ipavec (domen.ipavec@z-v.si)
*
* 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.
*/
#define F_CPU 8000000UL // 8 MHz
//#include <util/delay.h>
#define SHUTDOWN_TIMEOUT 1500
#define ADC_TIMEOUT 200
#define ADC_STARTUP 10
#include <avr/io.h>
#include <avr/interrupt.h>
//#include <avr/pgmspace.h>
//#include <avr/eeprom.h>
#include <stdint.h>
#include "bitop.h"
//#include "shiftOut.h"
#include "io.h"
volatile uint8_t flags = 0;
#define VOLTAGE_WARNING 0
#define VOLTAGE_CUTOFF 1
volatile uint8_t ir_count = 0;
volatile uint16_t ms_count = 0;
int main() {
// INIT
// soft power button
SETBIT(DDRA, PA3);
SETBIT(PORTA, PA3);
SETBIT(PORTA, PA1);
// timer 1 for 76khz interrupt and pwm for one led
TCCR1A = 0b01000000;
TCCR1B = 0b00001001; // CTC mode
OCR1A = 105; // clear
TIMSK1 = 0b00000010; // ocie1a interrupt
// pwm for leds
// 0
//SETBIT(DDRA, PA7);
// 1
//SETBIT(DDRB, PB2);
// 2
//SETBIT(DDRA, PA6);
TCCR0A = 0b01010010;
TCCR0B = 0b00000001;
OCR0A = 105;
OCR0B = 105;
// adc measurement
ADMUX = 0b10000010;
ADCSRA = 0b10001111;
DIDR0 = BIT(ADC2D);
// led output pin
avr_cpp_lib::OutputPin ledOut(&DDRA, &PORTA, PA0);
ledOut.set();
// enable interrupts
sei();
uint8_t button_state = 0;
uint8_t led_state = 0;
uint8_t adc_timeout = ADC_STARTUP;
uint16_t shutdown_timeout = SHUTDOWN_TIMEOUT;
uint8_t ir_state = 0;
for (;;) {
// ir state machine
switch (ir_state) {
case 0: // start first led
SETBIT(DDRA, PA7);
ir_state = 1;
ir_count = 0;
break;
case 1: // stop led
if (ir_count >= 20) {
CLEARBIT(DDRA, PA7);
ir_state = 2;
}
break;
case 2: // wait till after possible beginning (just)
if (ir_count >= 64) {
ir_state = 3;
}
break;
case 3: // check for signal and timeout
if (BITCLEAR(PINB, PB1)) {
ir_state = 4;
}
if (ir_count >= 130) {
ir_count = 0;
ir_state = 15;
}
break;
case 4: // wait till end of signal
if (BITSET(PINB, PB1)) {
ir_state = 5;
ir_count = 0;
}
break;
case 5: // wait for required time and transmit
if (ir_count >= 24) {
ir_state = 6;
SETBIT(DDRB, PB2);
ir_count = 0;
}
break;
case 6: // stop signal
if (ir_count >= 20) {
CLEARBIT(DDRB, PB2);
ir_state = 7;
}
break;
case 7: // wait till just after possible start
if (ir_count >= 64) {
ir_state = 8;
}
break;
case 8: // check for signal and timeout
if (BITCLEAR(PINB, PB0)) {
ir_state = 9;
}
if (ir_count >= 130) {
ir_count = 0;
ir_state = 15;
}
break;
case 9: // wait till end of signal
if (BITSET(PINB, PB0)) {
ir_state = 10;
ir_count = 0;
}
break;
case 10: // wait required time, transmit
if (ir_count >= 24) {
ir_state = 11;
SETBIT(DDRA, PA6);
ir_count = 0;
}
break;
case 11:
if (ir_count >= 20) { // stop led
CLEARBIT(DDRA, PA6);
ir_state = 12;
}
break;
case 12:
if (ir_count >= 64) { // wait to make sure signal stops at other end
ir_state = 0;
shutdown_timeout = SHUTDOWN_TIMEOUT;
}
break;
case 15: // timeout
if (ir_count >= 100) {
ir_state = 0;
}
break;
}
// execute every 50ms
if (ms_count >= 3810) {
ms_count = 0;
// shutdown after 75s
if (shutdown_timeout > 0) {
shutdown_timeout--;
} else {
break;
}
// adc every 10s
if (adc_timeout > 0) {
adc_timeout--;
} else {
adc_timeout = ADC_TIMEOUT;
SETBIT(ADCSRA, ADSC);
}
// if anything in flags
if (flags > 0) {
// voltage cutoff
if (BITSET(flags, VOLTAGE_CUTOFF)) {
break;
}
// blinking led
if (BITSET(flags, VOLTAGE_WARNING)) {
led_state++;
if (led_state == 6) {
ledOut.set();
if (led_state == 8) {
ledOut.clear();
led_state = 0;
}
}
}
}
// button
if (BITSET(PINA, PA1)) {
button_state = 0;
} else {
shutdown_timeout = SHUTDOWN_TIMEOUT;
// shutdown if pressed for 1s
if (button_state >= 20) {
break;
}
// button pressed
button_state++;
}
}
}
// going to shutdown, turn off led
ledOut.clear();
// wait for button release
while (BITCLEAR(PINA, PA1));
CLEARBIT(PORTA, PA3);
}
ISR(TIM1_COMPA_vect) {
ir_count++;
ms_count++;
}
ISR(ADC_vect) {
static uint8_t count = 0;
static uint16_t accumulator = 0;
accumulator += ADC;
count++;
if (count > 32) {
accumulator >>= 5;
if (accumulator < 900) {
SETBIT(flags, VOLTAGE_WARNING);
if (accumulator < 850) {
SETBIT(flags, VOLTAGE_CUTOFF);
}
}
count = 0;
accumulator = 0;
} else {
SETBIT(ADCSRA, ADSC);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <allegro5/allegro5.h>
#include <allegro5/display.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_color.h>
#include "Object.h"
#include "Ball.h"
int main(int argc, char **argv)
{
al_init();
al_init_font_addon();
al_init_image_addon();
al_init_primitives_addon();
al_install_keyboard();
int displayFlags = al_get_new_display_flags();
#ifdef WIN32
al_set_new_bitmap_flags(displayFlags | ALLEGRO_FULLSCREEN);
#else
al_set_new_display_flags(displayFlags | ALLEGRO_FULLSCREEN_WINDOW);
#endif
ALLEGRO_DISPLAY *display = al_create_display(1024, 600);
al_clear_to_color(al_map_rgb(13, 13, 13));
al_flip_display();
ALLEGRO_FONT *sysFont = al_create_builtin_font();
ALLEGRO_TIMER *timer = al_create_timer(1 / 60.0);
ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_keyboard_event_source());
al_register_event_source(queue, al_get_timer_event_source(timer));
al_start_timer(timer);
bool done = false;
bool redraw = false;
Ball obj1(512, 300, 500, 500, 0, "fhioekl");
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(queue, &ev);
switch(ev.type)
{
case ALLEGRO_EVENT_DISPLAY_CLOSE:
done = true;
break;
case ALLEGRO_EVENT_TIMER:
obj1.update();
redraw = true;
break;
case ALLEGRO_EVENT_KEY_DOWN:
if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
{
done = true;
}
break;
default:
break;
}
if(al_is_event_queue_empty(queue) && redraw)
{
al_clear_to_color(al_color_html("#212121"));
obj1.draw();
redraw = false;
al_flip_display();
}
}
return EXIT_SUCCESS;
}
<commit_msg>Change the application icon during runtime<commit_after>#include <iostream>
#include <allegro5/allegro5.h>
#include <allegro5/display.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_color.h>
#include "Object.h"
#include "Ball.h"
int main(int argc, char **argv)
{
al_init();
al_init_font_addon();
al_init_image_addon();
al_init_primitives_addon();
al_install_keyboard();
int displayFlags = al_get_new_display_flags();
#ifdef _WIN32
al_set_new_bitmap_flags(displayFlags | ALLEGRO_FULLSCREEN);
#else
al_set_new_display_flags(displayFlags | ALLEGRO_FULLSCREEN_WINDOW);
#endif
ALLEGRO_DISPLAY *display = al_create_display(1024, 600);
Object iconObject(0, 0, 100, 100, 0, 0, 0, "This only hold the icon for the game, that is, the error image! :)");
al_set_window_title(display, "Pong Clone");
al_set_display_icon(display, iconObject.getBitmap());
al_clear_to_color(al_map_rgb(13, 13, 13));
al_flip_display();
ALLEGRO_FONT *sysFont = al_create_builtin_font();
ALLEGRO_TIMER *timer = al_create_timer(1 / 60.0);
ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_keyboard_event_source());
al_register_event_source(queue, al_get_timer_event_source(timer));
al_start_timer(timer);
bool done = false;
bool redraw = false;
Ball obj1(512, 300, 50, 50, 0, "Error Image loaded here!");
obj1.reset();
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(queue, &ev);
switch(ev.type)
{
case ALLEGRO_EVENT_DISPLAY_CLOSE:
done = true;
break;
case ALLEGRO_EVENT_TIMER:
obj1.update();
redraw = true;
break;
case ALLEGRO_EVENT_KEY_DOWN:
if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
{
done = true;
}
break;
default:
break;
}
if(al_is_event_queue_empty(queue) && redraw)
{
al_clear_to_color(al_color_html("#212121"));
obj1.draw();
al_flip_display();
redraw = false;
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>c014dfd2-35ca-11e5-9063-6c40088e03e4<commit_msg>c01b8670-35ca-11e5-9b04-6c40088e03e4<commit_after>c01b8670-35ca-11e5-9b04-6c40088e03e4<|endoftext|> |
<commit_before>533a5d23-2e4f-11e5-a68f-28cfe91dbc4b<commit_msg>53412fe6-2e4f-11e5-a5ff-28cfe91dbc4b<commit_after>53412fe6-2e4f-11e5-a5ff-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <sstream>
using namespace std;
//TODO:
// Create parse function
// Add execute functionality to both classes
// Write loop in main function
class Shell{
public:
Shell* first;
Shell* second;
Shell(){};
virtual bool execute() = 0;
};
class Connector : public Shell{
public:
Shell* first;
Shell* second;
Connector() : Shell(){};
Connector(Shell* f, Shell* s) : first(f), second(s){};
virtual bool execute() = 0; // for compiler
};
class Bars : public Connector{
public:
Bars() : Connector (){};
Bars(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
if(!first->execute()){
return second->execute();
}
return true;
}
};
class Semi : public Connector{
public:
Semi() : Connector (){};
Semi(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
first->execute();
return second->execute();
}
};
class Amp : public Connector{
public:
Amp() : Connector (){};
Amp(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
if(first->execute()){
return second->execute();
}
return false; // else
}
};
class Command : public Shell{
public:
const char* cmd;
vector<string> args;
Command() : Shell(){};
Command(char c[], vector<string> a) : Shell(), cmd(c), args(a) {};
bool execute(){
cout << "executed command" << endl;
return true;
}
};
Shell* stringToCommand(string commandLine){
stringstream ss;
ss << commandLine;
// //sets up everything to use strtok
// char* cmdLine = new char[cmd.length() + 1];
// const char s[2] = " ";
// char *token;
// token = strtok(cmdLine, s);
//builds new command
Command* temp = new Command;
string tempString;
ss >> tempString;
temp->cmd = tempString.c_str();
while(ss >> tempString){
temp->args.push_back(tempString);
}
// if(token != NULL){
// }
// while(token != NULL){
// temp->args.push_back(token);
// token = strtok(NULL, s);
// }
return temp;
}
void parse(string commandLine){
Shell* top = NULL;
vector<string> commands;
vector<string> connectors;
for(int i = 0; i < commandLine.size(); ++i){
cout << "current: " << i << endl;
string temp;
if(commandLine.at(i) == ';'){
cout << "found semi" << endl;
//make substr
cout << "created substr" << endl;
temp = commandLine.substr(0, i);
cout << "substr: " << temp << endl;
//delete what we took
cout << "erased substr from master string" << endl;
commandLine.erase(0, i + 1);
cout << "new master string: " << commandLine << endl;
//reset i
i = 0;
cout << "top: " << top << endl;
//issue where it never enteres the first if statement
if(top = NULL){
cout << "top is empty" << endl;
Shell* connect = new Semi;
top = connect;
connect->first = stringToCommand(temp);
}
else{
cout << "top is not empty" << endl;
Shell* connect = new Semi;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
else if(commandLine.at(i) == '|'){
if(commandLine.at(i + 1) == '|'){
//make substr
temp = commandLine.substr(0, i);
//delete what we took
commandLine.erase(0, i); //see below for deleting both connectors
//reset i
i = 0;
if(top = NULL){
Shell* connect = new Bars;
top = connect;
connect->first = stringToCommand(temp);
}
else{
Shell* connect = new Bars;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
}
else if(commandLine.at(i) == '&'){
if(commandLine.at(i + 1) == '&'){
//make substr
temp = commandLine.substr(0, i);
//delete what we took
commandLine.erase(0, i); //need to change it so that it deletes both connectors
//reset i
i = 0;
if(top = NULL){
Shell* connect = new Amp;
top = connect;
connect->first = stringToCommand(temp);
}
else{
Shell* connect = new Amp;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
}
// else{ //this needs to get moved outside of the loop
// //this gets called every i that is not a connector
// cout << "no connector found!" << endl;
// //make substr
// temp = commandLine.substr(0, i);
// //if top != null, top->second = stringToCommand
// if(top == NULL){
// top = stringToCommand(temp);
// }
// else{
// top->second = stringToCommand(temp);
// }
// //if top == null, top = stringToCommand
// }
// }
cout << "no connector found!" << endl;
string temp = commandLine;
if(top == NULL){
top = stringToCommand(temp);
}
else{
top->second = stringToCommand(temp);
}
}
int main() {
string commandLine;
while(commandLine != "exit"){
cout << '$';
getline(cin, commandLine);
parse(commandLine);
}
return 0;
}
<commit_msg>fixed segfault error and a few other issues<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <sstream>
using namespace std;
//TODO:
// Add execute functionality to both classes
class Shell{
public:
Shell* first;
Shell* second;
Shell(){};
virtual bool execute() = 0;
};
class Connector : public Shell{
public:
Shell* first;
Shell* second;
Connector() : Shell(){};
Connector(Shell* f, Shell* s) : first(f), second(s){};
virtual bool execute() = 0; // for compiler
};
class Bars : public Connector{
public:
Bars() : Connector (){};
Bars(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
if(!first->execute()){
return second->execute();
}
return true;
}
};
class Semi : public Connector{
public:
Semi() : Connector (){};
Semi(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
cout << "executing tree" << endl;
first->execute();
cout << "executed first" << endl;
return second->execute();
}
};
class Amp : public Connector{
public:
Amp() : Connector (){};
Amp(Shell* f, Shell* s) : Connector(f, s){};
bool execute(){
if(first->execute()){
return second->execute();
}
return false; // else
}
};
class Command : public Shell{
public:
const char* cmd;
vector<string> args;
Command() : Shell(){};
Command(char c[], vector<string> a) : Shell(), cmd(c), args(a) {};
bool execute(){
cout << "executed command" << endl;
return true;
}
};
Shell* stringToCommand(string commandLine){
cout << "starting stringToCommand" << endl;
stringstream ss;
ss << commandLine;
// //sets up everything to use stringstream
//builds new command
Command* temp = new Command;
string tempString;
ss >> tempString;
temp->cmd = tempString.c_str();
//takes in any potential arguments
while(ss >> tempString){
temp->args.push_back(tempString);
}
return temp;
}
void parse(string commandLine){
Shell* top = 0;
for(int i = 0; i < commandLine.size(); ++i){
string temp;
if(commandLine.at(i) == ';'){
//make substr
temp = commandLine.substr(0, i);
//delete what we took
commandLine.erase(0, i + 1);
//reset i
i = 0;
//issue where it never enteres the first if statement
if(top == 0){
Shell* connect = new Semi;
top = connect;
connect->first = stringToCommand(temp);
}
else{
Shell* connect = new Semi;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
else if(commandLine.at(i) == '|'){
if(commandLine.at(i + 1) == '|'){
//make substr
temp = commandLine.substr(0, i);
//delete what we took
commandLine.erase(0, i + 2); //see below for deleting both connectors
//reset i
i = 0;
if(top == 0){
Shell* connect = new Bars;
top = connect;
connect->first = stringToCommand(temp);
}
else{
Shell* connect = new Bars;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
}
else if(commandLine.at(i) == '&'){
if(commandLine.at(i + 1) == '&'){
//make substr
temp = commandLine.substr(0, i);
//delete what we took
commandLine.erase(0, i + 2); //need to change it so that it deletes both connectors
//reset i
i = 0;
if(top == 0){
Shell* connect = new Amp;
top = connect;
connect->first = stringToCommand(temp);
}
else{
Shell* connect = new Amp;
connect->first = top;
top->second = stringToCommand(temp);
top = connect;
}
}
}
}
string temp = commandLine;
if(top == NULL){
top = stringToCommand(temp);
}
else{
top->second = stringToCommand(temp);
}
//top->execute();
}
int main() {
string commandLine;
while(commandLine != "exit"){
cout << '$';
getline(cin, commandLine);
parse(commandLine);
}
return 0;
}
<|endoftext|> |
<commit_before>8fdfbca3-4b02-11e5-8249-28cfe9171a43<commit_msg>add file<commit_after>8feb3b5e-4b02-11e5-b5aa-28cfe9171a43<|endoftext|> |
<commit_before>d2f1df8c-2e4e-11e5-b045-28cfe91dbc4b<commit_msg>d2f8682b-2e4e-11e5-9402-28cfe91dbc4b<commit_after>d2f8682b-2e4e-11e5-9402-28cfe91dbc4b<|endoftext|> |
<commit_before>a1399cfa-2747-11e6-9e02-e0f84713e7b8<commit_msg>ashley broke it<commit_after>a1d4fbfa-2747-11e6-9e6b-e0f84713e7b8<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <fstream>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"
using namespace std;
int main(){
vector<Usuario> vUsuario;
vector<Cliente> vCliente;
vector<Personal> vPersonal;
vector<Administrador> vAdministrador;
vector<Chef> vChef;
vector<Lavaplatos> vLavaplatos;
vector<Mesero> vMesero;
int opcMenu;
do{
cout<<"Menú";
cout<<"1. Agregar"<<endl;
cout<<"2. Listar"<<endl;
cout<<"3. Modificar"<<endl;
cout<<"4. Eliminar"<<endl;
cout<<"5. Guardar en archivos de texto"<<endl;
cout<<"6. Leer de archivos de texto"<<endl;
cout<<"7. Guardar en binarios"<<endl;
cout<<"7. Leer de binarios"<<endl;
cout<<"8. Salir"<<endl;
cout<<"Ingrese opción: "<<endl;
cin>>opcMenu;
switch(opcMenu){
case 1:
break;
case 2:
cout<<"Menú listar";
cout<<"1. Usuario";
cout<<"2. Cliente";
cout<<"3. Personal";
cout<<"4. Administrador";
cout<<"5. Chef";
cout<<"6. Lavaplatos";
cout<<"7. Mesero";
int opcListar;
cout<<"Ingrese la opción: ";
cin>>opcListar;
switch(opcListar){
case 1:
for(int i=0;i<vUsuario.size();i++){
cout<<Username<<" = "<<vUsuario.getUsername();
cout<<Password<<" = "<<vUsuario.getPassword();
cout<<Edad<<" = "<<vUsuario.getEdad();
cout<<Id<<" = "<<vUsuario.getId();
cout<<Telefono<<" = "<<vUsuario.getTelefono();
}break;
case 2:
for(int i=0;i<vCliente.size();i++){
cout<<Direccion<<" = "<<vCliente.getDireccion();
cout<<Estrellas<<" = "<<vCliente.getEstrellas();
}break;
case 3:
for(int i=0;i<vPersonal.size();i++){
cout<<AnioContratado<<" = "<<vPersonal.getAnioContratado();
}break;
case 4:
for(int i=0;i<vAdministrador.size();i++){
cout<<Contratados<<" = "<<vAdministrador.getContratados();
cout<<Despedidos<<" = "<<vAdministrador.getDespedidos();
}break;
case 5:
for(int i=0;i<vChef.size();i++){
cout<<PlatilloFavorito<<" = "<<vChef.getPlatilloFavorito();
cout<<Rating<<" = "<<vChef.getRating();
}break;
case 6:
for(int i=0;i<vLavaplatos.size();i++){
cout<<Motivacion<<" = "<<vLavaplatos.getMotivacion();
}break;
case 7:
for(int i=0;i<vMesero.size();i++){
cout<<Platillos<<" = "<<vMesero.getPlatillos();
}break;
}
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}while(opcMenu!=8);
}
Usuario agregarUsuario(){
cout<<"Menú agregar";
cout<<"1. Usuario";
cout<<"2. Cliente";
cout<<"3. Personal";
cout<<"4. Administrador";
cout<<"5. Chef";
cout<<"6. Lavaplatos";
cout<<"7. Mesero";
int opcAgregar;
cout<<"Ingrese la opción: ";
cin>>opcAgregar;
switch(opcAgregar){
case 1:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
Usuario temporal(username,nombre,password,edad,id,telefono);
return temporal;
break;
}
case 2:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
string direccion;
cout<<"Ingrese direccion: ";
cin>>direccion;
int estrellas;
cout<<"Ingrese estrellas: ";
cin>>estrellas;
Cliente temporal(username,nombre,password,edad,id,telefono,direccion,estrellas);
return temporal;
break;
}
case 3:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
int aniocontratado;
cout<<"Ingrese aniocontratado: ";
cin>>aniocontratado;
double sueldo;
cout<<"Ingrese sueldo: ";
cin>>sueldo;
Personal temporal(username,nombre,password,edad,id,telefono,aniocontratado,sueldo);
return temporal;
break;
}
case 4:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
int contratados;
cout<<"Ingrese contratados: ";
cin>>contratados;
int despedidos;
cout<<"Ingrese despedidos: ";
cin>>despedidos;
cout<<"Ingrese aniocontratado: ";
cin>>aniocontratado;
double sueldo;
cout<<"Ingrese sueldo: ";
cin>>sueldo;
Administrador temporal(username,nombre,password,edad,id,telefono,aniocontratado,sueldo,contratados,despedidos);
return temporal;
break;
}
case 5:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
string platillofavorito;
cout<<"Ingrese aniocontratado: ";
cin>>aniocontratado;
double sueldo;
cout<<"Ingrese sueldo: ";
cin>>sueldo;
cout<<"Ingrese platillofavorito: ";
cin>>platillofavorito;
int rating;
cout<<"Ingrese rating: ";
cin>>rating;
Chef temporal(username,nombre,password,edad,id,telefono,aniocontratado,sueldo,platillofavorito,rating);
return temporal;
break;
}
case 6:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
double motivacion;
cout<<"Ingrese aniocontratado: ";
cin>>aniocontratado;
double sueldo;
cout<<"Ingrese sueldo: ";
cin>>sueldo;
cout<<"Ingrese motivacion: ";
cin>>motivacion;
Lavaplatos temporal(username,nombre,password,edad,id,telefono,aniocontratado,sueldo,motivacion);
return temporal;
break;
}
case 7:{
string username;
cout<<"Ingrese username: ";
cin>>username;
string password;
string nombre;
cout<<"Ingrese nombre: ";
cin>>nombre;
cout<<"Ingrese password: ";
cin>>password;
int edad;
cout<<"Ingrese edad: ";
cin>>edad;
string id;
cout<<"Ingrese id: ";
cin>>id;
string telefono;
cout<<"Ingrese telefono: ";
cin>>telefono;
string platillos;
cout<<"Ingrese aniocontratado: ";
cin>>aniocontratado;
double sueldo;
cout<<"Ingrese sueldo: ";
cin>>sueldo;
cout<<"Ingrese platillos: ";
cin>>platillos;
Mesero temporal(username,nombre,password,edad,id,telefono,aniocontratado,sueldo,platillos);
return temporal;
break;
}
}
}
vector<Usuario*> eliminarUsuario(vector<Usuario*> usuarios){
int i;
cout<<"Ingrese la posición del usuario que desea eliminar"<<endl;
cin>>i;
usuarios.erase(usuarios.begin()+i);
return usuarios;
}
void guardarArchivo(vector<Usuario> Usuarios){
//Clientes
string Clientes="";
string Administradores="";
string Chefs="";
string Lavaplatos="";
string Meseros="";
for (int i = 0; i < Usuarios.size(); ++i)
{
if (typeid((*(Usuarios[i])).name()).compare(typeid(Cliente).name())==0)
{
Clientes+=Usuarios[i]->getUsername()+" ";
Clientes+=Usuarios[i]->getNombre()+" ";
Clientes+=Usuarios[i]->getPassword()+" ";
Clientes+=Usuarios[i]->getEdad()+" ";
}
}
ofstream archivo;
string nombreArchivo;
archivo.open("prueba.txt",ios::out);
if (archivo.fail()){
cout<<"No se puede abrir el archivo";
exit(1);
}
archivo<<Clientes;
}<commit_msg>Trabajando ~~<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <fstream>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"
using namespace std;
void guardarArchivo(vector<Usuario*>);
int main(){
vector<Usuario*> u;
Cliente c("jalvarez","Jorge","asdf",23,"0801","98202419","Honduras",7);
u.push_back(&c);
Mesero m("jalvarez","Jorge","asdf",23,"0801","98654",5,15.5);
u.push_back(&m);
guardarArchivo(u);
}
vector<Usuario*> eliminarUsuario(vector<Usuario*> usuarios){
int i;
cout<<"Ingrese la posición del usuario que desea eliminar: "<<endl;
cin>>i;
usuarios.erase(usuarios.begin()+i);
return usuarios;
}
void guardarArchivo(vector<Usuario*> Usuarios){
//Clientes
string Clientes="";
string Administradores="";
string Chefs="";
string Lavaplatoss="";
string Meseros="";
for (int i = 0; i < Usuarios.size(); ++i)
{
if(dynamic_cast<Cliente*>(Usuarios[i]))
{
Cliente* temp=dynamic_cast<Cliente*>(Usuarios[i]);
Clientes+=temp->getUsername()+" ";
Clientes+=temp->getNombre()+" ";
Clientes+=temp->getPassword()+" ";
Clientes+=to_string(temp->getEdad())+" ";
Clientes+=temp->getId()+" ";
Clientes+=temp->getTelefono()+" ";
Clientes+=temp->getDireccion()+" ";
Clientes+=to_string(temp->getEstrellas())+" ";
Clientes+="\n";
}
if(dynamic_cast<Administrador*>(Usuarios[i]))
{
Administrador* temp=dynamic_cast<Administrador*>(Usuarios[i]);
Administradores+=temp->getUsername()+" ";
Administradores+=temp->getNombre()+" ";
Administradores+=temp->getPassword()+" ";
Administradores+=to_string(temp->getEdad())+" ";
Administradores+=temp->getId()+" ";
Administradores+=temp->getTelefono()+" ";
Administradores+=to_string(temp->getAnioContratado())+" ";
Administradores+=to_string(temp->getSueldo())+" ";
Administradores+=to_string(temp->getContratados())+" ";
Administradores+=to_string(temp->getDespedidos())+" ";
Administradores+="\n";
}
if(dynamic_cast<Chef*>(Usuarios[i]))
{
Chef* temp=dynamic_cast<Chef*>(Usuarios[i]);
Chefs+=temp->getUsername()+" ";
Chefs+=temp->getNombre()+" ";
Chefs+=temp->getPassword()+" ";
Chefs+=to_string(temp->getEdad())+" ";
Chefs+=temp->getId()+" ";
Chefs+=temp->getTelefono()+" ";
Chefs+=to_string(temp->getAnioContratado())+" ";
Chefs+=to_string(temp->getSueldo())+" ";
Chefs+=temp->getPlatilloFavorito()+" ";
Chefs+=to_string(temp->getRating())+" ";
Chefs+="\n";
}
if(dynamic_cast<Lavaplatos*>(Usuarios[i]))
{
Lavaplatos* temp=dynamic_cast<Lavaplatos*>(Usuarios[i]);
Lavaplatoss+=temp->getUsername()+" ";
Lavaplatoss+=temp->getNombre()+" ";
Lavaplatoss+=temp->getPassword()+" ";
Lavaplatoss+=to_string(temp->getEdad())+" ";
Lavaplatoss+=temp->getId()+" ";
Lavaplatoss+=temp->getTelefono()+" ";
Lavaplatoss+=to_string(temp->getAnioContratado())+" ";
Lavaplatoss+=to_string(temp->getSueldo())+" ";
Lavaplatoss+=to_string(temp->getMotivacion())+" ";
Lavaplatoss+="\n";
}
if(dynamic_cast<Mesero*>(Usuarios[i]))
{
Mesero* temp=dynamic_cast<Mesero*>(Usuarios[i]);
Meseros+=temp->getUsername()+" ";
Meseros+=temp->getNombre()+" ";
Meseros+=temp->getPassword()+" ";
Meseros+=to_string(temp->getEdad())+" ";
Meseros+=temp->getId()+" ";
Meseros+=temp->getTelefono()+" ";
Meseros+=to_string(temp->getAnioContratado())+" ";
Meseros+=to_string(temp->getSueldo())+" ";
Meseros+="\n";
}
}
cout<<Clientes;
ofstream archivo;
string nombreArchivo;
archivo.open("Clientes.txt",ios::out);
archivo<<Clientes;
archivo.close();
archivo.open("Administradores.txt",ios::out);
archivo<<Administradores;
archivo.close();
archivo.open("Chefs.txt",ios::out);
archivo<<Chefs;
archivo.close();
archivo.open("Administradores.txt",ios::out);
archivo<<Administradores;
archivo.close();
archivo.open("Lavaplatos.txt",ios::out);
archivo<<Lavaplatoss;
archivo.close();
archivo.open("Meseros.txt",ios::out);
archivo<<Meseros;
archivo.close();
}<|endoftext|> |
<commit_before>9c6fbbeb-327f-11e5-99d7-9cf387a8033e<commit_msg>9c75db73-327f-11e5-9417-9cf387a8033e<commit_after>9c75db73-327f-11e5-9417-9cf387a8033e<|endoftext|> |
<commit_before>7374b766-5216-11e5-bed7-6c40088e03e4<commit_msg>737e9b50-5216-11e5-877c-6c40088e03e4<commit_after>737e9b50-5216-11e5-877c-6c40088e03e4<|endoftext|> |
<commit_before>c1d0a8c2-327f-11e5-88bf-9cf387a8033e<commit_msg>c1d7c363-327f-11e5-b93a-9cf387a8033e<commit_after>c1d7c363-327f-11e5-b93a-9cf387a8033e<|endoftext|> |
<commit_before>794ff312-5216-11e5-b1dc-6c40088e03e4<commit_msg>795690dc-5216-11e5-accc-6c40088e03e4<commit_after>795690dc-5216-11e5-accc-6c40088e03e4<|endoftext|> |
<commit_before>763191b4-2d53-11e5-baeb-247703a38240<commit_msg>76320f0e-2d53-11e5-baeb-247703a38240<commit_after>76320f0e-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>7e791998-2d15-11e5-af21-0401358ea401<commit_msg>7e791999-2d15-11e5-af21-0401358ea401<commit_after>7e791999-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>66079c6c-5216-11e5-9173-6c40088e03e4<commit_msg>660e6ee6-5216-11e5-b3ac-6c40088e03e4<commit_after>660e6ee6-5216-11e5-b3ac-6c40088e03e4<|endoftext|> |
<commit_before>cbae0f38-327f-11e5-8ee7-9cf387a8033e<commit_msg>cbb6fd97-327f-11e5-863e-9cf387a8033e<commit_after>cbb6fd97-327f-11e5-863e-9cf387a8033e<|endoftext|> |
<commit_before>0acf9cb0-585b-11e5-b966-6c40088e03e4<commit_msg>0ad66b9e-585b-11e5-b59f-6c40088e03e4<commit_after>0ad66b9e-585b-11e5-b59f-6c40088e03e4<|endoftext|> |
<commit_before>82d462dc-4b02-11e5-9dcd-28cfe9171a43<commit_msg>GOD DAMNED IT!<commit_after>82e29378-4b02-11e5-bf58-28cfe9171a43<|endoftext|> |
<commit_before>7f3bdd68-4b02-11e5-831a-28cfe9171a43<commit_msg>Fixed that one bug<commit_after>7f4a3763-4b02-11e5-8aec-28cfe9171a43<|endoftext|> |
<commit_before>e6fa9bc0-585a-11e5-b4dd-6c40088e03e4<commit_msg>e7010bf4-585a-11e5-8d1d-6c40088e03e4<commit_after>e7010bf4-585a-11e5-8d1d-6c40088e03e4<|endoftext|> |
<commit_before>2837a6a6-2d3f-11e5-b718-c82a142b6f9b<commit_msg>28a2a117-2d3f-11e5-be3e-c82a142b6f9b<commit_after>28a2a117-2d3f-11e5-be3e-c82a142b6f9b<|endoftext|> |
<commit_before>147273d7-2e4f-11e5-8b38-28cfe91dbc4b<commit_msg>147dcd8c-2e4f-11e5-abf0-28cfe91dbc4b<commit_after>147dcd8c-2e4f-11e5-abf0-28cfe91dbc4b<|endoftext|> |
<commit_before>d99bc918-585a-11e5-9c59-6c40088e03e4<commit_msg>d9a2a5d0-585a-11e5-a0fa-6c40088e03e4<commit_after>d9a2a5d0-585a-11e5-a0fa-6c40088e03e4<|endoftext|> |
<commit_before>9697cb70-4b02-11e5-ba99-28cfe9171a43<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>96a584eb-4b02-11e5-b893-28cfe9171a43<|endoftext|> |
<commit_before>76380b34-2d53-11e5-baeb-247703a38240<commit_msg>7638887a-2d53-11e5-baeb-247703a38240<commit_after>7638887a-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
using namespace std;
vector<string> split(const string& str) {
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
using RoomID = int;
struct RoomObject
{
vector<string> names;
string description;
bool visible;
};
struct Map
{
static const int max_width = 100, max_height = 100;
static const int player_start_x = 50, player_start_y = 50;
enum Location
{
UNKNOWN,
GRAVEYARD,
GRAVEYARD_GATES,
KHATHARRS_MOMS_HOUSE,
GATES_OF_SHOGUN,
HOUSE_OF_BLUES,
FOGGY_FOREST
};
Location map_location[max_width][max_height];
int x, y;
Map()
{
memset(map_location, UNKNOWN, sizeof(map_location));
x = 50;
y = 50;
map_location[50][50] = GRAVEYARD;
map_location[50][51] = GRAVEYARD_GATES;
map_location[50][52] = KHATHARRS_MOMS_HOUSE;
map_location[50][52] = GATES_OF_SHOGUN;
map_location[50][53] = HOUSE_OF_BLUES;
map_location[50][54] = FOGGY_FOREST;
}
};
struct Entity
{
Entity(string name, int maxHealth) : name(name), health(maxHealth) {}
void heal(int points)
{
health = min(100, health + points);
cout << name << " healed to " << health << " health" << endl;
}
void damage(int points)
{
health = max(0, health - points);
cout << name << " damaged to " << health << "health" << endl;
}
int getHealth() const { return health; }
// Return false if the entity didn't know the command
virtual bool act(vector<string> commands) = 0;
string name;
Map map;
private:
int health;
};
struct Shogun : public Entity {
Shogun() : Entity("Shogibear", 100) {}
};
struct Item
{
virtual void apply(Entity* entity) = 0;
virtual string identify() const = 0;
};
struct HealthItem : public Item
{
HealthItem(int healPower) : healPower(healPower) {}
void apply(Entity* entity) override
{
entity->heal(healPower);
}
string identify() const override
{
stringstream ss;
ss << "Health Potion (" << healPower << ")";
return ss.str();
}
private:
int healPower;
};
struct BlessedSword : public Item
{
BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<
/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
TheFastcall() : Entity("The Fastcall", 22) {}
virtual bool act(vector<string> commands) override
{
}
};
*/
typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.
struct Player : public Entity
{
Player(string name, int health) : Entity(name, health) {}
virtual bool act(vector<string> commands) override
{
auto cmd = commands[0];
if(cmd == "n") { commands = vector<string>{"go","north"}; }
if(cmd == "s") { commands = vector<string>{"go","south"}; }
if(cmd == "e") { commands = vector<string>{"go","east"}; }
if(cmd == "w") { commands = vector<string>{"go","west"}; }
if (commands.size() >= 1 && commands[0] == "look")
{
look();
return true;
}
else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
{
}
else if (commands.size() >= 2 && commands[0] == "go")
{
if (travel(commands[1]) == true)
{
look();
} else {
cout << "Can't travel " << commands[1] << endl;
}
return true;
}
else if (commands.size() >= 1 && commands[0] == "items")
{
showItems();
return true;
}
else if (commands.size() >= 2 && commands[0] == "use")
{
int index = stoi(commands[1]);
useItem(index);
return true;
}
return false;
}
bool travel(string direction)
{
if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
return false;
if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
return false;
if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
return true;/*
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
if (direction == "north")
{
map.y++;
return true;
}
break;
case Map::GRAVEYARD_GATES:
if (direction == "south")
{
map.y--;
return true;
}
if (direction == "north")
{
map.y++;
return true;
}
break;
}
cout << "Can't travel " << direction << endl;
return false;*/
}
void look()
{
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
break;
case Map::GRAVEYARD_GATES:
cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
break;
case Map::KHATHARRS_MOMS_HOUSE:
cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
break;
}
}
void giveItem(shared_ptr<Item> item)
{
inventory.push_back(item);
}
void showItems()
{
if (inventory.size() == 0)
cout << "You have no items." << endl;
int i = 1;
for (auto item : inventory)
{
cout << " " << i++ << ". " << item->identify() << std::endl;
}
}
void useItem(size_t index)
{
if (index > inventory.size())
{
cout << "Invalid index" << endl;
return;
}
inventory[index-1]->apply(this);
inventory.erase(inventory.begin() + index - 1);
}
private:
vector<shared_ptr<Item>> inventory;
unordered_map<string, function<bool(vector<string>)>> actions;
};
struct Room {
string describe() {
stringstream ss;
ss << description << "\n";
ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n"; //make this look nice later
ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
return ss.str();
}
string description;
vector<unique_ptr<Entity>> entities;
vector<RoomObject> objects;
unordered_map<string, RoomID> exits;
};
class Adventure
{
public:
void begin()
{
string command;
cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
cout << "> ";
getline(cin, command);
Player player(command, 100);
player.giveItem(make_shared<HealthItem>(20));
cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
player.look();
while (player.getHealth() > 0)
{
cout << "> ";
getline(cin, command);
if (player.act(split(command)) == false)
cout << "Unknown command" << endl;
}
cout << "You died. Game over." << endl;
}
};
int main()
{
Adventure adventure;
adventure.begin();
return 0;
}
<commit_msg>Added dialogue to the new locations.<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
using namespace std;
vector<string> split(const string& str) {
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
using RoomID = int;
struct RoomObject
{
vector<string> names;
string description;
bool visible;
};
struct Map
{
static const int max_width = 100, max_height = 100;
static const int player_start_x = 50, player_start_y = 50;
enum Location
{
UNKNOWN,
GRAVEYARD,
GRAVEYARD_GATES,
KHATHARRS_MOMS_HOUSE,
GATES_OF_SHOGUN,
HOUSE_OF_BLUES,
FOGGY_FOREST
};
Location map_location[max_width][max_height];
int x, y;
Map()
{
memset(map_location, UNKNOWN, sizeof(map_location));
x = 50;
y = 50;
map_location[50][50] = GRAVEYARD;
map_location[50][51] = GRAVEYARD_GATES;
map_location[50][52] = KHATHARRS_MOMS_HOUSE;
map_location[50][52] = GATES_OF_SHOGUN;
map_location[50][53] = HOUSE_OF_BLUES;
map_location[50][54] = FOGGY_FOREST;
}
};
struct Entity
{
Entity(string name, int maxHealth) : name(name), health(maxHealth) {}
void heal(int points)
{
health = min(100, health + points);
cout << name << " healed to " << health << " health" << endl;
}
void damage(int points)
{
health = max(0, health - points);
cout << name << " damaged to " << health << "health" << endl;
}
int getHealth() const { return health; }
// Return false if the entity didn't know the command
virtual bool act(vector<string> commands) = 0;
string name;
Map map;
private:
int health;
};
struct Shogun : public Entity {
Shogun() : Entity("Shogibear", 100) {}
};
struct Item
{
virtual void apply(Entity* entity) = 0;
virtual string identify() const = 0;
};
struct HealthItem : public Item
{
HealthItem(int healPower) : healPower(healPower) {}
void apply(Entity* entity) override
{
entity->heal(healPower);
}
string identify() const override
{
stringstream ss;
ss << "Health Potion (" << healPower << ")";
return ss.str();
}
private:
int healPower;
};
struct BlessedSword : public Item
{
BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<
/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
TheFastcall() : Entity("The Fastcall", 22) {}
virtual bool act(vector<string> commands) override
{
}
};
*/
typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.
struct Player : public Entity
{
Player(string name, int health) : Entity(name, health) {}
virtual bool act(vector<string> commands) override
{
auto cmd = commands[0];
if(cmd == "n") { commands = vector<string>{"go","north"}; }
if(cmd == "s") { commands = vector<string>{"go","south"}; }
if(cmd == "e") { commands = vector<string>{"go","east"}; }
if(cmd == "w") { commands = vector<string>{"go","west"}; }
if (commands.size() >= 1 && commands[0] == "look")
{
look();
return true;
}
else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
{
}
else if (commands.size() >= 2 && commands[0] == "go")
{
if (travel(commands[1]) == true)
{
look();
} else {
cout << "Can't travel " << commands[1] << endl;
}
return true;
}
else if (commands.size() >= 1 && commands[0] == "items")
{
showItems();
return true;
}
else if (commands.size() >= 2 && commands[0] == "use")
{
int index = stoi(commands[1]);
useItem(index);
return true;
}
return false;
}
bool travel(string direction)
{
if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
return false;
if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
return false;
if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
return true;/*
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
if (direction == "north")
{
map.y++;
return true;
}
break;
case Map::GRAVEYARD_GATES:
if (direction == "south")
{
map.y--;
return true;
}
if (direction == "north")
{
map.y++;
return true;
}
break;
}
cout << "Can't travel " << direction << endl;
return false;*/
}
void look()
{
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
break;
case Map::GRAVEYARD_GATES:
cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
break;
case Map::KHATHARRS_MOMS_HOUSE:
cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
break;
case Map::GATES_OF_SHOGUN:
cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
break;
case Map::HOUSE_OF_BLUES:
cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
break;
case Map::FOGGY_FOREST:
cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
break;
}
}
void giveItem(shared_ptr<Item> item)
{
inventory.push_back(item);
}
void showItems()
{
if (inventory.size() == 0)
cout << "You have no items." << endl;
int i = 1;
for (auto item : inventory)
{
cout << " " << i++ << ". " << item->identify() << std::endl;
}
}
void useItem(size_t index)
{
if (index > inventory.size())
{
cout << "Invalid index" << endl;
return;
}
inventory[index-1]->apply(this);
inventory.erase(inventory.begin() + index - 1);
}
private:
vector<shared_ptr<Item>> inventory;
unordered_map<string, function<bool(vector<string>)>> actions;
};
struct Room {
string describe() {
stringstream ss;
ss << description << "\n";
ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n"; //make this look nice later
ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
return ss.str();
}
string description;
vector<unique_ptr<Entity>> entities;
vector<RoomObject> objects;
unordered_map<string, RoomID> exits;
};
class Adventure
{
public:
void begin()
{
string command;
cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
cout << "> ";
getline(cin, command);
Player player(command, 100);
player.giveItem(make_shared<HealthItem>(20));
cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
player.look();
while (player.getHealth() > 0)
{
cout << "> ";
getline(cin, command);
if (player.act(split(command)) == false)
cout << "Unknown command" << endl;
}
cout << "You died. Game over." << endl;
}
};
int main()
{
Adventure adventure;
adventure.begin();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Rohan McGovern <rohan@mcgovern.id.au>
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.
*/
#include <string>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include "shared.h"
#include "run.h"
#define OPTION_NOT (1<<16)
#define OPTION_FS_ALLOW 0x101
static const char optionstring[] = "+hd";
#define OPTION_BOOL(longopt, value) \
{ longopt, 0, 0, value }, \
{ "no-" longopt, 0, 0, value|OPTION_NOT }
static const struct option options[] = {
{ "help", 0, 0, 'h' },
{ "debug", 0, 0, 'd' },
{ "none", 0, 0, 'N' },
{ "fs-allow", 1, 0, OPTION_FS_ALLOW },
OPTION_BOOL("net", 'n'),
OPTION_BOOL("pid", 'p'),
OPTION_BOOL("ipc", 'i'),
OPTION_BOOL("mount", 'm'),
OPTION_BOOL("fs", 'f'),
{ 0, 0, 0, 0 }
};
void usage(FILE* stream, int exitcode)
{
fprintf(stream,
"Usage: rsandbox [options] [--] command [args]\n\n"
"Run a command in a sandbox.\n\n"
"Options:\n"
" --help, -h Show this message\n"
" --debug, -d Enable debugging messages\n"
"\n"
"Sandbox features:\n"
" All of the following sandbox features are enabled by default.\n"
" `--no-<feature>' disables a feature.\n"
"\n"
" --none\n"
" Disable all sandbox features.\n"
" May be followed by additional options to turn on selected features.\n"
"\n"
" --net, --no-net\n"
" Network isolation; prevents connections to any host (including\n"
" localhost). This includes Unix domain socket connections.\n"
"\n"
" --pid, --no-pid\n"
" PID isolation; prevents sending signals to any process outside of\n"
" the sandbox.\n"
"\n"
" --mount, --no-mount\n"
" Mount isolation; prevents mounting or unmounting any mounts outside\n"
" of the sandbox.\n"
"\n"
" --ipc, --no-ipc\n"
" IPC isolation; prevents access to any SysV IPC resources outside of\n"
" the sandbox.\n"
"\n"
" --fs, --no-fs\n"
" Filesystem isolation; prevents modification of files outside of the\n"
" sandbox.\n"
"\n"
"Filesystem options:\n"
"\n"
" --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n"
" Allow writes to the specified path(s).\n"
" <PATH> may contain a single relative or absolute path, or\n"
" several paths separated with the : character.\n"
);
exit(exitcode);
}
std::string realpath(std::string const& path)
{
char* resolved = realpath(path.c_str(), 0);
if (!resolved) {
fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(),
strerror(errno));
exit(4);
}
std::string out{resolved};
free(resolved);
return out;
}
void parse_fs_allow(Context* ctx, const char* arg)
{
int backslash = 0;
std::string current_arg;
while (*arg) {
if (backslash) {
current_arg.append(1, *arg);
backslash = 0;
} else if (*arg == '\\') {
backslash = 1;
} else if (*arg == ':') {
ctx->fuse_writable_paths.push_back(realpath(current_arg));
current_arg.clear();
} else {
current_arg.append(1, *arg);
}
++arg;
}
ctx->fuse_writable_paths.push_back(realpath(current_arg));
}
void parse_arguments(Context* ctx, int argc, char** argv)
{
int gotopt;
while ((gotopt = getopt_long(argc, argv,
optionstring, options, 0))) {
if (gotopt == -1) {
break;
}
debug("gotopt 0x%x\n", gotopt);
int enable = !(gotopt&OPTION_NOT);
gotopt &= 0xffff;
switch (gotopt) {
case 'h':
usage(stdout, 0);
case '?':
usage(stderr, 3);
case 'd':
++Global::debug_mode;
break;
case 'N':
ctx->netns = 0;
ctx->pidns = 0;
ctx->mountns = 0;
ctx->ipcns = 0;
ctx->fs = 0;
break;
case 'n':
ctx->netns = enable;
break;
case 'p':
ctx->pidns = enable;
break;
case 'i':
ctx->ipcns = enable;
break;
case 'm':
ctx->mountns = enable;
break;
case 'f':
ctx->fs = enable;
break;
case OPTION_FS_ALLOW:
parse_fs_allow(ctx, optarg);
break;
}
}
debug("optind %d\n", optind);
ctx->child_argv = &argv[optind];
if (!ctx->child_argv[0]) {
fprintf(stderr, "Not enough arguments\n");
usage(stderr, 3);
}
if (ctx->fs && !ctx->mountns) {
fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n"
"Try adding --mount to the rsandbox arguments.\n");
exit(3);
}
ctx->mount_proc = ctx->mountns && ctx->pidns;
/*
If using fuse and pidns, create a pid namespace and mount namespace
for the fuse layer only; this ensures the sandbox fuse process won't
be visible within the sandbox, and killing the top-level sandbox
process is guaranteed to kill the fuse process.
*/
ctx->clone_for_fuse = ctx->fs && ctx->pidns;
}
static char* mountpoint = 0;
void remove_mountpoint()
{
if (rmdir(mountpoint)) {
if (errno != ENOENT) {
fprintf(stderr, "warning: could not remove rsandbox fuse mount point %s: "
"%s\n", mountpoint, strerror(errno));
}
}
}
void setup_fuse_context(Context* ctx)
{
const char* tempdir = getenv("TMPDIR");
if (!tempdir) {
tempdir = "/tmp";
}
std::string tmpl(tempdir);
tmpl += "/rsandbox-fuse-XXXXXX";
char* c_mountpoint = strdup(tmpl.c_str());
if (!mkdtemp(c_mountpoint)) {
perror("Can't create mount point for FUSE");
exit(3);
}
ctx->fuse_mountpoint = c_mountpoint;
mountpoint = c_mountpoint;
atexit(remove_mountpoint);
}
int main(int argc, char** argv)
{
Context ctx = {
.netns = 1,
.pidns = 1,
.mountns = 1,
.ipcns = 1,
.fs = 1
};
parse_arguments(&ctx, argc, argv);
if (ctx.fs) {
setup_fuse_context(&ctx);
}
return run(&ctx);
}
<commit_msg>Avoid C99-style named initializers.<commit_after>/*
Copyright (c) 2012 Rohan McGovern <rohan@mcgovern.id.au>
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.
*/
#include <string>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include "shared.h"
#include "run.h"
#define OPTION_NOT (1<<16)
#define OPTION_FS_ALLOW 0x101
static const char optionstring[] = "+hd";
#define OPTION_BOOL(longopt, value) \
{ longopt, 0, 0, value }, \
{ "no-" longopt, 0, 0, value|OPTION_NOT }
static const struct option options[] = {
{ "help", 0, 0, 'h' },
{ "debug", 0, 0, 'd' },
{ "none", 0, 0, 'N' },
{ "fs-allow", 1, 0, OPTION_FS_ALLOW },
OPTION_BOOL("net", 'n'),
OPTION_BOOL("pid", 'p'),
OPTION_BOOL("ipc", 'i'),
OPTION_BOOL("mount", 'm'),
OPTION_BOOL("fs", 'f'),
{ 0, 0, 0, 0 }
};
void usage(FILE* stream, int exitcode)
{
fprintf(stream,
"Usage: rsandbox [options] [--] command [args]\n\n"
"Run a command in a sandbox.\n\n"
"Options:\n"
" --help, -h Show this message\n"
" --debug, -d Enable debugging messages\n"
"\n"
"Sandbox features:\n"
" All of the following sandbox features are enabled by default.\n"
" `--no-<feature>' disables a feature.\n"
"\n"
" --none\n"
" Disable all sandbox features.\n"
" May be followed by additional options to turn on selected features.\n"
"\n"
" --net, --no-net\n"
" Network isolation; prevents connections to any host (including\n"
" localhost). This includes Unix domain socket connections.\n"
"\n"
" --pid, --no-pid\n"
" PID isolation; prevents sending signals to any process outside of\n"
" the sandbox.\n"
"\n"
" --mount, --no-mount\n"
" Mount isolation; prevents mounting or unmounting any mounts outside\n"
" of the sandbox.\n"
"\n"
" --ipc, --no-ipc\n"
" IPC isolation; prevents access to any SysV IPC resources outside of\n"
" the sandbox.\n"
"\n"
" --fs, --no-fs\n"
" Filesystem isolation; prevents modification of files outside of the\n"
" sandbox.\n"
"\n"
"Filesystem options:\n"
"\n"
" --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n"
" Allow writes to the specified path(s).\n"
" <PATH> may contain a single relative or absolute path, or\n"
" several paths separated with the : character.\n"
);
exit(exitcode);
}
std::string realpath(std::string const& path)
{
char* resolved = realpath(path.c_str(), 0);
if (!resolved) {
fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(),
strerror(errno));
exit(4);
}
std::string out{resolved};
free(resolved);
return out;
}
void parse_fs_allow(Context* ctx, const char* arg)
{
int backslash = 0;
std::string current_arg;
while (*arg) {
if (backslash) {
current_arg.append(1, *arg);
backslash = 0;
} else if (*arg == '\\') {
backslash = 1;
} else if (*arg == ':') {
ctx->fuse_writable_paths.push_back(realpath(current_arg));
current_arg.clear();
} else {
current_arg.append(1, *arg);
}
++arg;
}
ctx->fuse_writable_paths.push_back(realpath(current_arg));
}
void parse_arguments(Context* ctx, int argc, char** argv)
{
int gotopt;
while ((gotopt = getopt_long(argc, argv,
optionstring, options, 0))) {
if (gotopt == -1) {
break;
}
debug("gotopt 0x%x\n", gotopt);
int enable = !(gotopt&OPTION_NOT);
gotopt &= 0xffff;
switch (gotopt) {
case 'h':
usage(stdout, 0);
case '?':
usage(stderr, 3);
case 'd':
++Global::debug_mode;
break;
case 'N':
ctx->netns = 0;
ctx->pidns = 0;
ctx->mountns = 0;
ctx->ipcns = 0;
ctx->fs = 0;
break;
case 'n':
ctx->netns = enable;
break;
case 'p':
ctx->pidns = enable;
break;
case 'i':
ctx->ipcns = enable;
break;
case 'm':
ctx->mountns = enable;
break;
case 'f':
ctx->fs = enable;
break;
case OPTION_FS_ALLOW:
parse_fs_allow(ctx, optarg);
break;
}
}
debug("optind %d\n", optind);
ctx->child_argv = &argv[optind];
if (!ctx->child_argv[0]) {
fprintf(stderr, "Not enough arguments\n");
usage(stderr, 3);
}
if (ctx->fs && !ctx->mountns) {
fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n"
"Try adding --mount to the rsandbox arguments.\n");
exit(3);
}
ctx->mount_proc = ctx->mountns && ctx->pidns;
/*
If using fuse and pidns, create a pid namespace and mount namespace
for the fuse layer only; this ensures the sandbox fuse process won't
be visible within the sandbox, and killing the top-level sandbox
process is guaranteed to kill the fuse process.
*/
ctx->clone_for_fuse = ctx->fs && ctx->pidns;
}
static char* mountpoint = 0;
void remove_mountpoint()
{
if (rmdir(mountpoint)) {
if (errno != ENOENT) {
fprintf(stderr, "warning: could not remove rsandbox fuse mount point %s: "
"%s\n", mountpoint, strerror(errno));
}
}
}
void setup_fuse_context(Context* ctx)
{
const char* tempdir = getenv("TMPDIR");
if (!tempdir) {
tempdir = "/tmp";
}
std::string tmpl(tempdir);
tmpl += "/rsandbox-fuse-XXXXXX";
char* c_mountpoint = strdup(tmpl.c_str());
if (!mkdtemp(c_mountpoint)) {
perror("Can't create mount point for FUSE");
exit(3);
}
ctx->fuse_mountpoint = c_mountpoint;
mountpoint = c_mountpoint;
atexit(remove_mountpoint);
}
int main(int argc, char** argv)
{
Context ctx;
ctx.netns = 1;
ctx.pidns = 1;
ctx.mountns = 1;
ctx.ipcns = 1;
ctx.fs = 1;
parse_arguments(&ctx, argc, argv);
if (ctx.fs) {
setup_fuse_context(&ctx);
}
return run(&ctx);
}
<|endoftext|> |
<commit_before>83000e73-2d15-11e5-af21-0401358ea401<commit_msg>83000e74-2d15-11e5-af21-0401358ea401<commit_after>83000e74-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d8d19d5e-4b02-11e5-a983-28cfe9171a43<commit_msg>Nope, didn't work, now it does<commit_after>d8ddd382-4b02-11e5-922b-28cfe9171a43<|endoftext|> |
<commit_before>a55d2a4c-327f-11e5-9dfa-9cf387a8033e<commit_msg>a563d091-327f-11e5-850f-9cf387a8033e<commit_after>a563d091-327f-11e5-850f-9cf387a8033e<|endoftext|> |
<commit_before>776c3d36-2d53-11e5-baeb-247703a38240<commit_msg>776cbb62-2d53-11e5-baeb-247703a38240<commit_after>776cbb62-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>75186240-2e4f-11e5-8999-28cfe91dbc4b<commit_msg>751f31ee-2e4f-11e5-bbb1-28cfe91dbc4b<commit_after>751f31ee-2e4f-11e5-bbb1-28cfe91dbc4b<|endoftext|> |
<commit_before>41fc197d-2748-11e6-a9cd-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>420853cf-2748-11e6-8c76-e0f84713e7b8<|endoftext|> |
<commit_before>/**
* Copyright 2017 Google Inc.
*
* 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 "config.h"
#include "build/buildjson.hpp"
#include "conf.hpp"
#include "dbus/dbusconfiguration.hpp"
#include "interfaces.hpp"
#include "pid/builder.hpp"
#include "pid/buildjson.hpp"
#include "pid/pidloop.hpp"
#include "pid/tuning.hpp"
#include "pid/zone.hpp"
#include "sensors/builder.hpp"
#include "sensors/buildjson.hpp"
#include "sensors/manager.hpp"
#include "util.hpp"
#include <CLI/CLI.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/manager.hpp>
#include <chrono>
#include <filesystem>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace pid_control
{
/* The configuration converted sensor list. */
std::map<std::string, conf::SensorConfig> sensorConfig = {};
/* The configuration converted PID list. */
std::map<int64_t, conf::PIDConf> zoneConfig = {};
/* The configuration converted Zone configuration. */
std::map<int64_t, conf::ZoneConfig> zoneDetailsConfig = {};
} // namespace pid_control
/** the swampd daemon will check for the existence of this file. */
constexpr auto jsonConfigurationPath = "/usr/share/swampd/config.json";
std::string configPath = "";
/* async io context for operation */
boost::asio::io_context io;
/* buses for system control */
static sdbusplus::asio::connection modeControlBus(io);
static sdbusplus::asio::connection
hostBus(io, sdbusplus::bus::new_system().release());
static sdbusplus::asio::connection
passiveBus(io, sdbusplus::bus::new_system().release());
namespace pid_control
{
void restartControlLoops()
{
static SensorManager mgmr;
static std::unordered_map<int64_t, std::shared_ptr<ZoneInterface>> zones;
static std::vector<std::shared_ptr<boost::asio::steady_timer>> timers;
static bool isCanceling = false;
for (const auto timer : timers)
{
timer->cancel();
}
isCanceling = true;
timers.clear();
if (zones.size() > 0 && zones.begin()->second.use_count() > 1)
{
throw std::runtime_error("wait for count back to 1");
}
zones.clear();
isCanceling = false;
const std::string& path =
(configPath.length() > 0) ? configPath : jsonConfigurationPath;
if (std::filesystem::exists(path))
{
/*
* When building the sensors, if any of the dbus passive ones aren't on
* the bus, it'll fail immediately.
*/
try
{
auto jsonData = parseValidateJson(path);
sensorConfig = buildSensorsFromJson(jsonData);
std::tie(zoneConfig, zoneDetailsConfig) =
buildPIDsFromJson(jsonData);
}
catch (const std::exception& e)
{
std::cerr << "Failed during building: " << e.what() << "\n";
exit(EXIT_FAILURE); /* fatal error. */
}
}
else
{
static boost::asio::steady_timer reloadTimer(io);
if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig,
zoneConfig, zoneDetailsConfig))
{
return; // configuration not ready
}
}
mgmr = buildSensors(sensorConfig, passiveBus, hostBus);
zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus);
if (0 == zones.size())
{
std::cerr << "No zones defined, exiting.\n";
std::exit(EXIT_FAILURE);
}
for (const auto& i : zones)
{
std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back(
std::make_shared<boost::asio::steady_timer>(io));
std::cerr << "pushing zone " << i.first << "\n";
pidControlLoop(i.second, timer, &isCanceling);
}
}
void tryRestartControlLoops(bool first)
{
static int count = 0;
static const auto delayTime = std::chrono::seconds(10);
static boost::asio::steady_timer timer(io);
// try to start a control loop while the loop has been scheduled.
if (first && count != 0)
{
std::cerr
<< "ControlLoops has been scheduled, refresh the loop count\n";
count = 1;
return;
}
auto restartLbd = [](const boost::system::error_code& error) {
if (error == boost::asio::error::operation_aborted)
{
return;
}
// for the last loop, don't elminate the failure of restartControlLoops.
if (count >= 5)
{
restartControlLoops();
// reset count after succesful restartControlLoops()
count = 0;
return;
}
// retry when restartControlLoops() has some failure.
try
{
restartControlLoops();
// reset count after succesful restartControlLoops()
count = 0;
}
catch (const std::exception& e)
{
std::cerr << count
<< " Failed during restartControlLoops, try again: "
<< e.what() << "\n";
tryRestartControlLoops(false);
}
};
count++;
// first time of trying to restart the control loop without a delay
if (first)
{
boost::asio::post(io,
std::bind(restartLbd, boost::system::error_code()));
}
// re-try control loop, set up a delay.
else
{
timer.expires_after(delayTime);
timer.async_wait(restartLbd);
}
return;
}
} // namespace pid_control
int main(int argc, char* argv[])
{
loggingPath = "";
loggingEnabled = false;
tuningEnabled = false;
CLI::App app{"OpenBMC Fan Control Daemon"};
app.add_option("-c,--conf", configPath,
"Optional parameter to specify configuration at run-time")
->check(CLI::ExistingFile);
app.add_option("-l,--log", loggingPath,
"Optional parameter to specify logging folder")
->check(CLI::ExistingDirectory);
app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
CLI11_PARSE(app, argc, argv);
static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
// If this file exists, enable logging at runtime
std::ifstream fsLogging(loggingEnablePath);
if (fsLogging)
{
// Unless file contents are a valid directory path, use system default
std::getline(fsLogging, loggingPath);
if (!(std::filesystem::exists(loggingPath)))
{
loggingPath = std::filesystem::temp_directory_path();
}
fsLogging.close();
loggingEnabled = true;
std::cerr << "Logging enabled: " << loggingPath << "\n";
}
// If this file exists, enable tuning at runtime
if (std::filesystem::exists(tuningEnablePath))
{
tuningEnabled = true;
std::cerr << "Tuning enabled\n";
}
static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
// Create a manager for the ModeBus because we own it.
sdbusplus::server::manager::manager(
static_cast<sdbusplus::bus::bus&>(modeControlBus), modeRoot);
hostBus.request_name("xyz.openbmc_project.Hwmon.external");
modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
sdbusplus::server::manager::manager objManager(modeControlBus, modeRoot);
/*
* All sensors are managed by one manager, but each zone has a pointer to
* it.
*/
pid_control::tryRestartControlLoops();
io.run();
return 0;
}
<commit_msg>Fix command-line parsing of loggingPath<commit_after>/**
* Copyright 2017 Google Inc.
*
* 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 "config.h"
#include "build/buildjson.hpp"
#include "conf.hpp"
#include "dbus/dbusconfiguration.hpp"
#include "interfaces.hpp"
#include "pid/builder.hpp"
#include "pid/buildjson.hpp"
#include "pid/pidloop.hpp"
#include "pid/tuning.hpp"
#include "pid/zone.hpp"
#include "sensors/builder.hpp"
#include "sensors/buildjson.hpp"
#include "sensors/manager.hpp"
#include "util.hpp"
#include <CLI/CLI.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/manager.hpp>
#include <chrono>
#include <filesystem>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace pid_control
{
/* The configuration converted sensor list. */
std::map<std::string, conf::SensorConfig> sensorConfig = {};
/* The configuration converted PID list. */
std::map<int64_t, conf::PIDConf> zoneConfig = {};
/* The configuration converted Zone configuration. */
std::map<int64_t, conf::ZoneConfig> zoneDetailsConfig = {};
} // namespace pid_control
/** the swampd daemon will check for the existence of this file. */
constexpr auto jsonConfigurationPath = "/usr/share/swampd/config.json";
std::string configPath = "";
/* async io context for operation */
boost::asio::io_context io;
/* buses for system control */
static sdbusplus::asio::connection modeControlBus(io);
static sdbusplus::asio::connection
hostBus(io, sdbusplus::bus::new_system().release());
static sdbusplus::asio::connection
passiveBus(io, sdbusplus::bus::new_system().release());
namespace pid_control
{
void restartControlLoops()
{
static SensorManager mgmr;
static std::unordered_map<int64_t, std::shared_ptr<ZoneInterface>> zones;
static std::vector<std::shared_ptr<boost::asio::steady_timer>> timers;
static bool isCanceling = false;
for (const auto timer : timers)
{
timer->cancel();
}
isCanceling = true;
timers.clear();
if (zones.size() > 0 && zones.begin()->second.use_count() > 1)
{
throw std::runtime_error("wait for count back to 1");
}
zones.clear();
isCanceling = false;
const std::string& path =
(configPath.length() > 0) ? configPath : jsonConfigurationPath;
if (std::filesystem::exists(path))
{
/*
* When building the sensors, if any of the dbus passive ones aren't on
* the bus, it'll fail immediately.
*/
try
{
auto jsonData = parseValidateJson(path);
sensorConfig = buildSensorsFromJson(jsonData);
std::tie(zoneConfig, zoneDetailsConfig) =
buildPIDsFromJson(jsonData);
}
catch (const std::exception& e)
{
std::cerr << "Failed during building: " << e.what() << "\n";
exit(EXIT_FAILURE); /* fatal error. */
}
}
else
{
static boost::asio::steady_timer reloadTimer(io);
if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig,
zoneConfig, zoneDetailsConfig))
{
return; // configuration not ready
}
}
mgmr = buildSensors(sensorConfig, passiveBus, hostBus);
zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus);
if (0 == zones.size())
{
std::cerr << "No zones defined, exiting.\n";
std::exit(EXIT_FAILURE);
}
for (const auto& i : zones)
{
std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back(
std::make_shared<boost::asio::steady_timer>(io));
std::cerr << "pushing zone " << i.first << "\n";
pidControlLoop(i.second, timer, &isCanceling);
}
}
void tryRestartControlLoops(bool first)
{
static int count = 0;
static const auto delayTime = std::chrono::seconds(10);
static boost::asio::steady_timer timer(io);
// try to start a control loop while the loop has been scheduled.
if (first && count != 0)
{
std::cerr
<< "ControlLoops has been scheduled, refresh the loop count\n";
count = 1;
return;
}
auto restartLbd = [](const boost::system::error_code& error) {
if (error == boost::asio::error::operation_aborted)
{
return;
}
// for the last loop, don't elminate the failure of restartControlLoops.
if (count >= 5)
{
restartControlLoops();
// reset count after succesful restartControlLoops()
count = 0;
return;
}
// retry when restartControlLoops() has some failure.
try
{
restartControlLoops();
// reset count after succesful restartControlLoops()
count = 0;
}
catch (const std::exception& e)
{
std::cerr << count
<< " Failed during restartControlLoops, try again: "
<< e.what() << "\n";
tryRestartControlLoops(false);
}
};
count++;
// first time of trying to restart the control loop without a delay
if (first)
{
boost::asio::post(io,
std::bind(restartLbd, boost::system::error_code()));
}
// re-try control loop, set up a delay.
else
{
timer.expires_after(delayTime);
timer.async_wait(restartLbd);
}
return;
}
} // namespace pid_control
int main(int argc, char* argv[])
{
loggingPath = "";
loggingEnabled = false;
tuningEnabled = false;
CLI::App app{"OpenBMC Fan Control Daemon"};
app.add_option("-c,--conf", configPath,
"Optional parameter to specify configuration at run-time")
->check(CLI::ExistingFile);
app.add_option("-l,--log", loggingPath,
"Optional parameter to specify logging folder")
->check(CLI::ExistingDirectory);
app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
CLI11_PARSE(app, argc, argv);
static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
// Set up default logging path, preferring command line if it was given
std::string defLoggingPath(loggingPath);
if (defLoggingPath.empty())
{
defLoggingPath = std::filesystem::temp_directory_path();
}
else
{
// Enable logging, if user explicitly gave path on command line
loggingEnabled = true;
}
// If this file exists, enable logging at runtime
std::ifstream fsLogging(loggingEnablePath);
if (fsLogging)
{
// The first line of file might be a valid directory path
std::getline(fsLogging, loggingPath);
fsLogging.close();
// If so, use it, otherwise use default logging path instead
if (!(std::filesystem::exists(loggingPath)))
{
loggingPath = defLoggingPath;
}
loggingEnabled = true;
}
if (loggingEnabled)
{
std::cerr << "Logging enabled: " << loggingPath << "\n";
}
// If this file exists, enable tuning at runtime
if (std::filesystem::exists(tuningEnablePath))
{
tuningEnabled = true;
}
// This can also be enabled from the command line
if (tuningEnabled)
{
std::cerr << "Tuning enabled\n";
}
static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
// Create a manager for the ModeBus because we own it.
sdbusplus::server::manager::manager(
static_cast<sdbusplus::bus::bus&>(modeControlBus), modeRoot);
hostBus.request_name("xyz.openbmc_project.Hwmon.external");
modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
sdbusplus::server::manager::manager objManager(modeControlBus, modeRoot);
/*
* All sensors are managed by one manager, but each zone has a pointer to
* it.
*/
pid_control::tryRestartControlLoops();
io.run();
return 0;
}
<|endoftext|> |
<commit_before>b7f57254-327f-11e5-9589-9cf387a8033e<commit_msg>b7fc09f3-327f-11e5-bec0-9cf387a8033e<commit_after>b7fc09f3-327f-11e5-bec0-9cf387a8033e<|endoftext|> |
<commit_before>/*
* main.cpp
*
* Created on: Oct 13, 2017
* Author: austinhoffmann
*/
#include <iostream>
#include <unordered_map>
#include "./rapidXML/rapidxml_utils.hpp"
#include "./rapidXML/rapidxml.hpp"
#include "Object.h"
#include "Room.h"
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Zork usage: ./Zork [filename]" << std::endl;
return 0;
}
//create a c-string that will be parsed by rapidxml using the input file
rapidxml::file<>ifile(argv[1]);
//create a DOM model of the input file that is parsed
rapidxml::xml_document<> doc;
doc.parse<0>(ifile.data());
//create an unordered map to store all of our Room objects
std::unordered_map<std::string, Room::Room> roomMap;
//Map node is the first child of the XML overall tree
rapidxml::xml_node<>* mapNode = doc.first_node("map");
rapidxml::xml_node<>* node = mapNode->first_node("room");
if(node == nullptr) {
std::cout << "Could not find a valid room with the XML parser" <<std::endl;
return 0;
}
//keep creating rooms while we have new ones
while(node) {
//create Room
Room::Room room(node);
//Add room to unordered map
roomMap.insert(std::make_pair(room.get_name(), room));
//Get next room node
node = node->next_sibling("room");
}
//END OF SETUP
//START OF GAMEPLAY
//Find the Entrance to start the game
auto search = roomMap.find("Entrance");
auto currentRoom = search->second;
std::cout << currentRoom.get_description() << std::endl;
while(1) {
//Get user input
std::string input;
std::getline(std::cin, input);
currentRoom = currentRoom.movement(input, roomMap);
}
return 0;
}
<commit_msg>Minor fix from Room::Room to Room for object creation<commit_after>/*
* main.cpp
*
* Created on: Oct 13, 2017
* Author: austinhoffmann
*/
#include <iostream>
#include <unordered_map>
#include "./rapidXML/rapidxml_utils.hpp"
#include "./rapidXML/rapidxml.hpp"
#include "Object.h"
#include "Room.h"
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Zork usage: ./Zork [filename]" << std::endl;
return 0;
}
//create a c-string that will be parsed by rapidxml using the input file
rapidxml::file<>ifile(argv[1]);
//create a DOM model of the input file that is parsed
rapidxml::xml_document<> doc;
doc.parse<0>(ifile.data());
//create an unordered map to store all of our Room objects
std::unordered_map<std::string, Room> roomMap;
//Map node is the first child of the XML overall tree
rapidxml::xml_node<>* mapNode = doc.first_node("map");
rapidxml::xml_node<>* node = mapNode->first_node("room");
if(node == nullptr) {
std::cout << "Could not find a valid room with the XML parser" <<std::endl;
return 0;
}
//keep creating rooms while we have new ones
while(node) {
//create Room
Room room(node);
//Add room to unordered map
roomMap.insert(std::make_pair(room.get_name(), room));
//Get next room node
node = node->next_sibling("room");
}
//END OF SETUP
//START OF GAMEPLAY
//Find the Entrance to start the game
auto search = roomMap.find("Entrance");
auto currentRoom = search->second;
std::cout << currentRoom.get_description() << std::endl;
while(1) {
//Get user input
std::string input;
std::getline(std::cin, input);
currentRoom = currentRoom.movement(input, roomMap);
}
return 0;
}
<|endoftext|> |
<commit_before>c15af06e-327f-11e5-afd9-9cf387a8033e<commit_msg>c161949e-327f-11e5-9f04-9cf387a8033e<commit_after>c161949e-327f-11e5-9f04-9cf387a8033e<|endoftext|> |
<commit_before>9ca3f114-35ca-11e5-aa3c-6c40088e03e4<commit_msg>9caab170-35ca-11e5-b04a-6c40088e03e4<commit_after>9caab170-35ca-11e5-b04a-6c40088e03e4<|endoftext|> |
<commit_before>4966af12-2e3a-11e5-9f71-c03896053bdd<commit_msg>49744618-2e3a-11e5-b28a-c03896053bdd<commit_after>49744618-2e3a-11e5-b28a-c03896053bdd<|endoftext|> |
<commit_before>d0b18cfd-ad5b-11e7-9cbf-ac87a332f658<commit_msg>Adding stuff<commit_after>d18d168c-ad5b-11e7-bea1-ac87a332f658<|endoftext|> |
<commit_before>94fddfe1-2e4f-11e5-bb88-28cfe91dbc4b<commit_msg>9505063d-2e4f-11e5-9924-28cfe91dbc4b<commit_after>9505063d-2e4f-11e5-9924-28cfe91dbc4b<|endoftext|> |
<commit_before>c9480c63-2d3c-11e5-a76f-c82a142b6f9b<commit_msg>c999d7a3-2d3c-11e5-829a-c82a142b6f9b<commit_after>c999d7a3-2d3c-11e5-829a-c82a142b6f9b<|endoftext|> |
<commit_before>a9a5511e-2e4f-11e5-a5b6-28cfe91dbc4b<commit_msg>a9ac2cd1-2e4f-11e5-b42a-28cfe91dbc4b<commit_after>a9ac2cd1-2e4f-11e5-b42a-28cfe91dbc4b<|endoftext|> |
<commit_before>8f0a500a-ad5c-11e7-8388-ac87a332f658<commit_msg>Did ANOTHER thing<commit_after>8f8e900c-ad5c-11e7-8212-ac87a332f658<|endoftext|> |
<commit_before>d60d0f70-2e4e-11e5-a46d-28cfe91dbc4b<commit_msg>d614fd8f-2e4e-11e5-a29e-28cfe91dbc4b<commit_after>d614fd8f-2e4e-11e5-a29e-28cfe91dbc4b<|endoftext|> |
<commit_before>b5d217e1-2e4f-11e5-8067-28cfe91dbc4b<commit_msg>b5daa519-2e4f-11e5-a98b-28cfe91dbc4b<commit_after>b5daa519-2e4f-11e5-a98b-28cfe91dbc4b<|endoftext|> |
<commit_before>c3c23797-ad59-11e7-b721-ac87a332f658<commit_msg>roselyn broke it<commit_after>c45adb87-ad59-11e7-ba49-ac87a332f658<|endoftext|> |
<commit_before>6ccaf42e-2e4f-11e5-bb2f-28cfe91dbc4b<commit_msg>6cd1d37a-2e4f-11e5-b6fb-28cfe91dbc4b<commit_after>6cd1d37a-2e4f-11e5-b6fb-28cfe91dbc4b<|endoftext|> |
<commit_before>8e9c8535-2e4f-11e5-90d9-28cfe91dbc4b<commit_msg>8ea3b5f3-2e4f-11e5-8b9a-28cfe91dbc4b<commit_after>8ea3b5f3-2e4f-11e5-8b9a-28cfe91dbc4b<|endoftext|> |
<commit_before>bf8f2745-4b02-11e5-8cf5-28cfe9171a43<commit_msg>Introduced random NullPointerException bug<commit_after>bf9a5df0-4b02-11e5-b932-28cfe9171a43<|endoftext|> |
<commit_before>3c6d18f8-5216-11e5-9b1f-6c40088e03e4<commit_msg>3c73a342-5216-11e5-b632-6c40088e03e4<commit_after>3c73a342-5216-11e5-b632-6c40088e03e4<|endoftext|> |
<commit_before>#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/Core/Replacement.h>
#include <TypeMatchers.h>
#include <iostream>
#include <set>
std::string extractMethodCall(const std::string& literal)
{
std::string result = literal;
if (!result.empty())
{
result.erase(result.begin(), result.begin() + 1);
auto parenPos = result.find('(');
result = result.substr(0, parenPos);
}
return result;
}
void getExpressionsRecursive(const clang::Stmt* expr, std::vector<const clang::Stmt*>& children)
{
for (const auto& child : expr->children())
{
getExpressionsRecursive(child, children);
children.push_back(child);
}
}
using namespace clang;
class FindNamedClassVisitor
: public RecursiveASTVisitor<FindNamedClassVisitor> {
public:
explicit FindNamedClassVisitor(ASTContext *Context)
: Context(Context), _rewriter(Context->getSourceManager(), Context->getLangOpts()) {}
bool VisitCXXMethodDecl(CXXMethodDecl* declaration)
{
auto methodName = declaration->getAsFunction()->getNameInfo().getAsString();
auto className = declaration->getParent()->getNameAsString();
if (methodName == "connect"
&& className == "QObject"
&& declaration->getAccess() == AccessSpecifier::AS_public
&& declaration->getNumParams() >= 3)
{
bool isFirstCorrect = isQObjectPtrType(declaration->getParamDecl(0));
bool isSecondCorrect = isConstCharPtrType(declaration->getParamDecl(1));
if (isFirstCorrect && isSecondCorrect)
{
llvm::errs() << "Found " << className << "::" << methodName << "( ";
llvm::errs() << declaration->getParamDecl(0)->getType().getAsString();
for (int i=1 ; i < declaration->getNumParams() ; i++)
{
llvm::errs() << ", " << declaration->getParamDecl(i)->getType().getAsString();
}
llvm::errs() << ")";
auto fullLocation = Context->getFullLoc(declaration->getLocStart());
llvm::errs() << " at " << fullLocation.getSpellingLineNumber();
llvm::errs() << ":" << fullLocation.getSpellingColumnNumber();
llvm::errs() << " in file" << fullLocation.getFileEntry()->getName() << "\n";
myset.insert(declaration);
}
}
return true;
}
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *callExpression)
{
// llvm::errs() << callExpression->getDirectCallee()->getAsFunction()->getDeclName() << "\n";
// if (callExpression->getDirectCallee()->getNameInfo().getName().getAsString() == "connect"
// && callExpression->getDecl()->getParent()->isClass()
// && callExpression->getDecl()->getParent()->getNameAsString() == "QObject")
// {
// FullSourceLoc FullLocation = Context->getFullLoc(callExpression->getLocStart());
// if (FullLocation.isValid())
// llvm::errs() << "Found declaration at "
// << FullLocation.getSpellingLineNumber() << ":"
// << FullLocation.getSpellingColumnNumber() << " in file "
// << FullLocation.getFileEntry()->getName() << "\n";
// }
return true;
}
bool VisitCallExpr(CallExpr *callExpression)
{
std::string methodCall, lastTypeString;
if (callExpression->getDirectCallee())
{
if (myset.find(callExpression->getDirectCallee()->getFirstDecl()) != myset.end())
{
for (int i = 0 ; i < callExpression->getNumArgs() ; i++)
{
if (const CallExpr *qflaglocationCall = dyn_cast<CallExpr>(callExpression->getArg(i)))
{
if (const ImplicitCastExpr *castExpr = dyn_cast<ImplicitCastExpr>(qflaglocationCall->getArg(0)))
{
if (const StringLiteral* literal = dyn_cast<StringLiteral>(*castExpr->child_begin()))
{
methodCall = extractMethodCall(literal->getBytes());
}
}
}
if (callExpression->getArg(i)->getLocEnd().isValid())
{
auto& sm = Context->getSourceManager();
if (callExpression->getArg(i)->getLocStart().isMacroID())
{
llvm::errs() << "Matching call argument " << i << " ";
auto fullStartLocation = Context->getSourceManager().getImmediateExpansionRange(callExpression->getArg(i)->getLocStart());
llvm::errs() << fullStartLocation.first.printToString(sm);
llvm::errs() << " to ";
llvm::errs() << fullStartLocation.second.printToString(sm);
llvm::errs() << "\n";
std::string replacementText = "&";
replacementText += lastTypeString;
replacementText += "::";
replacementText += methodCall;
_rewriter.ReplaceText(SourceRange(fullStartLocation.first, fullStartLocation.second), replacementText);
methodCall.clear();
}
}
QualType argumentType;
if (const ImplicitCastExpr* castExpr = dyn_cast<ImplicitCastExpr>(callExpression->getArg(i)))
{
if (const Expr* expr = dyn_cast<Expr>(*castExpr->child_begin()))
{
argumentType = expr->getType();
}
}
else
{
argumentType = callExpression->getArg(i)->getType();
}
if (argumentType.getTypePtr()->isPointerType())
{
argumentType = argumentType.getTypePtr()->getPointeeType();
}
argumentType.removeLocalConst();
clang::PrintingPolicy policy(Context->getLangOpts());
policy.SuppressUnwrittenScope = 1;
policy.TerseOutput = 1;
policy.PolishForDeclaration = 1;
lastTypeString.clear();
argumentType.getAsStringInternal(lastTypeString, policy);
if (!lastTypeString.empty())
{
llvm::errs() << "Type string for parameter " << i << " is " << lastTypeString << "\n";
}
}
}
}
return true;
}
void dumpToOutputStream()
{
_rewriter.getEditBuffer(Context->getSourceManager().getMainFileID()).write(llvm::outs());
}
private:
ASTContext *Context;
std::set <void*> myset;
Rewriter _rewriter;
std::vector<clang::tooling::Replacement> replacements;
};
class FindNamedClassConsumer : public clang::ASTConsumer {
public:
explicit FindNamedClassConsumer(ASTContext *Context)
: Visitor(Context) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context) {
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
Visitor.dumpToOutputStream();
}
private:
FindNamedClassVisitor Visitor;
};
class FindNamedClassAction : public clang::ASTFrontendAction {
public:
virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
return std::unique_ptr<clang::ASTConsumer>(
new FindNamedClassConsumer(&Compiler.getASTContext()));
}
};
static llvm::cl::OptionCategory MyToolCategory("my-tool options");
int main(int argc, const char **argv) {
const std::string fName = "doSomething";
tooling::CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
tooling::ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
// run the Clang Tool, creating a new FrontendAction (explained below)
int result = Tool.run(clang::tooling::newFrontendActionFactory<FindNamedClassAction>().get());
return result;
}
<commit_msg>Remove unused functions<commit_after>#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/Core/Replacement.h>
#include <TypeMatchers.h>
#include <iostream>
#include <set>
std::string extractMethodCall(const std::string& literal)
{
std::string result = literal;
if (!result.empty())
{
result.erase(result.begin(), result.begin() + 1);
auto parenPos = result.find('(');
result = result.substr(0, parenPos);
}
return result;
}
using namespace clang;
class FindNamedClassVisitor
: public RecursiveASTVisitor<FindNamedClassVisitor> {
public:
explicit FindNamedClassVisitor(ASTContext *Context)
: Context(Context), _rewriter(Context->getSourceManager(), Context->getLangOpts()) {}
bool VisitCXXMethodDecl(CXXMethodDecl* declaration)
{
auto methodName = declaration->getAsFunction()->getNameInfo().getAsString();
auto className = declaration->getParent()->getNameAsString();
if (methodName == "connect"
&& className == "QObject"
&& declaration->getAccess() == AccessSpecifier::AS_public
&& declaration->getNumParams() >= 3)
{
bool isFirstCorrect = isQObjectPtrType(declaration->getParamDecl(0));
bool isSecondCorrect = isConstCharPtrType(declaration->getParamDecl(1));
if (isFirstCorrect && isSecondCorrect)
{
llvm::errs() << "Found " << className << "::" << methodName << "( ";
llvm::errs() << declaration->getParamDecl(0)->getType().getAsString();
for (int i=1 ; i < declaration->getNumParams() ; i++)
{
llvm::errs() << ", " << declaration->getParamDecl(i)->getType().getAsString();
}
llvm::errs() << ")";
auto fullLocation = Context->getFullLoc(declaration->getLocStart());
llvm::errs() << " at " << fullLocation.getSpellingLineNumber();
llvm::errs() << ":" << fullLocation.getSpellingColumnNumber();
llvm::errs() << " in file" << fullLocation.getFileEntry()->getName() << "\n";
myset.insert(declaration);
}
}
return true;
}
bool VisitCallExpr(CallExpr *callExpression)
{
std::string methodCall, lastTypeString;
if (callExpression->getDirectCallee())
{
if (myset.find(callExpression->getDirectCallee()->getFirstDecl()) != myset.end())
{
for (int i = 0 ; i < callExpression->getNumArgs() ; i++)
{
if (const CallExpr *qflaglocationCall = dyn_cast<CallExpr>(callExpression->getArg(i)))
{
if (const ImplicitCastExpr *castExpr = dyn_cast<ImplicitCastExpr>(qflaglocationCall->getArg(0)))
{
if (const StringLiteral* literal = dyn_cast<StringLiteral>(*castExpr->child_begin()))
{
methodCall = extractMethodCall(literal->getBytes());
}
}
}
if (callExpression->getArg(i)->getLocEnd().isValid())
{
auto& sm = Context->getSourceManager();
if (callExpression->getArg(i)->getLocStart().isMacroID())
{
llvm::errs() << "Matching call argument " << i << " ";
auto fullStartLocation = Context->getSourceManager().getImmediateExpansionRange(callExpression->getArg(i)->getLocStart());
llvm::errs() << fullStartLocation.first.printToString(sm);
llvm::errs() << " to ";
llvm::errs() << fullStartLocation.second.printToString(sm);
llvm::errs() << "\n";
std::string replacementText = "&";
replacementText += lastTypeString;
replacementText += "::";
replacementText += methodCall;
_rewriter.ReplaceText(SourceRange(fullStartLocation.first, fullStartLocation.second), replacementText);
methodCall.clear();
}
}
QualType argumentType;
if (const ImplicitCastExpr* castExpr = dyn_cast<ImplicitCastExpr>(callExpression->getArg(i)))
{
if (const Expr* expr = dyn_cast<Expr>(*castExpr->child_begin()))
{
argumentType = expr->getType();
}
}
else
{
argumentType = callExpression->getArg(i)->getType();
}
if (argumentType.getTypePtr()->isPointerType())
{
argumentType = argumentType.getTypePtr()->getPointeeType();
}
argumentType.removeLocalConst();
clang::PrintingPolicy policy(Context->getLangOpts());
policy.SuppressUnwrittenScope = 1;
policy.TerseOutput = 1;
policy.PolishForDeclaration = 1;
policy.SuppressScope = 1;
lastTypeString.clear();
argumentType.getAsStringInternal(lastTypeString, policy);
if (!lastTypeString.empty())
{
llvm::errs() << "Type string for parameter " << i << " is " << lastTypeString << "\n";
}
}
}
}
return true;
}
void dumpToOutputStream()
{
_rewriter.getEditBuffer(Context->getSourceManager().getMainFileID()).write(llvm::outs());
}
private:
ASTContext *Context;
std::set <void*> myset;
Rewriter _rewriter;
std::vector<clang::tooling::Replacement> replacements;
};
class FindNamedClassConsumer : public clang::ASTConsumer {
public:
explicit FindNamedClassConsumer(ASTContext *Context)
: Visitor(Context) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context) {
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
Visitor.dumpToOutputStream();
}
private:
FindNamedClassVisitor Visitor;
};
class FindNamedClassAction : public clang::ASTFrontendAction {
public:
virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
return std::unique_ptr<clang::ASTConsumer>(
new FindNamedClassConsumer(&Compiler.getASTContext()));
}
};
static llvm::cl::OptionCategory MyToolCategory("my-tool options");
int main(int argc, const char **argv) {
const std::string fName = "doSomething";
tooling::CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
tooling::ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
// run the Clang Tool, creating a new FrontendAction (explained below)
int result = Tool.run(clang::tooling::newFrontendActionFactory<FindNamedClassAction>().get());
return result;
}
<|endoftext|> |
<commit_before>6d9e52f4-2fa5-11e5-89f5-00012e3d3f12<commit_msg>6da027b6-2fa5-11e5-b0a4-00012e3d3f12<commit_after>6da027b6-2fa5-11e5-b0a4-00012e3d3f12<|endoftext|> |
<commit_before>982f9fdc-327f-11e5-a311-9cf387a8033e<commit_msg>983588fd-327f-11e5-a7c4-9cf387a8033e<commit_after>983588fd-327f-11e5-a7c4-9cf387a8033e<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <ctime>
#include <unistd.h>
int main(int argc, char **argv) {
/**
* This should not all be in the main function but I'm just trying to get
* a POC out the door for now.
*/
int i;
char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t* descr;
const u_char *packet;
struct pcap_pkthdr hdr;
struct ether_header *eptr;
u_char *ptr;
dev = pcap_lookupdev(errbuf);
if (getuid()) {
printf("%s", "Arper must be run as root.\n");
exit(1);
}
if(dev == NULL) {
printf("%s\n", errbuf);
exit(1);
}
printf("Capturing on device: %s\n", dev);
descr = pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);
if(descr == NULL) {
printf("pcap_open_live(): %s\n", errbuf);
exit(1);
}
packet = pcap_next(descr,&hdr);
if(packet == NULL) {
printf("Didn't grab packet\n");
exit(1);
}
printf("Grabbed packet of length %d\n", hdr.len);
printf("Recieved at ..... %s\n", ctime((const time_t*)&hdr.ts.tv_sec));
printf("Ethernet address length is %d\n", ETHER_HDR_LEN);
eptr = (struct ether_header *) packet;
if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
printf("Ethernet type hex:%x dec:%d is an IP packet\n",
ntohs(eptr->ether_type),
ntohs(eptr->ether_type));
}
else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) {
printf("Ethernet type hex:%x dec:%d is an ARP packet\n",
ntohs(eptr->ether_type),
ntohs(eptr->ether_type));
}
else {
printf("Ethernet type %x not IP", ntohs(eptr->ether_type));
exit(1);
}
ptr = eptr->ether_dhost;
i = ETHER_ADDR_LEN;
printf(" Destination Address: ");
do {
printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
}
while(--i>0);
printf("\n");
ptr = eptr->ether_shost;
i = ETHER_ADDR_LEN;
printf("Source Address: ");
do{
printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
}
while(--i>0);
printf("\n");
return 0;
}
<commit_msg>Nopeeee<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <pcap/pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <ctime>
#include <unistd.h>
int main(int argc, char **argv) {
/**
* This should not all be in the main function but I'm just trying to get
* a POC out the door for now.
*/
int i;
char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t* descr;
const u_char *packet;
struct pcap_pkthdr hdr;
struct ether_header *eptr;
u_char *ptr;
dev = pcap_lookupdev(errbuf);
if (getuid()) {
printf("%s", "Arper must be run as root.\n");
exit(1);
}
if(dev == NULL) {
printf("%s\n", errbuf);
exit(1);
}
printf("Capturing on device: %s\n", dev);
descr = pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);
if(descr == NULL) {
printf("pcap_open_live(): %s\n", errbuf);
exit(1);
}
packet = pcap_next(descr,&hdr);
if(packet == NULL) {
printf("Didn't grab packet\n");
exit(1);
}
printf("Grabbed packet of length %d\n", hdr.len);
printf("Recieved at ..... %s\n", ctime((const time_t*)&hdr.ts.tv_sec));
printf("Ethernet address length is %d\n", ETHER_HDR_LEN);
eptr = (struct ether_header *) packet;
if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
printf("Ethernet type hex:%x dec:%d is an IP packet\n",
ntohs(eptr->ether_type),
ntohs(eptr->ether_type));
}
else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) {
printf("Ethernet type hex:%x dec:%d is an ARP packet\n",
ntohs(eptr->ether_type),
ntohs(eptr->ether_type));
}
else {
printf("Ethernet type %x not IP", ntohs(eptr->ether_type));
exit(1);
}
ptr = eptr->ether_dhost;
i = ETHER_ADDR_LEN;
printf(" Destination Address: ");
do {
printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
}
while(--i>0);
printf("\n");
ptr = eptr->ether_shost;
i = ETHER_ADDR_LEN;
printf("Source Address: ");
do{
printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
}
while(--i>0);
printf("\n");
return 0;
}
<|endoftext|> |
<commit_before>5d28656b-2d16-11e5-af21-0401358ea401<commit_msg>5d28656c-2d16-11e5-af21-0401358ea401<commit_after>5d28656c-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include "main.h"
blaze::CompressedMatrix<double> D_T_blaze, M_invD_blaze;
blaze::DynamicVector<double> gamma_blaze, rhs_blaze;
int num_rows;
int num_cols;
int num_nonzeros;
int RUNS = 100;
vex::profiler<> prof;
double blaze_time;
double eigen_time;
double vexcl_time;
template <typename Matrix, typename Vector>
void TEST(Matrix& D_T, Matrix& M_invD, Vector& gamma, Vector& temporary, Vector& result) {
for (size_t i = 0; i < RUNS; i++) {
temporary = M_invD * gamma;
result += D_T * temporary;
}
}
void Blaze_TEST() {
blaze::DynamicVector<double> temporary(num_rows);
blaze::DynamicVector<double> result(num_rows);
prof.tic_cpu("Blaze");
TEST(D_T_blaze, M_invD_blaze, gamma_blaze, temporary, result);
blaze_time = prof.toc("Blaze");
}
void VexCL_TEST() {
vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
std::cout << ctx;
std::vector<size_t> row, col;
std::vector<double> val;
ConvertSparse(D_T_blaze, row, col, val);
vex::SpMat<double> D_T_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());
ConvertSparse(M_invD_blaze, row, col, val);
vex::SpMat<double> M_invD_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());
std::vector<double> gamma_temp(num_rows);
for (int i = 0; i < num_rows; i++) {
gamma_temp[i] = gamma_blaze[i];
}
vex::vector<double> gamma_vex(ctx, num_rows);
vex::copy(gamma_temp, gamma_vex);
vex::vector<double> temporary(ctx, num_rows);
vex::vector<double> result(ctx, num_rows);
temporary += M_invD_vex * gamma_vex;
temporary = 0;
result += D_T_vex * temporary;
result = 0;
prof.tic_cpu("VexCL");
TEST(D_T_vex, M_invD_vex, gamma_vex, temporary, result);
ctx.finish();
vexcl_time = prof.toc("VexCL");
// std::cout << vexcl_time << std::endl;
}
//
// void Eigen_TEST() {
//
// Eigen::SparseMatrix<double> M_invD_eigen(num_cols, num_rows);
// Eigen::SparseMatrix<double> D_T_eigen(num_rows, num_cols);
//
// std::vector<Eigen::Triplet<double> > triplet;
// ConvertSparse(D_T_blaze, triplet);
// D_T_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
// ConvertSparse(M_invD_blaze, triplet);
// M_invD_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
// Eigen::AMDOrdering<int> ordering;
// Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> perm;
//
// ordering(D_T_eigen, perm);
// ordering(M_invD_eigen, perm);
//
// Eigen::VectorXd gamma_eigen(num_rows);
// Eigen::VectorXd temporary(num_rows);
// Eigen::VectorXd result(num_rows);
//
// for (int i = 0; i < num_rows; i++) {
// gamma_eigen[i] = gamma_blaze[i];
// }
// prof.tic_cpu("EIGEN");
// TEST(D_T_eigen, M_invD_eigen, gamma_eigen, temporary, result);
// eigen_time = prof.toc("EIGEN");
//}
int main(int argc, char* argv[]) {
if (argc > 2) {
RUNS = atoi(argv[2]);
}
FillSparseMatrix("D_T_" + std::string(argv[1]) + ".dat", D_T_blaze);
FillSparseMatrix("M_invD_" + std::string(argv[1]) + ".dat", M_invD_blaze);
FillVector("gamma_" + std::string(argv[1]) + ".dat", gamma_blaze);
FillVector("b_" + std::string(argv[1]) + ".dat", rhs_blaze);
num_rows = D_T_blaze.rows();
num_cols = D_T_blaze.columns();
num_nonzeros = D_T_blaze.nonZeros();
printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: \n");
printf("%d, %d, %d, %d, %d, %d, %d, %d \n",
D_T_blaze.rows(),
D_T_blaze.columns(),
D_T_blaze.nonZeros(),
M_invD_blaze.rows(),
M_invD_blaze.columns(),
M_invD_blaze.nonZeros(),
gamma_blaze.size(),
rhs_blaze.size());
// printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// printf("gamma: size: %d\n", gamma_blaze.size());
// printf("b: size: %d\n", rhs_blaze.size());
Blaze_TEST();
// Eigen_TEST();
VexCL_TEST();
// Two Spmv each with 2*nnz operations
uint operations = 2 * 2 * num_nonzeros;
uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
double blaze_single = blaze_time / RUNS;
double vex_single = vexcl_time / RUNS;
double eig_single = eigen_time / RUNS;
double GFLOP = 1000000000;
printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
printf("%f, %f, %f, %f, %f, %f, %f\n",
blaze_single,
vex_single,
blaze_single / vex_single,
operations / blaze_single / GFLOP,
operations / vex_single / GFLOP,
moved / blaze_single / GFLOP,
moved / vex_single / GFLOP);
// printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
//
// printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<commit_msg>cleanup the VexCL code a bit<commit_after>#include "main.h"
blaze::CompressedMatrix<double> D_T_blaze, M_invD_blaze;
blaze::DynamicVector<double> gamma_blaze, rhs_blaze;
int num_rows;
int num_cols;
int num_nonzeros;
int RUNS = 100;
vex::profiler<> prof;
double blaze_time;
double eigen_time;
double vexcl_time;
template <typename Matrix, typename Vector>
void TEST(Matrix& D_T, Matrix& M_invD, Vector& gamma, Vector& temporary, Vector& result) {
for (size_t i = 0; i < RUNS; i++) {
temporary = M_invD * gamma;
result = D_T * temporary;
}
}
void Blaze_TEST() {
blaze::DynamicVector<double> temporary(num_rows);
blaze::DynamicVector<double> result(num_rows);
prof.tic_cpu("Blaze");
TEST(D_T_blaze, M_invD_blaze, gamma_blaze, temporary, result);
blaze_time = prof.toc("Blaze");
}
void VexCL_TEST() {
vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
std::cout << ctx;
std::vector<size_t> row, col;
std::vector<double> val;
ConvertSparse(D_T_blaze, row, col, val);
vex::SpMat<double> D_T_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());
ConvertSparse(M_invD_blaze, row, col, val);
vex::SpMat<double> M_invD_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());
std::vector<double> gamma_temp(num_rows);
for (int i = 0; i < num_rows; i++) {
gamma_temp[i] = gamma_blaze[i];
}
vex::vector<double> gamma_vex(ctx, num_rows);
vex::vector<double> temporary(ctx, num_rows);
vex::vector<double> result(ctx, num_rows);
vex::copy(gamma_temp, gamma_vex);
temporary = M_invD_vex * gamma_vex;
temporary = 0;
result = D_T_vex * temporary;
result = 0;
prof.tic_cpu("VexCL");
TEST(D_T_vex, M_invD_vex, gamma_vex, temporary, result);
ctx.finish();
vexcl_time = prof.toc("VexCL");
// std::cout << vexcl_time << std::endl;
}
//
// void Eigen_TEST() {
//
// Eigen::SparseMatrix<double> M_invD_eigen(num_cols, num_rows);
// Eigen::SparseMatrix<double> D_T_eigen(num_rows, num_cols);
//
// std::vector<Eigen::Triplet<double> > triplet;
// ConvertSparse(D_T_blaze, triplet);
// D_T_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
// ConvertSparse(M_invD_blaze, triplet);
// M_invD_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
// Eigen::AMDOrdering<int> ordering;
// Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> perm;
//
// ordering(D_T_eigen, perm);
// ordering(M_invD_eigen, perm);
//
// Eigen::VectorXd gamma_eigen(num_rows);
// Eigen::VectorXd temporary(num_rows);
// Eigen::VectorXd result(num_rows);
//
// for (int i = 0; i < num_rows; i++) {
// gamma_eigen[i] = gamma_blaze[i];
// }
// prof.tic_cpu("EIGEN");
// TEST(D_T_eigen, M_invD_eigen, gamma_eigen, temporary, result);
// eigen_time = prof.toc("EIGEN");
//}
int main(int argc, char* argv[]) {
if (argc > 2) {
RUNS = atoi(argv[2]);
}
FillSparseMatrix("D_T_" + std::string(argv[1]) + ".dat", D_T_blaze);
FillSparseMatrix("M_invD_" + std::string(argv[1]) + ".dat", M_invD_blaze);
FillVector("gamma_" + std::string(argv[1]) + ".dat", gamma_blaze);
FillVector("b_" + std::string(argv[1]) + ".dat", rhs_blaze);
num_rows = D_T_blaze.rows();
num_cols = D_T_blaze.columns();
num_nonzeros = D_T_blaze.nonZeros();
printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: \n");
printf("%d, %d, %d, %d, %d, %d, %d, %d \n",
D_T_blaze.rows(),
D_T_blaze.columns(),
D_T_blaze.nonZeros(),
M_invD_blaze.rows(),
M_invD_blaze.columns(),
M_invD_blaze.nonZeros(),
gamma_blaze.size(),
rhs_blaze.size());
// printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// printf("gamma: size: %d\n", gamma_blaze.size());
// printf("b: size: %d\n", rhs_blaze.size());
Blaze_TEST();
// Eigen_TEST();
VexCL_TEST();
// Two Spmv each with 2*nnz operations
uint operations = 2 * 2 * num_nonzeros;
uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
double blaze_single = blaze_time / RUNS;
double vex_single = vexcl_time / RUNS;
double eig_single = eigen_time / RUNS;
double GFLOP = 1000000000;
printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
printf("%f, %f, %f, %f, %f, %f, %f\n",
blaze_single,
vex_single,
blaze_single / vex_single,
operations / blaze_single / GFLOP,
operations / vex_single / GFLOP,
moved / blaze_single / GFLOP,
moved / vex_single / GFLOP);
// printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
//
// printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<|endoftext|> |
<commit_before>2f4ed23e-2f67-11e5-ad70-6c40088e03e4<commit_msg>2f55338c-2f67-11e5-97da-6c40088e03e4<commit_after>2f55338c-2f67-11e5-97da-6c40088e03e4<|endoftext|> |
<commit_before>8811d5a3-2e4f-11e5-b201-28cfe91dbc4b<commit_msg>881a0a1c-2e4f-11e5-b57d-28cfe91dbc4b<commit_after>881a0a1c-2e4f-11e5-b57d-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include "Base.h"
#include "Command.h"
#include "Processes.h"
#include "Sentinel.h"
#include "Andand.h"
#include "Oror.h"
using namespace std;
int main(int argc, char **argv)
{
return 0;
}<commit_msg>adding while loop<commit_after>#include <iostream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include "Base.h"
#include "Command.h"
#include "Processes.h"
#include "Sentinel.h"
#include "Andand.h"
#include "Oror.h"
using namespace std;
int main()
{
string input;
cout << "$ ";
getline(cin, input);
while(input != "exit")
{
}
return 0;
}<|endoftext|> |
<commit_before>66b777b0-2e4f-11e5-aed2-28cfe91dbc4b<commit_msg>66be3259-2e4f-11e5-9350-28cfe91dbc4b<commit_after>66be3259-2e4f-11e5-9350-28cfe91dbc4b<|endoftext|> |
<commit_before>b9101091-327f-11e5-bfea-9cf387a8033e<commit_msg>b915ea6b-327f-11e5-8ae8-9cf387a8033e<commit_after>b915ea6b-327f-11e5-8ae8-9cf387a8033e<|endoftext|> |
<commit_before>e681cc70-2d3c-11e5-acca-c82a142b6f9b<commit_msg>e7028180-2d3c-11e5-b71a-c82a142b6f9b<commit_after>e7028180-2d3c-11e5-b71a-c82a142b6f9b<|endoftext|> |
<commit_before>952f1d5a-35ca-11e5-a986-6c40088e03e4<commit_msg>95358c58-35ca-11e5-9955-6c40088e03e4<commit_after>95358c58-35ca-11e5-9955-6c40088e03e4<|endoftext|> |
<commit_before>#include "CollisionsExample.h"
#include "../EventManager.h"
#include "../DrawUtils.h"
#include "../Math/ofDraw.h"
using namespace math;
math::Vector3D CollisionsExample::getElementColor(const ColliderWrapper& wrapper) {
return wrapper.selected ? Vector3D(255, 255, 255) :(
wrapper.contains ? Vector3D(125, 125, 125) :(
wrapper.intersects ? Vector3D(0, 255, 0) : wrapper.defaultColor));
}
void CollisionsExample::setSelected(int id) {
for (auto i = 0; i < wrappers.size(); i++) {
wrappers[i].selected = wrappers[i].id == id;
if (wrappers[i].selected) currentSelected = &wrappers[i];
}
}
void CollisionsExample::drawElement(const ColliderWrapper& tmp) const
{
auto aabbDraw = make_shared<ofAABB_DrawHelper>();
auto bcDraw = make_shared<ofBC_DrawHelper>();
cg::setColor(getElementColor(tmp));
if (tmp.boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp.mathElement);
elem->draw(aabbDraw);
//cg::drawBox(elem->p + elem->s / 2, elem->s);
}
else if (tmp.boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp.mathElement);
elem->draw(bcDraw);
//cg::drawCircle(elem->p, elem->radius);
}
}
//TODO: Ugly code. Another better solution would be plan some kind of inheritance in AABB and BoundingBox to make polymorphism
void CollisionsExample::testIntersects(ColliderWrapper& wrapper)
{
auto c1 = wrapper.boxOrCircle == 1 ?
static_cast<AABB*>(wrapper.mathElement) :
nullptr;
auto c2 = wrapper.boxOrCircle == 2 ?
static_cast<BoundingCircle*>(wrapper.mathElement) :
nullptr;
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
if (tmp->id == wrapper.id) continue;
if (tmp->boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp->mathElement);
if ((c1 != nullptr && elem->contains(*c1)) || (c2 != nullptr && elem->contains(*c2))) {
tmp->contains = true;
return;
}
if ((c1 != nullptr && elem->intersects(*c1)) || (c2 != nullptr && elem->intersects(*c2))) {
wrapper.intersects = true;
return;
}
} else if (tmp->boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp->mathElement);
if ((c1 != nullptr && elem->contains(*c1)) || (c2 != nullptr && elem->contains(*c2))) {
tmp->contains = true;
return;
}
if ((c1 != nullptr && elem->intersects(*c1)) || (c2 != nullptr && elem->intersects(*c2))) {
wrapper.intersects = true;
return;
}
}
}
}
CollisionsExample::CollisionsExample(): currentSelected(nullptr) {
}
void CollisionsExample::init()
{
wrappers[0].mathElement = &boxRed;
wrappers[0].id = 0;
wrappers[0].defaultColor = Vector3D(255, 0, 0);
wrappers[0].boxOrCircle = 1;
wrappers[0].position.set(200, 200);
wrappers[0].size = 100;
boxRed.position.set(wrappers[0].position);
boxRed.size.set(wrappers[0].size, wrappers[0].size);
wrappers[1].mathElement = &boxBlue;
wrappers[1].id = 1;
wrappers[1].defaultColor = Vector3D(0, 0, 255);
wrappers[1].boxOrCircle = 1;
wrappers[1].position.set(600, 500);
wrappers[1].size = 100;
boxBlue.position.set(wrappers[1].position);
boxBlue.size.set(wrappers[1].size, wrappers[1].size);
wrappers[2].mathElement = &circleYellow;
wrappers[2].id = 2;
wrappers[2].defaultColor = Vector3D(255, 255, 0);
wrappers[2].boxOrCircle = 2;
wrappers[2].position.set(200, 500);
wrappers[2].size = 80;
circleYellow.position.set(wrappers[2].position);
circleYellow.radius = wrappers[2].size;
wrappers[3].mathElement = &circleCyan;
wrappers[3].id = 3;
wrappers[3].defaultColor = Vector3D(0, 255, 255);
wrappers[3].boxOrCircle = 2;
wrappers[3].position.set(600, 200);
wrappers[3].size = 80;
circleCyan.position.set(wrappers[3].position);
circleCyan.radius = wrappers[3].size;
currentSelected = &wrappers[0];
}
void CollisionsExample::update()
{
mouse = Vector2D(ofGetMouseX(), ofGetHeight() - ofGetMouseY())
- (currentSelected->boxOrCircle == 1 ? Vector2D(currentSelected->size, currentSelected->size) / 2 : Vector2D());
setSelected(EventManager::getLastKeyPressed() - '0' - 1);
currentSelected->selected = true; //Workaround for the first selection (without input)
currentSelected->position = mouse;
if (KEY(OF_KEY_UP)) currentSelected->size += 60 * ofGetLastFrameTime();
if (KEY(OF_KEY_DOWN)) currentSelected->size -= 60 * ofGetLastFrameTime();
//Next step will check everything again, so I need to reset collisions from previous frame
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
tmp->intersects = false;
tmp->contains = false;
}
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
testIntersects(*tmp);
cg::setColor(getElementColor(*tmp));
if (tmp->boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp->mathElement);
elem->position = tmp->position;
elem->size.set(tmp->size, tmp->size);
} else if (tmp->boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp->mathElement);
elem->position = tmp->position;
elem->radius = tmp->size;
}
}
}
void CollisionsExample::draw()
{
for(auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
if(tmp->selected) continue;
drawElement(*tmp);
}
drawElement(*currentSelected);
//Look for the inner and outer boxes and circles
//AABB::innerBoxFromCircle(circleYellow).draw(make_shared<ofAABB_DrawHelper>());
//AABB::outerBoxFromCircle(circleYellow).draw(make_shared<ofAABB_DrawHelper>());
BoundingCircle::innerCircleFromBox(boxRed).draw(make_shared<ofBC_DrawHelper>());
BoundingCircle::outerCircleFromBox(boxRed).draw(make_shared<ofBC_DrawHelper>());
}
void CollisionsExample::close()
{
}
IScreen* CollisionsExample::nextScreen()
{
return this;
}
CollisionsExample::~CollisionsExample()
{
}<commit_msg>Minor changes<commit_after>#include "CollisionsExample.h"
#include "../EventManager.h"
#include "../DrawUtils.h"
#include "../Math/ofDraw.h"
using namespace math;
math::Vector3D CollisionsExample::getElementColor(const ColliderWrapper& wrapper) {
return wrapper.selected ? Vector3D(255, 255, 255) :(
wrapper.contains ? Vector3D(125, 125, 125) :(
wrapper.intersects ? Vector3D(0, 255, 0) : wrapper.defaultColor));
}
void CollisionsExample::setSelected(int id) {
for (auto i = 0; i < wrappers.size(); i++) {
wrappers[i].selected = wrappers[i].id == id;
if (wrappers[i].selected) currentSelected = &wrappers[i];
}
}
void CollisionsExample::drawElement(const ColliderWrapper& tmp) const
{
auto aabbDraw = make_shared<ofAABB_DrawHelper>();
auto bcDraw = make_shared<ofBC_DrawHelper>();
cg::setColor(getElementColor(tmp));
if (tmp.boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp.mathElement);
elem->draw(aabbDraw);
cg::drawBox(elem->p + elem->s / 2, elem->s);
}
else if (tmp.boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp.mathElement);
elem->draw(bcDraw);
cg::drawCircle(elem->p, elem->radius);
}
}
//TODO: Ugly code. Another better solution would be plan some kind of inheritance in AABB and BoundingBox to make polymorphism
void CollisionsExample::testIntersects(ColliderWrapper& wrapper)
{
auto c1 = wrapper.boxOrCircle == 1 ?
static_cast<AABB*>(wrapper.mathElement) :
nullptr;
auto c2 = wrapper.boxOrCircle == 2 ?
static_cast<BoundingCircle*>(wrapper.mathElement) :
nullptr;
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
if (tmp->id == wrapper.id) continue;
if (tmp->boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp->mathElement);
if ((c1 != nullptr && elem->contains(*c1)) || (c2 != nullptr && elem->contains(*c2))) {
tmp->contains = true;
return;
}
if ((c1 != nullptr && elem->intersects(*c1)) || (c2 != nullptr && elem->intersects(*c2))) {
wrapper.intersects = true;
return;
}
} else if (tmp->boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp->mathElement);
if ((c1 != nullptr && elem->contains(*c1)) || (c2 != nullptr && elem->contains(*c2))) {
tmp->contains = true;
return;
}
if ((c1 != nullptr && elem->intersects(*c1)) || (c2 != nullptr && elem->intersects(*c2))) {
wrapper.intersects = true;
return;
}
}
}
}
CollisionsExample::CollisionsExample(): currentSelected(nullptr) {
}
void CollisionsExample::init()
{
wrappers[0].mathElement = &boxRed;
wrappers[0].id = 0;
wrappers[0].defaultColor = Vector3D(255, 0, 0);
wrappers[0].boxOrCircle = 1;
wrappers[0].position.set(200, 200);
wrappers[0].size = 100;
boxRed.position.set(wrappers[0].position);
boxRed.size.set(wrappers[0].size, wrappers[0].size);
wrappers[1].mathElement = &boxBlue;
wrappers[1].id = 1;
wrappers[1].defaultColor = Vector3D(0, 0, 255);
wrappers[1].boxOrCircle = 1;
wrappers[1].position.set(600, 500);
wrappers[1].size = 100;
boxBlue.position.set(wrappers[1].position);
boxBlue.size.set(wrappers[1].size, wrappers[1].size);
wrappers[2].mathElement = &circleYellow;
wrappers[2].id = 2;
wrappers[2].defaultColor = Vector3D(255, 255, 0);
wrappers[2].boxOrCircle = 2;
wrappers[2].position.set(200, 500);
wrappers[2].size = 80;
circleYellow.position.set(wrappers[2].position);
circleYellow.radius = wrappers[2].size;
wrappers[3].mathElement = &circleCyan;
wrappers[3].id = 3;
wrappers[3].defaultColor = Vector3D(0, 255, 255);
wrappers[3].boxOrCircle = 2;
wrappers[3].position.set(600, 200);
wrappers[3].size = 80;
circleCyan.position.set(wrappers[3].position);
circleCyan.radius = wrappers[3].size;
currentSelected = &wrappers[0];
}
void CollisionsExample::update()
{
mouse = Vector2D(ofGetMouseX(), ofGetHeight() - ofGetMouseY())
- (currentSelected->boxOrCircle == 1 ? Vector2D(currentSelected->size, currentSelected->size) / 2 : Vector2D());
setSelected(EventManager::getLastKeyPressed() - '0' - 1);
currentSelected->selected = true; //Workaround for the first selection (without input)
currentSelected->position = mouse;
if (KEY(OF_KEY_UP)) currentSelected->size += 60 * ofGetLastFrameTime();
if (KEY(OF_KEY_DOWN)) currentSelected->size -= 60 * ofGetLastFrameTime();
//Next step will check everything again, so I need to reset collisions from previous frame
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
tmp->intersects = false;
tmp->contains = false;
}
for (auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
testIntersects(*tmp);
cg::setColor(getElementColor(*tmp));
if (tmp->boxOrCircle == 1) {
auto elem = static_cast<AABB*>(tmp->mathElement);
elem->position = tmp->position;
elem->size.set(tmp->size, tmp->size);
} else if (tmp->boxOrCircle == 2) {
auto elem = static_cast<BoundingCircle*>(tmp->mathElement);
elem->position = tmp->position;
elem->radius = tmp->size;
}
}
}
void CollisionsExample::draw()
{
for(auto i = 0; i < wrappers.size(); i++) {
auto tmp = &wrappers[i];
if(tmp->selected) continue;
drawElement(*tmp);
}
drawElement(*currentSelected);
//Look for the inner and outer boxes and circles
//AABB::innerBoxFromCircle(circleYellow).draw(make_shared<ofAABB_DrawHelper>());
//AABB::outerBoxFromCircle(circleYellow).draw(make_shared<ofAABB_DrawHelper>());
//BoundingCircle::innerCircleFromBox(boxRed).draw(make_shared<ofBC_DrawHelper>());
//BoundingCircle::outerCircleFromBox(boxRed).draw(make_shared<ofBC_DrawHelper>());
}
void CollisionsExample::close()
{
}
IScreen* CollisionsExample::nextScreen()
{
return this;
}
CollisionsExample::~CollisionsExample()
{
}<|endoftext|> |
<commit_before>21e9cbc7-2d3d-11e5-addb-c82a142b6f9b<commit_msg>225b54a1-2d3d-11e5-a4f3-c82a142b6f9b<commit_after>225b54a1-2d3d-11e5-a4f3-c82a142b6f9b<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <fstream>
#include "RJObject.h"
#include "RandomNumberGenerator.h"
#include "Distributions/ClassicMassInf.h"
using namespace DNest3;
using namespace std;
// Demonstration of the MCMC
int main()
{
// Initialise DNest3's random number generator
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
RJObject<ClassicMassInf> r1(3, 100, false, ClassicMassInf(-1., 1., -1., 1., 1E-3, 1E3));
RJObject<ClassicMassInf> r2(3, 100, false, ClassicMassInf(-1., 1., -1., 1., 1E-3, 1E3));
fstream fout("output.txt", ios::out);
for(int i=0; i<1000; i++)
{
r2 = r1;
double logH = r2.perturb();
if(randomU() <= exp(logH))
r1 = r2;
r1.print(fout);
fout<<endl;
cout<<(i+1)<<endl;
}
fout.close();
return 0;
}
<commit_msg>Initialise from the prior<commit_after>#include <ctime>
#include <iostream>
#include <fstream>
#include "RJObject.h"
#include "RandomNumberGenerator.h"
#include "Distributions/ClassicMassInf.h"
using namespace DNest3;
using namespace std;
// Demonstration of the MCMC
int main()
{
// Initialise DNest3's random number generator
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
RJObject<ClassicMassInf> r1(3, 100, false, ClassicMassInf(-1., 1., -1., 1., 1E-3, 1E3));
RJObject<ClassicMassInf> r2(3, 100, false, ClassicMassInf(-1., 1., -1., 1., 1E-3, 1E3));
r1.fromPrior();
fstream fout("output.txt", ios::out);
for(int i=0; i<1000; i++)
{
r2 = r1;
double logH = r2.perturb();
if(randomU() <= exp(logH))
r1 = r2;
r1.print(fout);
fout<<endl;
cout<<(i+1)<<endl;
}
fout.close();
return 0;
}
<|endoftext|> |
<commit_before>8fd0494b-2d14-11e5-af21-0401358ea401<commit_msg>8fd0494c-2d14-11e5-af21-0401358ea401<commit_after>8fd0494c-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f52198ae-ad5b-11e7-afec-ac87a332f658<commit_msg>I'm done<commit_after>f58e1b47-ad5b-11e7-823b-ac87a332f658<|endoftext|> |
<commit_before>//============================================================================
// Name : main.cpp
// Author : Kadir Yasar
// Version :
// Copyright : MIT License
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <fstream>
#include <ctype.h>
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <list>
#include <cmath>
#include "StrInfo.h"
#include "StrTime.h"
using namespace std;
#define SRT_FILE_NAME_LEN 256
#define ESC_BTN 27
const std::string WHITESPACE = " \n\r\t";
static StrTime movie_time;
int counter = 0, lines_printed = 0;
std::list<StrInfo*> strInfoList;
std::list<StrInfo*>::iterator iter;
struct itimerval timer;
struct sigaction sa;
int totalPrinted = 0;
bool currPrinted = false;
int executed = 0;
int movie_end_time = 0;
void movie_player(int);
bool timerStopped = false;
/*
* Movie timer pause/play methods
*/
void pauseMovie(void)
{
timer.it_value.tv_usec = 0;
timer.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &timer, NULL);
timerStopped = true;
}
void continueMovie()
{
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &movie_player;
sigaction (SIGALRM, &sa, NULL); // POSIX signal
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 1000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 1000;
setitimer (ITIMER_REAL, &timer, NULL);
timerStopped = false;
}
void togglePlaying(void)
{
if (timerStopped) continueMovie();
else pauseMovie();
}
void clearLatestLinesOnScreen()
{
for (int i = 0; i < lines_printed; i++) {
move(14 + i, 0);
clrtoeol();
}
lines_printed = 0;
}
/*
* This method is invoked when fast forward or backward operation is needed
* It finds the next subtitle entry on the list according to updated movie time
*/
void findNextSubtitle(int way)
{
currPrinted = false;
clearLatestLinesOnScreen();
/*
* FORWARD
*/
if (way) {
while (movie_time.cmpTime((*iter)->endTime) > 0) {
if (iter != --strInfoList.end()) {
iter++;
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
} else
break;
}
}
/*
* BACKWARD
*/
else {
while (movie_time.cmpTime((*iter)->startTime) < 0) {
if (iter != strInfoList.begin()) {
iter--;
if (movie_time.cmpTime((*iter)->endTime) >= 0) {
iter++;
break;
}
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
}
else
break;
}
}
}
/*
* This function is actual player function
* It is invoked by POSIX ALARM interrupt in every milliseconds
* Responsible for showing or removing subtitle sentences according to movie time
* on the Ncurses screen
*/
void movie_player(int sig)
{
/*
* We reach the end of the subtitle list?
* If yes, stop the movie time
*/
if (iter == strInfoList.end()) {
pauseMovie();
return;
}
movie_time.incMillisecs();
mvprintw(9, 10, "Movie Time: %s", movie_time.getPrintableTime().c_str());
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
refresh();
/*
* Start time for the current subtitle sentences ?
*/
if (!currPrinted && movie_time.betweenTimes((*iter)->startTime, (*iter)->endTime))
{
mvprintw(12, 10, "%d %s --> %s", (*iter)->number, (*iter)->startTime.getPrintableTime().c_str(), (*iter)->endTime.getPrintableTime().c_str());
lines_printed = 0;
for (std::list<std::string>::iterator li = (*iter)->lines.begin(); li != (*iter)->lines.end(); li++, lines_printed++) {
mvprintw(14 + lines_printed, 10, "%s", (*li).c_str());
}
refresh();
/*
* This subtitle entry is shown, do not process it again
*/
currPrinted = true;
totalPrinted++;
}
/*
* Deadline of the current subtitle sentences ?
*/
else if (currPrinted && movie_time.cmpTime((*iter)->endTime) >= 0)
{
/*
* Remove the sentences on the screen, they are expired
*/
clearLatestLinesOnScreen();
/*
* Skip to next subtitle entry
*/
iter++;
currPrinted = false;
}
}
/*
* Some string functions to trim empty lines
*/
std::string TrimLeft(const std::string& s)
{
size_t startpos = s.find_first_not_of(WHITESPACE);
return (startpos == std::string::npos) ? "" : s.substr(startpos);
}
std::string TrimRight(const std::string& s)
{
size_t endpos = s.find_last_not_of(WHITESPACE);
return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
}
std::string Trim(const std::string& s)
{
return TrimRight(TrimLeft(s));
}
bool isEmptyLine(string strInput)
{
if (Trim(strInput).compare("") != 0)
return false;
else
return true;
}
std::string readLineFromFile(ifstream* fd_srt)
{
std::string line;
getline(*fd_srt, line);
return line;
}
/*
* This function process given Subtitle file
* Creates a list of subtitle entries in the file
*/
void processSrtFile(char* srt_file)
{
ifstream fd_srt;
std::string strLine;
int vals[8];
fd_srt.open(srt_file);
if (!fd_srt)
{
cout << "Cannot open Subtitle file: " << srt_file << endl;
exit(EXIT_FAILURE);
}
// While there's still stuff left to read
while (fd_srt)
{
// read stuff from the file into a string and print it
strLine = readLineFromFile(&fd_srt);
if (!isEmptyLine(strLine))
{
// Create an Entry object to keep the number times and sentences
StrInfo* strInfo = new StrInfo();
strInfo->number = atoi(strLine.c_str()); // Gets the entry number
strLine = readLineFromFile(&fd_srt);
// Gets the start and end times
sscanf(strLine.c_str(), "%u:%u:%u,%u --> %u:%u:%u,%u",
&vals[0], &vals[1], &vals[2], &vals[3],
&vals[4], &vals[5], &vals[6], &vals[7]);
strInfo->startTime.setTime(vals[0], vals[1], vals[2], vals[3]);
strInfo->endTime.setTime(vals[4], vals[5], vals[6], vals[7]);
// Gets sentences for current entry
strLine = readLineFromFile(&fd_srt);
while (!isEmptyLine(strLine)) {
strInfo->lines.insert(strInfo->lines.end(), strLine);
strLine = readLineFromFile(&fd_srt);
}
// Store current entry in the list of all entries
strInfoList.insert(strInfoList.end(), strInfo);
}
}
// Print all entries read. Just for debug
/*for (std::list<StrInfo*>::iterator it = strInfoList.begin(); it != strInfoList.end(); it++)
{
cout << (*it)->number << " " << (*it)->startTime.getPrintableTime() << " --> " << (*it)->endTime.getPrintableTime() << endl;
cout << (*it)->number << " " << (*it)->startTime.timeInMsec << " --> " << (*it)->endTime.timeInMsec << endl;
cout << (*it)->number << " " << (*it)->startTime.getPrintableTime() << " --> " << (*it)->endTime.getPrintableTime() << endl;
for (std::list<std::string>::iterator li = (*it)->lines.begin(); li != (*it)->lines.end(); li++) {
cout << (*li) << endl;
}
cout << endl;
} */
/*
* Keep the end time of the subtitle for boundary control
*/
iter = strInfoList.end();
movie_end_time = (*--iter)->endTime.timeInMsec;
/*
* Current player iterator on the first entry of the list
* Srt File is completely processed and all entries are stored in an arraylist
* Now, we are ready to play
*/
iter = strInfoList.begin();
}
void usage()
{
cout << "Welcome to KSP (Kadir's just Subtitle Player)" << endl << endl;
cout << "\t Usage:" << endl << "\t ===================" << endl;
cout << "\t -h \t\t\t: Help" << endl;
cout << "\t -f <srt-file> \t\t: SRT formatted subtitle file" << endl;
cout << "\t -s <milliseconds> \t: Fast forward/backward speed on left/right buttons" << endl << endl;
}
int main(int argc, char *argv[]) {
WINDOW * mainwin;
int ch, ch_prev = 0, speed = 0;
char srt_file[SRT_FILE_NAME_LEN] = {0};
while ( (ch = getopt(argc, argv, "f:s:h") ) != -1)
{
switch (ch)
{
case 'f':
snprintf(srt_file, SRT_FILE_NAME_LEN, "%s", optarg);
cout << "SRT file: " << srt_file << endl;
break;
case 's':
speed = atoi(optarg);
cout << "FF FB speed: " << speed << endl;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
fprintf(stderr, "Unrecognized option!\n");
break;
}
}
// Check file
if (!strcmp(srt_file, ""))
{
cout << "No Subtitle file given !!" << srt_file << endl;
usage();
exit(EXIT_FAILURE);
}
/*
* No need for return value
*/
processSrtFile(srt_file);
/* Initialize ncurses */
if ((mainwin = initscr()) == NULL ) {
fprintf(stderr, "Error initializing ncurses.\n");
exit(EXIT_FAILURE);
}
noecho(); /* Turn off key echoing */
keypad(mainwin, TRUE); /* Enable the keypad for non-char keys */
/* Print usage and refresh() the screen */
mvaddstr(2, 10, " Usage");
mvaddstr(3, 10, "====================");
mvaddstr(4, 10, "SpaceBar to Pause");
mvaddstr(5, 10, "ESC to quit");
mvaddstr(6, 10, "Right to forward");
mvaddstr(7, 10, "Left to forward");
refresh();
/*
* Start movie timer to play
*/
continueMovie();
while ((ch = getch()) != ESC_BTN)
{
switch (ch) {
case KEY_LEFT:
pauseMovie();
movie_time.backward(1000);
findNextSubtitle(0);
continueMovie();
break;
case KEY_RIGHT:
/*
* If we reach the end, no need to forward
*/
//if (iter != strInfoList.end()) {
if (movie_time.timeInMsec + 1000 <= movie_end_time) {
pauseMovie();
movie_time.forward(1000);
findNextSubtitle(1);
continueMovie();
}
break;
case ' ':
togglePlaying();
break;
}
}
/* Clean up after ourselves */
delwin(mainwin);
endwin();
refresh();
return EXIT_SUCCESS;
}
<commit_msg>ff/fb speed is parametric.<commit_after>//============================================================================
// Name : main.cpp
// Author : Kadir Yasar
// Version :
// Copyright : MIT License
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <fstream>
#include <ctype.h>
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <list>
#include <cmath>
#include "StrInfo.h"
#include "StrTime.h"
using namespace std;
#define SRT_FILE_NAME_LEN 256
#define ESC_BTN 27
const std::string WHITESPACE = " \n\r\t";
static StrTime movie_time;
int counter = 0, lines_printed = 0;
std::list<StrInfo*> strInfoList;
std::list<StrInfo*>::iterator iter;
struct itimerval timer;
struct sigaction sa;
int totalPrinted = 0;
bool currPrinted = false;
int executed = 0;
int movie_end_time = 0;
void movie_player(int);
bool timerStopped = false;
/*
* Movie timer pause/play methods
*/
void pauseMovie(void)
{
timer.it_value.tv_usec = 0;
timer.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &timer, NULL);
timerStopped = true;
}
void continueMovie()
{
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &movie_player;
sigaction (SIGALRM, &sa, NULL); // POSIX signal
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 1000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 1000; // every milliseconds
setitimer (ITIMER_REAL, &timer, NULL);
timerStopped = false;
}
void togglePlaying(void)
{
if (timerStopped) continueMovie();
else pauseMovie();
}
void clearLatestLinesOnScreen()
{
for (int i = 0; i < lines_printed; i++) {
move(14 + i, 0);
clrtoeol();
}
lines_printed = 0;
}
/*
* This method is invoked when fast forward or backward operation is needed
* It finds the next subtitle entry on the list according to updated movie time
*/
void findNextSubtitle(int direction)
{
currPrinted = false;
clearLatestLinesOnScreen();
/*
* FORWARD
*/
if (direction) {
while (movie_time.cmpTime((*iter)->endTime) > 0) {
if (iter != --strInfoList.end()) {
iter++;
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
} else
break;
}
}
/*
* BACKWARD
*/
else {
while (movie_time.cmpTime((*iter)->startTime) < 0) {
if (iter != strInfoList.begin()) {
iter--;
if (movie_time.cmpTime((*iter)->endTime) >= 0) {
iter++;
break;
}
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
}
else
break;
}
}
}
/*
* This function is actual player function
* It is invoked by POSIX ALARM interrupt in every milliseconds
* Responsible for showing or removing subtitle sentences according to movie time
* on the Ncurses screen
*/
void movie_player(int sig)
{
/*
* We reach the end of the subtitle list?
* If yes, stop the movie time
*/
if (iter == strInfoList.end()) {
pauseMovie();
return;
}
movie_time.incMillisecs();
mvprintw(9, 10, "Movie Time: %s", movie_time.getPrintableTime().c_str());
mvprintw(10, 10, "N: %2d, Total shown: %2d", (*iter)->number, totalPrinted);
refresh();
/*
* Start time for the current subtitle sentences ?
*/
if (!currPrinted && movie_time.betweenTimes((*iter)->startTime, (*iter)->endTime))
{
mvprintw(12, 10, "%d %s --> %s", (*iter)->number, (*iter)->startTime.getPrintableTime().c_str(), (*iter)->endTime.getPrintableTime().c_str());
lines_printed = 0;
for (std::list<std::string>::iterator li = (*iter)->lines.begin(); li != (*iter)->lines.end(); li++, lines_printed++) {
mvprintw(14 + lines_printed, 10, "%s", (*li).c_str());
}
refresh();
/*
* This subtitle entry is shown, do not process it again
*/
currPrinted = true;
totalPrinted++;
}
/*
* Deadline of the current subtitle sentences ?
*/
else if (currPrinted && movie_time.cmpTime((*iter)->endTime) >= 0)
{
/*
* Remove the sentences on the screen, they are expired
*/
clearLatestLinesOnScreen();
/*
* Skip to next subtitle entry
*/
iter++;
currPrinted = false;
}
}
/*
* Some string functions to trim empty lines
*/
std::string TrimLeft(const std::string& s)
{
size_t startpos = s.find_first_not_of(WHITESPACE);
return (startpos == std::string::npos) ? "" : s.substr(startpos);
}
std::string TrimRight(const std::string& s)
{
size_t endpos = s.find_last_not_of(WHITESPACE);
return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
}
std::string Trim(const std::string& s)
{
return TrimRight(TrimLeft(s));
}
bool isEmptyLine(string strInput)
{
if (Trim(strInput).compare("") != 0)
return false;
else
return true;
}
std::string readLineFromFile(ifstream* fd_srt)
{
std::string line;
getline(*fd_srt, line);
return line;
}
/*
* This function process given Subtitle file
* Creates a list of subtitle entries in the file
*/
void processSrtFile(char* srt_file)
{
ifstream fd_srt;
std::string strLine;
int vals[8];
fd_srt.open(srt_file);
if (!fd_srt)
{
cout << "Cannot open Subtitle file: " << srt_file << endl;
exit(EXIT_FAILURE);
}
// While there's still stuff left to read
while (fd_srt)
{
// read stuff from the file into a string and print it
strLine = readLineFromFile(&fd_srt);
if (!isEmptyLine(strLine))
{
// Create an Entry object to keep the number times and sentences
StrInfo* strInfo = new StrInfo();
strInfo->number = atoi(strLine.c_str()); // Gets the entry number
strLine = readLineFromFile(&fd_srt);
// Gets the start and end times
sscanf(strLine.c_str(), "%u:%u:%u,%u --> %u:%u:%u,%u",
&vals[0], &vals[1], &vals[2], &vals[3],
&vals[4], &vals[5], &vals[6], &vals[7]);
strInfo->startTime.setTime(vals[0], vals[1], vals[2], vals[3]);
strInfo->endTime.setTime(vals[4], vals[5], vals[6], vals[7]);
// Gets sentences for current entry
strLine = readLineFromFile(&fd_srt);
while (!isEmptyLine(strLine)) {
strInfo->lines.insert(strInfo->lines.end(), strLine);
strLine = readLineFromFile(&fd_srt);
}
// Store current entry in the list of all entries
strInfoList.insert(strInfoList.end(), strInfo);
}
}
// Print all entries read. Just for debug
/*for (std::list<StrInfo*>::iterator it = strInfoList.begin(); it != strInfoList.end(); it++)
{
cout << (*it)->number << " " << (*it)->startTime.getPrintableTime() << " --> " << (*it)->endTime.getPrintableTime() << endl;
cout << (*it)->number << " " << (*it)->startTime.timeInMsec << " --> " << (*it)->endTime.timeInMsec << endl;
cout << (*it)->number << " " << (*it)->startTime.getPrintableTime() << " --> " << (*it)->endTime.getPrintableTime() << endl;
for (std::list<std::string>::iterator li = (*it)->lines.begin(); li != (*it)->lines.end(); li++) {
cout << (*li) << endl;
}
cout << endl;
} */
/*
* Keep the end time of the subtitle for boundary control
*/
iter = strInfoList.end();
movie_end_time = (*--iter)->endTime.timeInMsec;
/*
* Current player iterator on the first entry of the list
* Srt File is completely processed and all entries are stored in an arraylist
* Now, we are ready to play
*/
iter = strInfoList.begin();
}
void usage()
{
cout << "Welcome to KSP (Kadir's just Subtitle Player)" << endl << endl;
cout << "\t Usage:" << endl << "\t ===================" << endl;
cout << "\t -h \t\t\t: Help" << endl;
cout << "\t -f <srt-file> \t\t: SRT formatted subtitle file" << endl;
cout << "\t -s <milliseconds> \t: Fast forward/backward speed on left/right buttons" << endl << endl;
}
int main(int argc, char *argv[]) {
WINDOW * mainwin;
int ch, ch_prev = 0, speed = 0;
char srt_file[SRT_FILE_NAME_LEN] = {0};
while ( (ch = getopt(argc, argv, "f:s:h") ) != -1)
{
switch (ch)
{
case 'f':
snprintf(srt_file, SRT_FILE_NAME_LEN, "%s", optarg);
cout << "SRT file: " << srt_file << endl;
break;
case 's':
speed = atoi(optarg);
if (speed < 0 || speed > 10000)
{
cout << "FF/FB speed must be less than 10 seconds (10.000 msec) !" << endl;
}
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
fprintf(stderr, "Unrecognized option!\n");
break;
}
}
// Check file
if (!strcmp(srt_file, ""))
{
cout << "No Subtitle file given !!" << srt_file << endl;
usage();
exit(EXIT_FAILURE);
}
/*
* No need for return value
*/
processSrtFile(srt_file);
/* Initialize ncurses */
if ((mainwin = initscr()) == NULL ) {
fprintf(stderr, "Error initializing ncurses.\n");
exit(EXIT_FAILURE);
}
noecho(); /* Turn off key echoing */
keypad(mainwin, TRUE); /* Enable the keypad for non-char keys */
/* Print usage and refresh() the screen */
mvaddstr(1, 10, " Usage");
mvaddstr(2, 10, "====================");
mvaddstr(3, 10, "SpaceBar to Pause");
mvaddstr(4, 10, "ESC to quit");
mvaddstr(5, 10, "Right to forward ");
mvaddstr(6, 10, "Left to backward ");
mvprintw(8, 10, "ff/fb speed is %d msec", speed);
refresh();
/*
* Start movie timer to play
*/
continueMovie();
while ((ch = getch()) != ESC_BTN)
{
switch (ch) {
case KEY_LEFT:
pauseMovie();
movie_time.backward(speed);
findNextSubtitle(0);
continueMovie();
break;
case KEY_RIGHT:
/*
* If we reach the end, no need to forward
*/
//if (iter != strInfoList.end()) {
if (movie_time.timeInMsec + speed <= movie_end_time) {
pauseMovie();
movie_time.forward(speed);
findNextSubtitle(1);
continueMovie();
}
break;
case ' ':
togglePlaying();
break;
}
}
/* Clean up after ourselves */
delwin(mainwin);
endwin();
refresh();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>d10e8eae-2747-11e6-a16e-e0f84713e7b8<commit_msg>oh my, I hate lynda<commit_after>d134658c-2747-11e6-bd9d-e0f84713e7b8<|endoftext|> |
<commit_before>193e7f42-2f67-11e5-8c56-6c40088e03e4<commit_msg>19480db4-2f67-11e5-baf0-6c40088e03e4<commit_after>19480db4-2f67-11e5-baf0-6c40088e03e4<|endoftext|> |
<commit_before>8d255a70-2e4f-11e5-bb88-28cfe91dbc4b<commit_msg>8d2c59c2-2e4f-11e5-8882-28cfe91dbc4b<commit_after>8d2c59c2-2e4f-11e5-8882-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <array>
#include <fstream>
#include <iostream>
#include <locale.h>
#include <vector>
#ifdef MEASURE_BRANCHING_FACTOR
#include <thread>
#endif
#include "alphabeta_pv.hpp"
#include "game.hpp"
#include "heuristic.hpp"
#include "position.hpp"
#include "trainer.hpp"
#include "util.hpp"
using namespace std;
template <class S, class T> char game_test(int depth = 12) {
heuristic e = best_heuristic();
position p;
S black{e, depth, BLACK};
T white{e, depth, WHITE};
int i;
try {
for (i = 0; i < 256; i++) {
cout << p;
p = black.get_move(p);
cout << p;
p = white.get_move(p);
}
cout << "Draw after 256 moves." << endl;
return 0;
} catch (agent::resign) {
if (p.player() == BLACK) {
cout << "White wins after " << i << " moves." << endl;
return -1;
} else {
cout << "Black wins after " << i << " moves." << endl;
return 1;
}
}
}
static void usage() {
cout << "Usage: checkers <arguments>\n"
<< " <arguments> can be any of:\n"
<< " --train Train the heuristic by playing the "
"computer against itself.\n"
<< " --cpu-game [depth] Showcase a CPU vs CPU match.\n"
#ifdef MEASURE_BRANCHING_FACTOR
<< " --branch Plays a few games to test the branching "
"factor.\n"
#endif
<< " --game Play against the computer\n"
<< "Ensure UTF-8 support is enabled. In PuTTY, select:\n"
<< "Configure -> Window -> Translation -> Remote character set -> UTF-8" << endl;
exit(0);
}
static void train() {
heuristic e = best_heuristic();
trainer t{{e}, 12, 12};
for (;;) {
t();
ofstream o{"training_data.txt", ios_base::app};
o << '\n' << t << endl;
#ifdef MEASURE_BRANCHING_FACTOR
alphabeta_pv::report_branching();
#endif
}
}
#ifdef MEASURE_BRANCHING_FACTOR
template <class T> void measure_branching() {
vector<thread> threads;
mutex m;
for (int i = thread::hardware_concurrency(); i--;)
threads.emplace_back(thread{[&] {
while (1) {
heuristic e = best_heuristic();
T black{e, 12, BLACK};
T white{e, 12, WHITE};
position p;
try {
for (int i = 192; i--;) {
p = black.get_move(p);
p = white.get_move(p);
}
} catch (agent::resign) {
}
m.lock();
T::report_branching();
m.unlock();
}
}});
for (thread &t : threads)
t.join();
}
#endif
int main(int argc, char **argv) {
setlocale(LC_ALL, ""); // UTF-8 characters are used to represent the pieces.
if (argc == 1)
usage();
for (int i = 1; i < argc; i++)
if (string{"--train"}.compare(argv[i]) == 0)
train();
else if (string{"--cpu-game"}.compare(argv[i]) == 0) {
int depth = 0;
if (i + 1 < argc)
depth = atoi(argv[i + 1]);
if (depth > 0)
++i;
else
depth = 12;
game_test<alphabeta_pv, alphabeta_pv>(depth);
} else if (string{"--game"}.compare(argv[i]) == 0)
play_game();
#ifdef MEASURE_BRANCHING_FACTOR
else if (string{"--branch"}.compare(argv[i]) == 0)
measure_branching<alphabeta_pv>();
#endif
else
usage();
#ifdef MEASURE_BRANCHING_FACTOR
alphabeta_pv::report_branching();
alphabeta::report_branching();
#endif
return 0;
}
<commit_msg>Made branch measurement configurable.<commit_after>#include <array>
#include <fstream>
#include <iostream>
#include <locale.h>
#include <vector>
#ifdef MEASURE_BRANCHING_FACTOR
#include <thread>
#endif
#include "alphabeta_pv.hpp"
#include "game.hpp"
#include "heuristic.hpp"
#include "position.hpp"
#include "trainer.hpp"
#include "util.hpp"
using namespace std;
template <class S, class T> char game_test(int depth = 12) {
heuristic e = best_heuristic();
position p;
S black{e, depth, BLACK};
T white{e, depth, WHITE};
int i;
try {
for (i = 0; i < 256; i++) {
cout << p;
p = black.get_move(p);
cout << p;
p = white.get_move(p);
}
cout << "Draw after 256 moves." << endl;
return 0;
} catch (agent::resign) {
if (p.player() == BLACK) {
cout << "White wins after " << i << " moves." << endl;
return -1;
} else {
cout << "Black wins after " << i << " moves." << endl;
return 1;
}
}
}
static void usage() {
cout << "Usage: checkers <arguments>\n"
<< " <arguments> can be any of:\n"
<< " --train Train the heuristic by playing the "
"computer against itself.\n"
<< " --cpu-game [depth] Showcase a CPU vs CPU match.\n"
#ifdef MEASURE_BRANCHING_FACTOR
<< " --branch Plays a few games to test the branching "
"factor.\n"
#endif
<< " --game Play against the computer\n"
<< "Ensure UTF-8 support is enabled. In PuTTY, select:\n"
<< "Configure -> Window -> Translation -> Remote character set -> UTF-8"
<< endl;
}
static void train() {
heuristic e = best_heuristic();
trainer t{{e}, 12, 12};
for (;;) {
t();
ofstream o{"training_data.txt", ios_base::app};
o << '\n' << t << endl;
#ifdef MEASURE_BRANCHING_FACTOR
alphabeta_pv::report_branching();
#endif
}
}
#ifdef MEASURE_BRANCHING_FACTOR
template <class T, int depth = 12> void measure_branching() {
vector<thread> threads;
mutex m;
for (int i = thread::hardware_concurrency(); i--;)
threads.emplace_back(thread{[&] {
while (1) {
heuristic e = best_heuristic();
T black{e, depth, BLACK};
T white{e, depth, WHITE};
position p;
try {
for (int i = 192; i--;) {
p = black.get_move(p);
p = white.get_move(p);
}
} catch (agent::resign) {
}
m.lock();
T::report_branching();
m.unlock();
}
}});
for (thread &t : threads)
t.join();
}
#endif
int main(int argc, char **argv) {
setlocale(LC_ALL, ""); // UTF-8 characters are used to represent the pieces.
if (argc == 1)
usage();
for (int i = 1; i < argc; i++)
if (string{"--train"}.compare(argv[i]) == 0)
train();
else if (string{"--cpu-game"}.compare(argv[i]) == 0) {
int depth = 0;
if (i + 1 < argc)
depth = atoi(argv[i + 1]);
if (depth > 0)
++i;
else
depth = 12;
game_test<alphabeta_pv, alphabeta_pv>(depth);
} else if (string{"--game"}.compare(argv[i]) == 0)
play_game();
#ifdef MEASURE_BRANCHING_FACTOR
else if (string{"--branch"}.compare(argv[i]) == 0)
measure_branching<alphabeta_pv, 8>();
#endif
else
usage();
#ifdef MEASURE_BRANCHING_FACTOR
alphabeta_pv::report_branching();
alphabeta::report_branching();
#endif
return 0;
}
<|endoftext|> |
<commit_before>a42b3ed7-2e4f-11e5-a613-28cfe91dbc4b<commit_msg>a4338f17-2e4f-11e5-85c0-28cfe91dbc4b<commit_after>a4338f17-2e4f-11e5-85c0-28cfe91dbc4b<|endoftext|> |
<commit_before>8fd048d9-2d14-11e5-af21-0401358ea401<commit_msg>8fd048da-2d14-11e5-af21-0401358ea401<commit_after>8fd048da-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5cd3b674-2e3a-11e5-b1bc-c03896053bdd<commit_msg>5ce4a970-2e3a-11e5-8736-c03896053bdd<commit_after>5ce4a970-2e3a-11e5-8736-c03896053bdd<|endoftext|> |
<commit_before>0d76b122-2f67-11e5-9da5-6c40088e03e4<commit_msg>0d7db788-2f67-11e5-9c97-6c40088e03e4<commit_after>0d7db788-2f67-11e5-9c97-6c40088e03e4<|endoftext|> |
<commit_before>985ae475-2d3e-11e5-87a6-c82a142b6f9b<commit_msg>98c32b80-2d3e-11e5-924e-c82a142b6f9b<commit_after>98c32b80-2d3e-11e5-924e-c82a142b6f9b<|endoftext|> |
<commit_before>08ddd6c8-585b-11e5-b224-6c40088e03e4<commit_msg>08e47ff8-585b-11e5-80b0-6c40088e03e4<commit_after>08e47ff8-585b-11e5-80b0-6c40088e03e4<|endoftext|> |
<commit_before>3df1b4c7-2e4f-11e5-94bc-28cfe91dbc4b<commit_msg>3df8a600-2e4f-11e5-a922-28cfe91dbc4b<commit_after>3df8a600-2e4f-11e5-a922-28cfe91dbc4b<|endoftext|> |
<commit_before>
//Main entry point
int main()
{
return 0;
}
<commit_msg>Basic sfml windows test<commit_after>#include <SFML/Window.hpp>
//Main entry point
int main()
{
sf::Window window(sf::VideoMode(800,600),"",sf::Style::None); //Splash screen
//Load stuff ie: settings
window.create(sf::VideoMode(800,600),"NitroTD");
return 0;
}
<|endoftext|> |
<commit_before>06031c74-585b-11e5-8901-6c40088e03e4<commit_msg>0610e44c-585b-11e5-9630-6c40088e03e4<commit_after>0610e44c-585b-11e5-9630-6c40088e03e4<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <curl/curl.h>
#include <openssl/hmac.h>
using std::string;
using std::cout;
using std::endl;
using std::strcpy;
struct pair {
string key, value;
pair() {}
pair(string k, string v) {
key = k;
value = v;
}
bool operator<(const pair &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
string hmac_sha1(unsigned const char *key, unsigned const char *data, int key_size, int data_size) {
unsigned int i;
HMAC_CTX ctx;
unsigned int len;
unsigned char out[40];
HMAC_Init(&ctx, &key, key_size, EVP_sha1());
HMAC_Update(&ctx, data, data_size);
HMAC_Final(&ctx, out, &len);
/*unsigned char *HMAC(EVP_sha1(), key, sizeof(key),
data, sizeof(data), out, sizeof(out));*/
HMAC_cleanup(&ctx);
std::stringstream buff;
for (i = 0; i < len; i++) {
buff << std::hex << (int)out[i];
}
return buff.str();
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
::pair app_info[8] = {::pair("screen_name", username),
::pair("oauth_consumer_key", username),
::pair("oauth_nonce", gen_alphanum(42)),
::pair("oauth_signature", ""),
::pair("oauth_signature_method", "HMAC_SHA1"),
::pair("oauth_timestamp", std::to_string(time(0))),
::pair("oauth_token", ""),
::pair("oauth_version", "1.0")};
string secrets[2];
string line;
std::ifstream infile("twitter.conf");
while (std::getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("csecret") != string::npos) {
find_and_replace(line, "csecret=", "");
secrets[0] = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[6].value = line;
} else if (line.find("asecret") != string::npos) {
find_and_replace(line, "asecret=", "");
secrets[1] = line;
} else {
continue;
}
}
::pair encode_info[8];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 8; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = pair(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
string url = "https://api.twitter.com/1.1/users/lookup.json";
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
string sign_key;
temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
sign_key = string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
char key[sign_key.size()];
char data[out.size()];
strcpy(key, sign_key.c_str());
strcpy(data, out.c_str());
cout << hmac_sha1((unsigned const char *)key, (unsigned const char *)data, sizeof(key),
sizeof(data))
<< endl;
/*string command = "curl --get 'https://api.twitter.com/1.1/users/lookup.json' --data
'screen_name=" + username + "' --header 'Authorization: OAuth oauth_consumer_key=\"" +
appinfo[0] + "\", oauth_nonce=\"" + nonce + "\",
oauth_signature=\"h18hZk1pMPAc8uaxBNLqvc1fQLU\%3D\", oauth_signature_method=\"HMAC-SHA1\",
oauth_timestamp=\"1457318794\", oauth_token=\"" + appinfo[2] + "\", oauth_version=\"1.0\"'
--verbose > lookup.json";
std::system(command.c_str());*/
/*string url = "https://twitter.com/" + username + "#page-container";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}*/
curl_easy_cleanup(curl);
return 0;
}
<commit_msg>Added base64 encoding stuff<commit_after>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
using std::string;
using std::cout;
using std::endl;
using std::strcpy;
struct pair {
string key, value;
pair() {}
pair(string k, string v) {
key = k;
value = v;
}
bool operator<(const pair &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
string hmac_sha1(unsigned const char *key, unsigned const char *data, int key_size, int data_size) {
unsigned int i;
HMAC_CTX ctx;
unsigned int len;
unsigned char out[40];
HMAC_Init(&ctx, &key, key_size, EVP_sha1());
HMAC_Update(&ctx, data, data_size);
HMAC_Final(&ctx, out, &len);
/*unsigned char *HMAC(EVP_sha1(), key, sizeof(key),
data, sizeof(data), out, sizeof(out));*/
HMAC_cleanup(&ctx);
std::stringstream buff;
for (i = 0; i < len; i++) {
buff << std::hex << (int)out[i];
}
return buff.str();
}
string base64(string data) {
BIO *bio, *b64;
char message[data.size()];
strcpy(message, data.c_str());
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdout, BIO_NOCLOSE);
BIO_push(b64, bio);
BIO_write(b64, message, strlen(message));
BIO_flush(b64);
BIO_free_all(b64);
return data;
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
::pair app_info[8] = {::pair("screen_name", username),
::pair("oauth_consumer_key", username),
::pair("oauth_nonce", gen_alphanum(42)),
::pair("oauth_signature", ""),
::pair("oauth_signature_method", "HMAC_SHA1"),
::pair("oauth_timestamp", std::to_string(time(0))),
::pair("oauth_token", ""),
::pair("oauth_version", "1.0")};
string secrets[2];
string line;
std::ifstream infile("twitter.conf");
while (std::getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("csecret") != string::npos) {
find_and_replace(line, "csecret=", "");
secrets[0] = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[6].value = line;
} else if (line.find("asecret") != string::npos) {
find_and_replace(line, "asecret=", "");
secrets[1] = line;
} else {
continue;
}
}
::pair encode_info[8];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 8; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = pair(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
string url = "https://api.twitter.com/1.1/users/lookup.json";
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
string sign_key;
temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
sign_key = string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
char key[sign_key.size()];
char data[out.size()];
strcpy(key, sign_key.c_str());
strcpy(data, out.c_str());
app_info[3].value = base64(hmac_sha1((unsigned const char *)key, (unsigned const char *)data,
sizeof(key), sizeof(data)));
string command =
"curl --get \'" + url + "\' --data \'screen_name=" + app_info[0].value +
"\' --header \'Authorization: OAuth oauth_consumer_key=\"" + app_info[1].value +
"\", oauth_nonce=\"" + app_info[2].value + "\", oauth_signature=\"" + app_info[3].value +
"\", oauth_signature_method=\"" + app_info[4].value + "\", oauth_timestamp=\"" +
app_info[5].value + "\", oauth_token=\"" + app_info[6].value + "\", oauth_version=\"" +
app_info[7].value + "\" --verbose > lookup.json";
cout << command << endl;
// std::system(command.c_str());
/*string url = "https://twitter.com/" + username + "#page-container";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}*/
curl_easy_cleanup(curl);
return 0;
}
<|endoftext|> |
<commit_before>e909f3e3-327f-11e5-825b-9cf387a8033e<commit_msg>e90ff211-327f-11e5-999a-9cf387a8033e<commit_after>e90ff211-327f-11e5-999a-9cf387a8033e<|endoftext|> |
<commit_before>d254b29c-313a-11e5-ad08-3c15c2e10482<commit_msg>d25a81fd-313a-11e5-ba29-3c15c2e10482<commit_after>d25a81fd-313a-11e5-ba29-3c15c2e10482<|endoftext|> |
<commit_before>8b985fc2-2e4f-11e5-808b-28cfe91dbc4b<commit_msg>8b9f2294-2e4f-11e5-8c8f-28cfe91dbc4b<commit_after>8b9f2294-2e4f-11e5-8c8f-28cfe91dbc4b<|endoftext|> |
<commit_before>648056f4-2fa5-11e5-bc15-00012e3d3f12<commit_msg>648252c6-2fa5-11e5-a0ab-00012e3d3f12<commit_after>648252c6-2fa5-11e5-a0ab-00012e3d3f12<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
template<class Derived, typename Delegate>
class using_;
template<class Derived, typename Delegate>
auto DerivedType(using_<Derived, Delegate> &) -> Derived;
template<class Derived, typename Delegate>
auto DelegateType(using_<Derived, Delegate> &) -> Delegate;
template<class Base>
auto &delegate(Base &base)
{
using Derived = decltype(DerivedType(base));
static_assert(std::is_base_of_v<Base, Derived>);
//! Downcast to the derived class
auto &derived = static_cast<Derived &>(base);
using Delegate = decltype(DelegateType(base));
//! Now invoke the conversion operator
return static_cast<Delegate &>(derived);
}
template<class Class, typename... T>
struct DelayedImpl
{
using type = Class;
};
template<class Class, typename... T>
using Delayed = typename DelayedImpl<Class, T...>::type;
#define MEMBER(member) \
template<typename... T> \
auto member(T &&... args) -> decltype(DelegateType(std::declval<Delayed<decltype(*this), T...>>()).member(std::forward<T>(args)...)) \
{ \
return delegate(*this).member(std::forward<T>(args)...); \
} \
template<class Derived, typename Delegate>
class using_
{
public:
MEMBER(push_back)
MEMBER(begin)
MEMBER(end)
};
template<typename T>
class Property : public using_<Property<T>, T>
{
public:
operator T &()
{
return data;
}
private:
T data;
};
int main()
{
std::cout << "Hello, Wandbox!" << std::endl;
Property<std::vector<int>> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
//v.push_back(1, 2, 3);
for (auto x : v)
{
std::cout << x << std::endl;
}
Property<int> x{};
Property<int> y{};
auto z = x + y;
std::cout << z << std::endl;
std::cout << typeid(z).name() << std::endl;
}
<commit_msg>Generalized the DerivedType and DelegateType functions to also work for other types than 'using_'.<commit_after>#include <iostream>
#include <vector>
template<class Derived, typename Delegate>
class using_;
template<template<typename, typename> class Class, class Derived, typename Delegate>
auto DerivedType(Class<Derived, Delegate> &) -> Derived;
template<template<typename, typename> class Class, class Derived, typename Delegate>
auto DelegateType(Class<Derived, Delegate> &) -> Delegate;
template<class Base>
auto &delegate(Base &base)
{
using Derived = decltype(DerivedType(base));
static_assert(std::is_base_of_v<Base, Derived>);
//! Downcast to the derived class
auto &derived = static_cast<Derived &>(base);
using Delegate = decltype(DelegateType(base));
//! Now invoke the conversion operator
return static_cast<Delegate &>(derived);
}
template<class Class, typename... T>
struct DelayedImpl
{
using type = Class;
};
template<class Class, typename... T>
using Delayed = typename DelayedImpl<Class, T...>::type;
#define MEMBER(member) \
template<typename... T> \
auto member(T &&... args) -> decltype(DelegateType(std::declval<Delayed<decltype(*this), T...>>()).member(std::forward<T>(args)...)) \
{ \
return delegate(*this).member(std::forward<T>(args)...); \
} \
template<class Derived, typename Delegate>
class using_
{
public:
MEMBER(push_back)
MEMBER(begin)
MEMBER(end)
};
template<typename T>
class Property : public using_<Property<T>, T>
{
public:
operator T &()
{
return data;
}
private:
T data;
};
int main()
{
std::cout << "Hello, Wandbox!" << std::endl;
Property<std::vector<int>> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
//v.push_back(1, 2, 3);
for (auto x : v)
{
std::cout << x << std::endl;
}
Property<int> x{};
Property<int> y{};
auto z = x + y;
std::cout << z << std::endl;
std::cout << typeid(z).name() << std::endl;
}
<|endoftext|> |
<commit_before>676e84ab-2e4f-11e5-a2e2-28cfe91dbc4b<commit_msg>67755c94-2e4f-11e5-8259-28cfe91dbc4b<commit_after>67755c94-2e4f-11e5-8259-28cfe91dbc4b<|endoftext|> |
<commit_before>7e7919ed-2d15-11e5-af21-0401358ea401<commit_msg>7e7919ee-2d15-11e5-af21-0401358ea401<commit_after>7e7919ee-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
#include "shifter.h"
#include "launch_counter.h"
#include "pid_controller.h"
#include "two_jags.h"
#include <PWM.h>
#include "override_controls.h"
#include "vision_alt.h"
//#include "states/shooting.h" no such file or directory
//#include "states/driving.h" no such file or directory
/* this is just for test purposes. Don't use it */
launch_counter launch_wheel_counter(launcher_wheel);
two_jags launch_wheel_jags(left_launcher_jag, right_launcher_jag);
pid_controller launch_pid(0.0, 0.0, 0.0, &launch_wheel_counter, &launch_wheel_jags);
/* end */
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
global_state.set_state(STATE_DRIVING);
init_camera();
//launcher_wheel.Enable();
launcher_wheel.Start();
global_state.register_func(STATE_DRIVING, state_driving);
global_state.register_func(STATE_SHOOTING, state_shooting);
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (right_joystick.GetRawButton(11) || left_joystick.GetRawButton(11)) {
servo_shifter.set(shifter::HIGH);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10) || right_joystick.GetRawButton(10)) {
servo_shifter.set(shifter::LOW);
//Sets servo to low gear
}
if(left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_SHOOTING);
}
//Turret rotation controlled by gunner joystick during drive state only. Must press button 1
if(gunner_joystick.GetRawButton(1)){
turret_rotation_jag.Set(gunner_joystick.GetX());
}
// bridge
if(gunner_joystick.GetRawButton(2)){//up
if (bridge_arm_switch.Get()){ //limit switch not pressed
bridge_arm_spike.Set(Relay::kForward);
}
}
else if(gunner_joystick.GetRawButton(3)){//down
bridge_arm_spike.Set(Relay::kReverse);
}
else {
bridge_arm_spike.Set(Relay::kOff);
}
// winch
if(gunner_joystick.GetRawButton(6)) {
turret_winch_jag.Set(-0.2);
}
else if(gunner_joystick.GetRawButton(7)) {
turret_winch_jag.Set(0.2);
}
else {
turret_winch_jag.Set(0.0);
}
if(gunner_joystick.GetRawButton(6)) {
turret_winch_jag.Set(-0.2);
}
else if(gunner_joystick.GetRawButton(7)) {
turret_winch_jag.Set(0.2);
}
else {
turret_winch_jag.Set(0.0);
}
if(gunner_joystick.GetRawButton(9)) {
printf("pot voltage: %f\n", launch_angle_pot.GetVoltage());
}
}
else if(global_state.get_state() == STATE_SHOOTING) {
// disable motor safety check to stop wasting netconsole space
drive.SetSafetyEnabled(false);
/*
vision_processing::update();
vector<double> target_degrees = vision_processing::get_degrees();
vector<double> target_distances = vision_processing::get_distance();
printf("Number of targets detected: %d\n", target_degrees.size());
if(target_degrees.size() >= 1) {
printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
}
else {
printf("No target detected\n");
}
if(target_distances.size() >= 1) {
printf("Distance of target: %f\n", target_distances[0]);
}
*/
target::update_targets();
if(!left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_DRIVING);
drive.SetSafetyEnabled(true);
}
}
//TEMPORARY: GUNNER LAUNCHER WHEEL CONTROLS
if (gunner_joystick.GetRawButton(4)) {
left_launcher_jag.Set(1.0);
right_launcher_jag.Set(1.0);
std::printf("Launcher Wheel Speed: %f\n", 1/launcher_wheel.GetPeriod());
}
else {
left_launcher_jag.Set(-0.05);
right_launcher_jag.Set(-0.05);
}
if (global_state.get_state() != STATE_SHOOTING) {
//MANUAL ROLLER CONTROL
if (gunner_joystick.GetRawButton(11)) {
//rollers up
rollers.set_direction(roller_t::UP);
}
else if (gunner_joystick.GetRawButton(10)) {
//rollers down
rollers.set_direction(roller_t::DOWN);
}
else {
rollers.set_direction(roller_t::OFF);
}
//
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
}
void robot_class::update_sensors() {
//run functions in update registry
registry().update();
//power on LEDs
camera_led_digital.Set(1);
//camera_led.SetRaw(255); //not using pwm
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<commit_msg>added back includes for states<commit_after>/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include <PWM.h>
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
#include "shifter.h"
#include "launch_counter.h"
#include "pid_controller.h"
#include "two_jags.h"
#include "vision_alt.h"
#include "override_controls.h"
#include "states/shooting.h"
#include "states/driving.h"
/* this is just for test purposes. Don't use it */
launch_counter launch_wheel_counter(launcher_wheel);
two_jags launch_wheel_jags(left_launcher_jag, right_launcher_jag);
pid_controller launch_pid(0.0, 0.0, 0.0, &launch_wheel_counter, &launch_wheel_jags);
/* end */
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
global_state.set_state(STATE_DRIVING);
init_camera();
//launcher_wheel.Enable();
launcher_wheel.Start();
global_state.register_func(STATE_DRIVING, state_driving);
global_state.register_func(STATE_SHOOTING, state_shooting);
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (right_joystick.GetRawButton(11) || left_joystick.GetRawButton(11)) {
servo_shifter.set(shifter::HIGH);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10) || right_joystick.GetRawButton(10)) {
servo_shifter.set(shifter::LOW);
//Sets servo to low gear
}
if(left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_SHOOTING);
}
//Turret rotation controlled by gunner joystick during drive state only. Must press button 1
if(gunner_joystick.GetRawButton(1)){
turret_rotation_jag.Set(gunner_joystick.GetX());
}
// bridge
if(gunner_joystick.GetRawButton(2)){//up
if (bridge_arm_switch.Get()){ //limit switch not pressed
bridge_arm_spike.Set(Relay::kForward);
}
}
else if(gunner_joystick.GetRawButton(3)){//down
bridge_arm_spike.Set(Relay::kReverse);
}
else {
bridge_arm_spike.Set(Relay::kOff);
}
// winch
if(gunner_joystick.GetRawButton(6)) {
turret_winch_jag.Set(-0.2);
}
else if(gunner_joystick.GetRawButton(7)) {
turret_winch_jag.Set(0.2);
}
else {
turret_winch_jag.Set(0.0);
}
if(gunner_joystick.GetRawButton(6)) {
turret_winch_jag.Set(-0.2);
}
else if(gunner_joystick.GetRawButton(7)) {
turret_winch_jag.Set(0.2);
}
else {
turret_winch_jag.Set(0.0);
}
if(gunner_joystick.GetRawButton(9)) {
printf("pot voltage: %f\n", launch_angle_pot.GetVoltage());
}
}
else if(global_state.get_state() == STATE_SHOOTING) {
// disable motor safety check to stop wasting netconsole space
drive.SetSafetyEnabled(false);
/*
vision_processing::update();
vector<double> target_degrees = vision_processing::get_degrees();
vector<double> target_distances = vision_processing::get_distance();
printf("Number of targets detected: %d\n", target_degrees.size());
if(target_degrees.size() >= 1) {
printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
}
else {
printf("No target detected\n");
}
if(target_distances.size() >= 1) {
printf("Distance of target: %f\n", target_distances[0]);
}
*/
target::update_targets();
if(!left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_DRIVING);
drive.SetSafetyEnabled(true);
}
}
//TEMPORARY: GUNNER LAUNCHER WHEEL CONTROLS
if (gunner_joystick.GetRawButton(4)) {
left_launcher_jag.Set(1.0);
right_launcher_jag.Set(1.0);
std::printf("Launcher Wheel Speed: %f\n", 1/launcher_wheel.GetPeriod());
}
else {
left_launcher_jag.Set(-0.05);
right_launcher_jag.Set(-0.05);
}
if (global_state.get_state() != STATE_SHOOTING) {
//MANUAL ROLLER CONTROL
if (gunner_joystick.GetRawButton(11)) {
//rollers up
rollers.set_direction(roller_t::UP);
}
else if (gunner_joystick.GetRawButton(10)) {
//rollers down
rollers.set_direction(roller_t::DOWN);
}
else {
rollers.set_direction(roller_t::OFF);
}
//
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
}
void robot_class::update_sensors() {
//run functions in update registry
registry().update();
//power on LEDs
camera_led_digital.Set(1);
//camera_led.SetRaw(255); //not using pwm
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.