<commit_before>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <sys/stat.h>

//getlogin() and gethostname().
#include <unistd.h>

//perror.
#include <stdio.h>

//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>

//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"

//that one class.
#include "Command.h"

using namespace std;
using namespace boost;

//execute command.
void execute(const vector<string> & s);

//replaces char in string.
void replace_char(string &s, char o, char r);

//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);

//display vector.
template<typename unit>
void display_vector(vector<unit> v);

//helper function that finds amount of character.
int find_char_amount(const string s,char c);

//removes comment from input.
void remove_comment(string &s);

//removes char in string.
void remove_char(string &s, char c);

//checks if string passed in contains a flag
bool isFlag(string f);

//creates command types from vector of strings.
vector<Command> create_commands(const vector<string> &v);

int main()
{
    //grab the login.
    char* login = getlogin();

    //start a flag.
    bool login_check = true;

    if((!login) != 0)
    {
        //check flag.
        login_check = false;

        //output error.
        perror("Error: could not retrieve login name");
    }

    //hold c-string for host name.
    char host[150];

    //start another flag.
    bool host_check = true;

    //gets hostname while checking if it actually grabbed it.
    if(gethostname(host,sizeof(host)) != 0)
    {
        //check flag.
        host_check = false;

        //output error.
        perror("Error: could not rerieve host name.");
    }

    //warn user of upcoming trouble.
    if(login_check == false || host_check == false)
        cout << "Unable to display login and/or host information." << endl;

    //string to hold user input.
    string input;

    while(true)
    {
        //output login@hostname.
        if(login_check && host_check)
            cout << login << '@' << host << ' ';

        //bash money.
        cout << "$ ";

        //placeholder to tell its the program.
        cout << " (program) ";

        //geting input as a string.
        getline(cin,input);

        //remove extra white space.
        trim(input);

        //remove comments.
        remove_comment(input);

        //trim again just in case.
        trim(input);

        //testing parse.
        cout << "Testing parse" << endl;
        display_vector(parseInput(input));

        //execute command.
        execute(parseInput(input));

    }

    cout << "End of program" << endl;

    return 0;
}

void execute(const vector<string> &s)
{
    //check to see if user wants to quit and its the only command.
    if(s.size() == 1)
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == "exit")
                exit(0);

    //c-string to hold command.
    char* args[2048];

    //place, remove comments and convert commands.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        string temp = s.at(i);
        remove_char(temp,'\"');
        args[i] = (char*)temp.c_str();
    }
    args[s.size()] = NULL;

    //creates fork process.
    pid_t pid = fork();

    if(pid == -1)
    {
        //fork didn't work.
        perror("fork");
    }
    if(pid ==0)
    {
        if(execvp(args[0], args) == -1)
        {
            //execute didn't work.
            perror("execvp");

            //break out of shadow realm.
            exit(1);
        }

    }
    if(pid > 0)
    {
        //wait for child to die.
        if(wait(0) == -1)
        {
            //didnt wait.
            perror("wait");
        }
    }

    return;
}

vector<string> parseInput(string s)
{

    //replace spaces.
    replace_char(s,' ','*');

    //make temp vector to hold parsed strings.
    vector<string> temp;

    //create boost magic function.
    char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);

    //create boost magic holder thingy.
    tokenizer< char_separator<char> > cm(s,sep);

    //for each loop to grab each peice and push it into a vector.
    for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
        if(*it != "")
        {
            //fix string.
            string temp_string = *it;
            replace_char(temp_string,'*',' ');
            temp.push_back(temp_string);
        }

    //return that vector.
    return temp;
}

void replace_char(string &s, char o, char r)
{
    //different use for the function.
    if(o == '\"')
    {
        //nothing to replace.
        if(s.find(o) == string::npos)
            return;

        //replace.
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        return;

    }

    //no quotes.
    if(s.find("\"") == string::npos)
        return;
    else if(s.find(o) == string::npos)
        return;

    //vector to hold quote positions.
    vector<int> pos;

    //place positions of char into vector.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == '\"')
            pos.push_back(i);

    //count position.
    unsigned int count = 0;

    //replace.
    while(count < pos.size())
    {
        for(int i = pos.at(count); i < pos.at(count+1); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        count++;
        count++;
    }

    return;
}

template<typename unit>
void display_vector(vector<unit> v)
{
    for(unsigned int i = 0; i < v.size(); ++i)
        cout << i+1 << ": " << v.at(i) << endl;
    return;
}

void remove_comment(string &s)
{
    //just add a " to the end to avoid errors.
    if(find_char_amount(s,'\"') % 2 != 0)
        s += '\"';

    //delete everything!
    if(s.find("#") == 0)
    {
        s = "";
        return;
    }

    //return if no comments.
    if(s.find("#") == string::npos)
    {
        return;
    }

    //if no comments then deletes everything from hash forward.
    if(s.find("\"") == string::npos && s.find("#") != string::npos)
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //if comment before quote then delete.
    if(s.find("\"") > s.find("#"))
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //advanced situations.
    //get a vector to hold positions of quotes and hash.
    vector<int> quotePos;
    vector<int> hashPos;

    //grab pos.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        if(s.at(i) == '\"')
            quotePos.push_back(i);
        else if(s.at(i) == '#')
            hashPos.push_back(i);
    }

    //no comments or hash for some reason.
    if(hashPos.size() == 0 || quotePos.size() == 0)
        return;

    //just in case.
    if(quotePos.size() % 2 != 0)
        quotePos.push_back(0);

    //overall check;
    vector<bool> check;

    //start it up.
    for(unsigned int i = 0; i < hashPos.size(); ++i)
        check.push_back(true);

    //check if hash is in quotes.
    for(unsigned int i = 0; i < hashPos.size(); ++i )
        for(unsigned int j = 0; j < quotePos.size(); j+=2 )
        {
            if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
            {
                check.at(i) = true;
                break;
            }
            else
                check.at(i) = false;
        }

    //check bool vector to delete string.
    for(unsigned int i = 0; i < check.size(); ++i)
        if(!check.at(i))
        {
            s = s.substr(0,hashPos.at(i));
            return;
        }

    //if comment at end then kill it.
    if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
        s = s.substr(0,hashPos.at(hashPos.size()-1));

    return;
}

int find_char_amount(const string s, char c)
{
    if(s.find(c) == string::npos)
        return 0;

    int count = 0;
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            count++;
    return count;

}

void remove_char(string &s, char c)
{
    //if not there then just return.
    if(s.find(c) == string::npos)
        return;

    //start empty.
    string temp = "";

    //add everything thats not what we dont want.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) != c)
            temp += s.at(i);

    //transfer to s.
    s = temp;

    return;
}

bool isFlag(string f)
{	//default list of possible flags
	string flags = "-e -d -f";
	//see if string is one of the flags
	if (flags.find(f) != string::npos)
		return true;
	return false;
}

/*
bool test(vector<string> &commands, vector<char*> &command_v)
{
	//defaults to "-e"
	string flag = "-e";

	struct stat s_thing;

	//put everything into a queue for ease of use
	queue<string> coms;
	for (unsigned int i = 0; i < commands.size(); i++)
	{
		coms.push_back(commands.at(i));
	}

	//was a bracket used for the test command?
	bool bracketUsed = false;

	//set if a bracket was used
	if(coms.front() == "[";
		bracketUsed = true;

	//remove the first part of the command regardless of whether it's "test" or "["
	coms.pop();

	if (isTestFlag(coms.front()))
	{
		flag = coms.front();
		//now we have the flag for the test
		coms.pop()
	}

	//if there's another flag attempt then it's broken
	if (coms.front().at(0) == "-")
	{
		cout << "ERROR: incorrect flags" << endl;

		//keep deleting from queue till the next command
		while (!is_connector(coms.front()))
		{
			coms.pop();
		}
		return true;
	}

	// if the first part of the path is a "/" remove it (that way it can't mess up)
	if(coms.front().at(0) == "/")
		commands.front().substr(1, commands.front().size() - 1);

	//make a new c_string to hold the file path
	char *filePath = new char[coms.front.size()];

	//copy it on over from the command vector
	strcpy(filePath, coms.front().c_str());
	command_v.push_back(filePath);

	//moving along
	coms.pop();

	//Did we use a bracket instead of "test"? If so get rid of the last bracket
	if(bracketUsed)
	{
		coms.pop();
	}

	//valuse for using the stat thingy
	int current_stat;

	//get the status of the command
	current_stat = stat(command_v.front(), &s_thing);

	//Did it fail?
	if(current_stat < 0)
	{
		//Yup it did
		perror("ERROR: Coudn't get the stat");
		return true;
	}
	//No it didn't so lets try out with "-e"
	if (flag == "-e")
	{
		return false;
	}

	//Try it out with "-f"
	if(flag == "-f")
	{
		if(S_ISREG(s_thing.st_mode))
		{
			return false
		} else
		{
			return true
		}
	}

	//Try it out with "-d"
	if (flag == "-d")
	{
		if (S_ISDIR(s_thing.st_mode))
		{
			return false;
		} else
		{
			return true
		}
	}
	//Obviously something went wrong if you got here
	return true
}*/

vector<Command> create_commands(const vector<string> &v)
{
    vector<Command> commandVector;
    Command temp;

    return commandVector;
}

<commit_msg>added the is_connector function<commit_after>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <sys/stat.h>

//getlogin() and gethostname().
#include <unistd.h>

//perror.
#include <stdio.h>

//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>

//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"

//that one class.
#include "Command.h"

using namespace std;
using namespace boost;

//execute command.
void execute(const vector<string> & s);

//replaces char in string.
void replace_char(string &s, char o, char r);

//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);

//display vector.
template<typename unit>
void display_vector(vector<unit> v);

//helper function that finds amount of character.
int find_char_amount(const string s,char c);

//removes comment from input.
void remove_comment(string &s);

//removes char in string.
void remove_char(string &s, char c);

//checks if string passed in contains a flag
bool isFlag(string f);

//creates command types from vector of strings.
vector<Command> create_commands(const vector<string> &v);

int main()
{
    //grab the login.
    char* login = getlogin();

    //start a flag.
    bool login_check = true;

    if((!login) != 0)
    {
        //check flag.
        login_check = false;

        //output error.
        perror("Error: could not retrieve login name");
    }

    //hold c-string for host name.
    char host[150];

    //start another flag.
    bool host_check = true;

    //gets hostname while checking if it actually grabbed it.
    if(gethostname(host,sizeof(host)) != 0)
    {
        //check flag.
        host_check = false;

        //output error.
        perror("Error: could not rerieve host name.");
    }

    //warn user of upcoming trouble.
    if(login_check == false || host_check == false)
        cout << "Unable to display login and/or host information." << endl;

    //string to hold user input.
    string input;

    while(true)
    {
        //output login@hostname.
        if(login_check && host_check)
            cout << login << '@' << host << ' ';

        //bash money.
        cout << "$ ";

        //placeholder to tell its the program.
        cout << " (program) ";

        //geting input as a string.
        getline(cin,input);

        //remove extra white space.
        trim(input);

        //remove comments.
        remove_comment(input);

        //trim again just in case.
        trim(input);

        //testing parse.
        cout << "Testing parse" << endl;
        display_vector(parseInput(input));

        //execute command.
        execute(parseInput(input));

    }

    cout << "End of program" << endl;

    return 0;
}

void execute(const vector<string> &s)
{
    //check to see if user wants to quit and its the only command.
    if(s.size() == 1)
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == "exit")
                exit(0);

    //c-string to hold command.
    char* args[2048];

    //place, remove comments and convert commands.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        string temp = s.at(i);
        remove_char(temp,'\"');
        args[i] = (char*)temp.c_str();
    }
    args[s.size()] = NULL;

    //creates fork process.
    pid_t pid = fork();

    if(pid == -1)
    {
        //fork didn't work.
        perror("fork");
    }
    if(pid ==0)
    {
        if(execvp(args[0], args) == -1)
        {
            //execute didn't work.
            perror("execvp");

            //break out of shadow realm.
            exit(1);
        }

    }
    if(pid > 0)
    {
        //wait for child to die.
        if(wait(0) == -1)
        {
            //didnt wait.
            perror("wait");
        }
    }

    return;
}

vector<string> parseInput(string s)
{

    //replace spaces.
    replace_char(s,' ','*');

    //make temp vector to hold parsed strings.
    vector<string> temp;

    //create boost magic function.
    char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);

    //create boost magic holder thingy.
    tokenizer< char_separator<char> > cm(s,sep);

    //for each loop to grab each peice and push it into a vector.
    for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
        if(*it != "")
        {
            //fix string.
            string temp_string = *it;
            replace_char(temp_string,'*',' ');
            temp.push_back(temp_string);
        }

    //return that vector.
    return temp;
}

void replace_char(string &s, char o, char r)
{
    //different use for the function.
    if(o == '\"')
    {
        //nothing to replace.
        if(s.find(o) == string::npos)
            return;

        //replace.
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        return;

    }

    //no quotes.
    if(s.find("\"") == string::npos)
        return;
    else if(s.find(o) == string::npos)
        return;

    //vector to hold quote positions.
    vector<int> pos;

    //place positions of char into vector.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == '\"')
            pos.push_back(i);

    //count position.
    unsigned int count = 0;

    //replace.
    while(count < pos.size())
    {
        for(int i = pos.at(count); i < pos.at(count+1); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        count++;
        count++;
    }

    return;
}

template<typename unit>
void display_vector(vector<unit> v)
{
    for(unsigned int i = 0; i < v.size(); ++i)
        cout << i+1 << ": " << v.at(i) << endl;
    return;
}

void remove_comment(string &s)
{
    //just add a " to the end to avoid errors.
    if(find_char_amount(s,'\"') % 2 != 0)
        s += '\"';

    //delete everything!
    if(s.find("#") == 0)
    {
        s = "";
        return;
    }

    //return if no comments.
    if(s.find("#") == string::npos)
    {
        return;
    }

    //if no comments then deletes everything from hash forward.
    if(s.find("\"") == string::npos && s.find("#") != string::npos)
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //if comment before quote then delete.
    if(s.find("\"") > s.find("#"))
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //advanced situations.
    //get a vector to hold positions of quotes and hash.
    vector<int> quotePos;
    vector<int> hashPos;

    //grab pos.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        if(s.at(i) == '\"')
            quotePos.push_back(i);
        else if(s.at(i) == '#')
            hashPos.push_back(i);
    }

    //no comments or hash for some reason.
    if(hashPos.size() == 0 || quotePos.size() == 0)
        return;

    //just in case.
    if(quotePos.size() % 2 != 0)
        quotePos.push_back(0);

    //overall check;
    vector<bool> check;

    //start it up.
    for(unsigned int i = 0; i < hashPos.size(); ++i)
        check.push_back(true);

    //check if hash is in quotes.
    for(unsigned int i = 0; i < hashPos.size(); ++i )
        for(unsigned int j = 0; j < quotePos.size(); j+=2 )
        {
            if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
            {
                check.at(i) = true;
                break;
            }
            else
                check.at(i) = false;
        }

    //check bool vector to delete string.
    for(unsigned int i = 0; i < check.size(); ++i)
        if(!check.at(i))
        {
            s = s.substr(0,hashPos.at(i));
            return;
        }

    //if comment at end then kill it.
    if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
        s = s.substr(0,hashPos.at(hashPos.size()-1));

    return;
}

int find_char_amount(const string s, char c)
{
    if(s.find(c) == string::npos)
        return 0;

    int count = 0;
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            count++;
    return count;

}

void remove_char(string &s, char c)
{
    //if not there then just return.
    if(s.find(c) == string::npos)
        return;

    //start empty.
    string temp = "";

    //add everything thats not what we dont want.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) != c)
            temp += s.at(i);

    //transfer to s.
    s = temp;

    return;
}

int is_connector(string s)
{
    if(s == ";")
		return 1;
	if(s == "&&")
		return 2;
	if(s == "||")
		return 3;

	return -1;
}

bool isFlag(string f)
{	//default list of possible flags
	string flags = "-e -d -f";
	//see if string is one of the flags
	if (flags.find(f) != string::npos)
		return true;
	return false;
}

/*
bool test(vector<string> &commands, vector<char*> &command_v)
{
	//defaults to "-e"
	string flag = "-e";

	struct stat s_thing;

	//put everything into a queue for ease of use
	queue<string> coms;
	for (unsigned int i = 0; i < commands.size(); i++)
	{
		coms.push_back(commands.at(i));
	}

	//was a bracket used for the test command?
	bool bracketUsed = false;

	//set if a bracket was used
	if(coms.front() == "[";
		bracketUsed = true;

	//remove the first part of the command regardless of whether it's "test" or "["
	coms.pop();

	if (isTestFlag(coms.front()))
	{
		flag = coms.front();
		//now we have the flag for the test
		coms.pop()
	}

	//if there's another flag attempt then it's broken
	if (coms.front().at(0) == "-")
	{
		cout << "ERROR: incorrect flags" << endl;

		//keep deleting from queue till the next command
		while (!is_connector(coms.front()))
		{
			coms.pop();
		}
		return true;
	}

	// if the first part of the path is a "/" remove it (that way it can't mess up)
	if(coms.front().at(0) == "/")
		commands.front().substr(1, commands.front().size() - 1);

	//make a new c_string to hold the file path
	char *filePath = new char[coms.front.size()];

	//copy it on over from the command vector
	strcpy(filePath, coms.front().c_str());
	command_v.push_back(filePath);

	//moving along
	coms.pop();

	//Did we use a bracket instead of "test"? If so get rid of the last bracket
	if(bracketUsed)
	{
		coms.pop();
	}

	//valuse for using the stat thingy
	int current_stat;

	//get the status of the command
	current_stat = stat(command_v.front(), &s_thing);

	//Did it fail?
	if(current_stat < 0)
	{
		//Yup it did
		perror("ERROR: Coudn't get the stat");
		return true;
	}
	//No it didn't so lets try out with "-e"
	if (flag == "-e")
	{
		return false;
	}

	//Try it out with "-f"
	if(flag == "-f")
	{
		if(S_ISREG(s_thing.st_mode))
		{
			return false
		} else
		{
			return true
		}
	}

	//Try it out with "-d"
	if (flag == "-d")
	{
		if (S_ISDIR(s_thing.st_mode))
		{
			return false;
		} else
		{
			return true
		}
	}
	//Obviously something went wrong if you got here
	return true
}*/

vector<Command> create_commands(const vector<string> &v)
{
    vector<Command> commandVector;
    Command temp;

    return commandVector;
}

<|endoftext|>


<commit_before>#include "encoder_app.h"
#include "encoding_task.h"
#include "riff_wave.h"

int main(int argc, char *argv[])
{
//    GMp3Enc::RiffWave w;
//    w.readWave("./temple_of_love-sisters_of_mercy.wav");

//    if (!w.isValid()) {
//        return -1;
//    }

//    GMp3Enc::EncodingTask *t = GMp3Enc::EncodingTask::create(
//                w, "./1.mp3", 0);

//    t->encode();

    GMp3Enc::EncoderApp app(argc, argv);
    return app.exec();
}
<commit_msg>Removed not needed comments<commit_after>#include "encoder_app.h"
#include "encoding_task.h"
#include "riff_wave.h"

int main(int argc, char *argv[])
{
    GMp3Enc::EncoderApp app(argc, argv);
    return app.exec();
}
<|endoftext|>


<commit_before>#include <iostream>

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "Constants.h"
#include "Path.h"
#include "AbstractView.h"
#include "ResourceManager.h"
#include "HIManager.h"
#include "Logs.h"

using namespace std;

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

    log_init();

    LOG(info)  << "Superteacher is starting";
    LOG(debug) << "SRC Directory: " << _SRC_DIR;
    LOG(debug) << "Install Prefix: " << _INSTALL_PREFIX;

    LOG(info) << "Opening window";
    LOG(debug) << "Window size: " << SCREEN_X_PXSIZE << "x" << SCREEN_Y_PXSIZE;

    ResourceManager resource = {};
    auto config = resource.get_json("conf.json");
    auto style = sf::Style::Default;

    if((bool)(*config)["video"]["fullscreen"]){
        style = sf::Style::Fullscreen;
    }

    sf::RenderWindow window(
            sf::VideoMode(SCREEN_X_PXSIZE, SCREEN_Y_PXSIZE),
            "SuperTeacher",
            style
    );

    window.setFramerateLimit(50);
    HIManager user_input = {&window};

    user_input.HIEvent_sig.connect([&window](HIEvent event)->void{
        switch(event) {
            case HIEvent::CLOSE:
                window.close();
                break;
            default:
                break;
        }
    });

    auto level = resource.get_json("levels/level.json");
    auto font = resource.get_font(FONT_INDIE_FLOWER);
    auto song = resource.get_music(SONG_1);

    sf::Text text("Hello SuperTeacher", *font, 50);
    text.move(25,25);
    const std::string bg = (*level)["background"];
    auto bg_texture = resource.get_texture("graphics/backgrounds/" + bg + ".png");
    bg_texture->setRepeated(true);

    sf::Sprite bg_sprite;
    bg_sprite.setTexture(*bg_texture);
    bg_sprite.setTextureRect(sf::IntRect(0,0,1920,1080));

    auto cloud_texture = resource.get_texture("graphics/tests/Items/cloud3.png");
    sf::Sprite cloud_sprite;
    cloud_sprite.setTexture(*cloud_texture);
    cloud_sprite.move(200,200);

    sf::Sprite cloud2_sprite;
    cloud2_sprite.setTexture(*cloud_texture);
    cloud2_sprite.move(400,175);

    std::string gr_name = (*level)["ground"]["name"];
    auto ground_texture = resource.get_texture("graphics/grounds/" + gr_name + "/top.png");
    ground_texture->setRepeated(true);
    sf::Sprite ground_sprite;
    ground_sprite.setTexture(*ground_texture);
    ground_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE));
    ground_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] )));

    auto ground_fill_texture = resource.get_texture("graphics/grounds/" + gr_name + "/fill.png");
    ground_fill_texture->setRepeated(true);
    sf::Sprite ground_fill_sprite;
    ground_fill_sprite.setTexture(*ground_fill_texture);
    ground_fill_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE*(SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] ) - 1));
    ground_fill_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] - 1 )));

    auto superteacher_texture = resource.get_texture("graphics/characters/superteacher.png");

    sf::Sprite superteacher;
    superteacher.setTexture(*superteacher_texture);
    superteacher.move(0,720 - ( BLOCK_PXSIZE * ((SCREEN_Y_BLOCKS) - (int)(*level)["ground"]["level"] )));

    user_input.HIEvent_sig.connect([&superteacher](HIEvent event)->void{
        switch(event) {
            case HIEvent::GO_LEFT:
                superteacher.move(-10,0);
                break;
            case HIEvent::GO_RIGHT:
                superteacher.move(10,0);
				break;
			case HIEvent::GO_UP:
				superteacher.move(0, -10);
				break;
			case HIEvent::GO_DOWN:
				superteacher.move(0, 10);
				break;
            default:
                break;
            }
    });

    song->play();
    while(window.isOpen()){

        user_input.process();

        window.clear(sf::Color::White);

        // Dessin

        window.draw(bg_sprite);
        window.draw(ground_sprite);
        window.draw(ground_fill_sprite);
        window.draw(cloud_sprite);
        window.draw(cloud2_sprite);
        window.draw(text);
        window.draw(superteacher);

        window.display();
    }

    LOG(info) << "Good bye, end of main process";
    return 0;
}
<commit_msg>Speed adjustment<commit_after>#include <iostream>

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "Constants.h"
#include "Path.h"
#include "AbstractView.h"
#include "ResourceManager.h"
#include "HIManager.h"
#include "Logs.h"

using namespace std;

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

    log_init();

    LOG(info)  << "Superteacher is starting";
    LOG(debug) << "SRC Directory: " << _SRC_DIR;
    LOG(debug) << "Install Prefix: " << _INSTALL_PREFIX;

    LOG(info) << "Opening window";
    LOG(debug) << "Window size: " << SCREEN_X_PXSIZE << "x" << SCREEN_Y_PXSIZE;

    ResourceManager resource = {};
    auto config = resource.get_json("conf.json");
    auto style = sf::Style::Default;

    if((bool)(*config)["video"]["fullscreen"]){
        style = sf::Style::Fullscreen;
    }

    sf::RenderWindow window(
            sf::VideoMode(SCREEN_X_PXSIZE, SCREEN_Y_PXSIZE),
            "SuperTeacher",
            style
    );

    window.setFramerateLimit(50);
    HIManager user_input = {&window};

    user_input.HIEvent_sig.connect([&window](HIEvent event)->void{
        switch(event) {
            case HIEvent::CLOSE:
                window.close();
                break;
            default:
                break;
        }
    });

    auto level = resource.get_json("levels/level.json");
    auto font = resource.get_font(FONT_INDIE_FLOWER);
    auto song = resource.get_music(SONG_1);

    sf::Text text("Hello SuperTeacher", *font, 50);
    text.move(25,25);
    const std::string bg = (*level)["background"];
    auto bg_texture = resource.get_texture("graphics/backgrounds/" + bg + ".png");
    bg_texture->setRepeated(true);

    sf::Sprite bg_sprite;
    bg_sprite.setTexture(*bg_texture);
    bg_sprite.setTextureRect(sf::IntRect(0,0,1920,1080));

    auto cloud_texture = resource.get_texture("graphics/tests/Items/cloud3.png");
    sf::Sprite cloud_sprite;
    cloud_sprite.setTexture(*cloud_texture);
    cloud_sprite.move(200,200);

    sf::Sprite cloud2_sprite;
    cloud2_sprite.setTexture(*cloud_texture);
    cloud2_sprite.move(400,175);

    std::string gr_name = (*level)["ground"]["name"];
    auto ground_texture = resource.get_texture("graphics/grounds/" + gr_name + "/top.png");
    ground_texture->setRepeated(true);
    sf::Sprite ground_sprite;
    ground_sprite.setTexture(*ground_texture);
    ground_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE));
    ground_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] )));

    auto ground_fill_texture = resource.get_texture("graphics/grounds/" + gr_name + "/fill.png");
    ground_fill_texture->setRepeated(true);
    sf::Sprite ground_fill_sprite;
    ground_fill_sprite.setTexture(*ground_fill_texture);
    ground_fill_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE*(SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] ) - 1));
    ground_fill_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] - 1 )));

    auto superteacher_texture = resource.get_texture("graphics/characters/superteacher.png");

    sf::Sprite superteacher;
    superteacher.setTexture(*superteacher_texture);
    superteacher.move(0,720 - ( BLOCK_PXSIZE * ((SCREEN_Y_BLOCKS) - (int)(*level)["ground"]["level"] )));

    user_input.HIEvent_sig.connect([&superteacher](HIEvent event)->void{
        switch(event) {
            case HIEvent::GO_LEFT:
                superteacher.move(-5,0);
                break;
            case HIEvent::GO_RIGHT:
                superteacher.move(5,0);
				break;
			case HIEvent::GO_UP:
				superteacher.move(0, -5);
				break;
			case HIEvent::GO_DOWN:
				superteacher.move(0, 5);
				break;
            default:
                break;
            }
    });

    song->play();
    while(window.isOpen()){

        user_input.process();

        window.clear(sf::Color::White);

        // Dessin

        window.draw(bg_sprite);
        window.draw(ground_sprite);
        window.draw(ground_fill_sprite);
        window.draw(cloud_sprite);
        window.draw(cloud2_sprite);
        window.draw(text);
        window.draw(superteacher);

        window.display();
    }

    LOG(info) << "Good bye, end of main process";
    return 0;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode)
		{
			close();
#if defined(_WIN32) && defined(UNICODE)
			std::wstring wpath(safe_convert(path.native_file_string()));
			m_fd = ::_wopen(
				wpath.c_str()
				, map_open_mode(mode)
				, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
			m_fd = ::_open(
#else
			m_fd = ::open(
#endif
				utf8_native(path.native_file_string()).c_str()
				, map_open_mode(mode)
#ifdef _WIN32
				, S_IREAD | S_IWRITE);
#else
				, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
			if (m_fd == -1)
			{
				std::stringstream msg;
				msg << "open failed: '" << path.native_file_string() << "'. "
					<< std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "read failed: " << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
			}
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "write failed: " << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
			}
			return ret;
		}

		bool set_size(size_type s)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				std::stringstream msg;
				msg << "ftruncate failed: '" << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m = 1)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "seek failed: '" << std::strerror(errno)
					<< "' fd: " << m_fd
					<< " offset: " << offset
					<< " seekdir: " << seekdir;
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return -1;
			}
			return ret;
		}

		size_type tell()
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			return _telli64(m_fd);
#else
			return lseek(m_fd, 0, SEEK_CUR);
#endif
		}

		std::string const& error() const
		{
			if (!m_error) m_error.reset(new std::string);
			return *m_error;
		}

		int m_fd;
		int m_open_mode;
		mutable boost::scoped_ptr<std::string> m_error;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m)
		: m_impl(new impl(p, m.m_mask))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m)
	{
		return m_impl->open(p, m.m_mask);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes)
	{
		return m_impl->write(buf, num_bytes);
	}

	size_type file::read(char* buf, size_type num_bytes)
	{
		return m_impl->read(buf, num_bytes);
	}

	bool file::set_size(size_type s)
	{
		return m_impl->set_size(s);
	}

	size_type file::seek(size_type pos, file::seek_mode m)
	{
		return m_impl->seek(pos, m.m_val);
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}

	std::string const& file::error() const
	{
		return m_impl->error();
	}

}
<commit_msg>removed hard coded file permission bits<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode)
		{
			close();
#if defined _WIN32 && defined UNICODE
			std::wstring wpath(safe_convert(path.native_file_string()));
			m_fd = ::_wopen(
				wpath.c_str()
				, map_open_mode(mode));
#elif defined _WIN32
			m_fd = ::_open(
				utf8_native(path.native_file_string()).c_str()
				, map_open_mode(mode));
#else
			m_fd = ::open(
				utf8_native(path.native_file_string()).c_str()
				, map_open_mode(mode));
#endif
			if (m_fd == -1)
			{
				std::stringstream msg;
				msg << "open failed: '" << path.native_file_string() << "'. "
					<< std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "read failed: " << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
			}
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "write failed: " << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
			}
			return ret;
		}

		bool set_size(size_type s)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				std::stringstream msg;
				msg << "ftruncate failed: '" << std::strerror(errno);
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m = 1)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "seek failed: '" << std::strerror(errno)
					<< "' fd: " << m_fd
					<< " offset: " << offset
					<< " seekdir: " << seekdir;
				if (!m_error) m_error.reset(new std::string);
				*m_error = msg.str();
				return -1;
			}
			return ret;
		}

		size_type tell()
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			return _telli64(m_fd);
#else
			return lseek(m_fd, 0, SEEK_CUR);
#endif
		}

		std::string const& error() const
		{
			if (!m_error) m_error.reset(new std::string);
			return *m_error;
		}

		int m_fd;
		int m_open_mode;
		mutable boost::scoped_ptr<std::string> m_error;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m)
		: m_impl(new impl(p, m.m_mask))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m)
	{
		return m_impl->open(p, m.m_mask);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes)
	{
		return m_impl->write(buf, num_bytes);
	}

	size_type file::read(char* buf, size_type num_bytes)
	{
		return m_impl->read(buf, num_bytes);
	}

	bool file::set_size(size_type s)
	{
		return m_impl->set_size(s);
	}

	size_type file::seek(size_type pos, file::seek_mode m)
	{
		return m_impl->seek(pos, m.m_val);
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}

	std::string const& file::error() const
	{
		return m_impl->error();
	}

}
<|endoftext|>


<commit_before>#include <iostream>

#include "model.hpp"
#include "scanner.hpp"
#include "tokenizer.hpp"

int main()
{
	model::Stack stack, stack2;

	stack.push(new model::Integer(1));
	stack.push(new model::Integer(2));

	stack2.push(new model::Integer(3));
	stack2.push(new model::Integer(4));

	// スタックの内容確認
	std::cout << "stack: " << stack.to_string() << std::endl;
	std::cout << "stack2: " << stack2.to_string() << std::endl;

	//////////////////

	// オーバーライドの確認
	model::Integer a(321);
	model::Integer b(123);

	std::cout << "321 + 123 = " << a.add(&b)->cast<model::Integer>()->get_data() << std::endl;

	// スタックの結合確認
	std::cout << "[ " << stack.to_string() << "] + [ " << stack2.to_string() << "] = ";
	stack += stack2;
	std::cout << stack.to_string() << std::endl;

	// 関数実行確認
	model::Instruction inst = model::Instruction::INST_PLUS;
	inst.applicate(stack);
	std::cout << "3 + 4 = " << stack.back()->cast<model::Integer>()->get_data() << std::endl;

	// スタックの内容確認
	/*
	stack.pop();
	stack.pop();

	int i;
	for (i = 0; i < 100; i++) {
		stack.push(new model::Integer(i));
	}
	std::cout << "stack: " << stack.to_string() << std::endl;
	for (i = 0; i < 100; i++) {
		std::cout << ((model::Integer*)(stack.pop()))->data << std::endl;
	}
	*/

	// stack1
	// std::cout << stack.at(-1) << std::endl;
	//

	// Lexer testing
	lexer::Tokenizer tokenizer("3 4");
	model::Stack stack3 = tokenizer.tokenize().to_stack();
	std::cout << "stack3: " << stack3.to_string() << std::endl;

	// applicate check
	lexer::Tokenizer tokenizer2("1 2 3 4 5 6 7 8 9 10");
	model::Stack stack4 = tokenizer2.tokenize().to_stack();

	std::cout << "stack4: " << stack4.to_string() << std::endl;

	while (stack4.size() > 1) {
		model::Instruction(model::Instruction::INST_PLUS).applicate(stack4);
	}

	std::cout << "stack4: " << stack4.to_string() << std::endl;

	// String Tokenize Test
	lexer::Tokenizer tokenizer3("1 2 3 + 4 \"string data example\" 12 34");
	std::cout << "string data: " << tokenizer3.tokenize().to_stack().to_string() << std::endl;

	// REPL
	std::string input;
	model::Stack stack5;
	lexer::TokenVector tokvec;

	while (true) {
		std::cout << std::endl << "Input> ";
		std::getline(std::cin, input);

		lexer::Tokenizer* p_tokenizer = new lexer::Tokenizer(input);
		tokvec = p_tokenizer->tokenize();

		for (auto& tok : tokvec) {
			if (tok.type == tokentype::T_INST_PLUS
				|| tok.type == tokentype::T_INST_MINUS
				|| tok.type == tokentype::T_INST_MULTIPLICATION
				|| tok.type == tokentype::T_INST_DIVISION
				) {
				if (stack5.size() > 1) {
					tok.to_element()->cast<model::Instruction>()->applicate(stack5);
				} else {
					std::cout << "Cannot Applicate Instruction" << std::endl;
				}
			} else if (tok.type == tokentype::T_INTEGER
						|| tok.type == tokentype::T_FLOAT
						|| tok.type == tokentype::T_STRING
						|| tok.type == tokentype::T_NIL
				) {
				stack5.push(tok.to_element());
			} else {
				std::cout << "Unknown TokenType" << std::endl;
			}
		}
		delete p_tokenizer;

		std::cout << "Data Stack: " << stack5.to_string() << std::endl;
	}

	return 0;
}
<commit_msg>comment out test code<commit_after>#include <iostream>

#include "model.hpp"
#include "scanner.hpp"
#include "tokenizer.hpp"

int main()
{
	/*
	model::Stack stack, stack2;

	stack.push(new model::Integer(1));
	stack.push(new model::Integer(2));

	stack2.push(new model::Integer(3));
	stack2.push(new model::Integer(4));

	// スタックの内容確認
	std::cout << "stack: " << stack.to_string() << std::endl;
	std::cout << "stack2: " << stack2.to_string() << std::endl;

	//////////////////

	// オーバーライドの確認
	model::Integer a(321);
	model::Integer b(123);

	std::cout << "321 + 123 = " << a.add(&b)->cast<model::Integer>()->get_data() << std::endl;

	// スタックの結合確認
	std::cout << "[ " << stack.to_string() << "] + [ " << stack2.to_string() << "] = ";
	stack += stack2;
	std::cout << stack.to_string() << std::endl;

	// 関数実行確認
	model::Instruction inst = model::Instruction::INST_PLUS;
	inst.applicate(stack);
	std::cout << "3 + 4 = " << stack.back()->cast<model::Integer>()->get_data() << std::endl;
	*/

	// スタックの内容確認
	/*
	stack.pop();
	stack.pop();

	int i;
	for (i = 0; i < 100; i++) {
		stack.push(new model::Integer(i));
	}
	std::cout << "stack: " << stack.to_string() << std::endl;
	for (i = 0; i < 100; i++) {
		std::cout << ((model::Integer*)(stack.pop()))->data << std::endl;
	}
	*/

	/*
	// stack1
	// std::cout << stack.at(-1) << std::endl;
	//

	// Lexer testing
	lexer::Tokenizer tokenizer("3 4");
	model::Stack stack3 = tokenizer.tokenize().to_stack();
	std::cout << "stack3: " << stack3.to_string() << std::endl;

	// applicate check
	lexer::Tokenizer tokenizer2("1 2 3 4 5 6 7 8 9 10");
	model::Stack stack4 = tokenizer2.tokenize().to_stack();

	std::cout << "stack4: " << stack4.to_string() << std::endl;

	while (stack4.size() > 1) {
		model::Instruction(model::Instruction::INST_PLUS).applicate(stack4);
	}

	std::cout << "stack4: " << stack4.to_string() << std::endl;

	// String Tokenize Test
	lexer::Tokenizer tokenizer3("1 2 3 + 4 \"string data example\" 12 34");
	std::cout << "string data: " << tokenizer3.tokenize().to_stack().to_string() << std::endl;
	*/

	// REPL
	std::string input;
	model::Stack stack5;
	lexer::TokenVector tokvec;

	while (true) {
		std::cout << "Input> ";
		std::getline(std::cin, input);

		lexer::Tokenizer* p_tokenizer = new lexer::Tokenizer(input);
		tokvec = p_tokenizer->tokenize();

		for (auto& tok : tokvec) {
			if (tok.type == tokentype::T_INST_PLUS
				|| tok.type == tokentype::T_INST_MINUS
				|| tok.type == tokentype::T_INST_MULTIPLICATION
				|| tok.type == tokentype::T_INST_DIVISION
				) {
				if (stack5.size() > 1) {
					tok.to_element()->cast<model::Instruction>()->applicate(stack5);
				} else {
					std::cout << "Cannot Applicate Instruction" << std::endl;
				}
			} else if (tok.type == tokentype::T_INTEGER
						|| tok.type == tokentype::T_FLOAT
						|| tok.type == tokentype::T_STRING
						|| tok.type == tokentype::T_NIL
				) {
				stack5.push(tok.to_element());
			} else {
				std::cout << "Unknown TokenType" << std::endl;
			}
		}
		delete p_tokenizer;

		std::cout << "Data Stack: " << stack5.to_string() << std::endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>

using namespace std;

//Global Variable vectors
vector<int> connect_Pos; //holds the positions of possible connectors in prompt
vector<int> kinds_of_connect; //holds what kind of connector are in prompt

void possible_connector(string prompt,int size)
{
for(int x = 0; x < size; x++)
    {
        if(prompt.at(x)  == ';')
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(0);
        }
        else if(prompt[x] ==  '|' && (x + 1 < size &&  prompt[x + 1] == '|'))
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(1);
            kinds_of_connect.push_back(1);
            x++;
        }
        else if(prompt[x] == '&' && (x + 1 < size && prompt[x + 1] == '&'))
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(2);
            kinds_of_connect.push_back(2);
            x++;

        }
        else
        {
            kinds_of_connect.push_back(-1);
        }
    }
}

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

    char prompt_holder[50000];

    cout  << "$ ";
    string converter;                           //converts all bits of string into one piece
    string to_be_tokenized;
    getline(cin, to_be_tokenized);
    for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
    {
        prompt_holder[x] =  to_be_tokenized.at(x);
    }
    prompt_holder[to_be_tokenized.size()] = '\0';

    possible_connector(to_be_tokenized ,to_be_tokenized.size());

    int i = fork();
    if(i == 0)
    {
        if(-1 == execvp(prompt_holder, argv))
        {
            perror("execvp");
        }
    }
    else
    {
        cout << "hello world" << endl;
    }

    for(int x = 0; x < connect_Pos.size() ; x++)
    {
        cout << "Connect_pos: " << connect_Pos.at(x) << endl;
    }

    for(int x = 0; x < kinds_of_connect.size() ; x++)
    {
        cout << "kinds of connect: " << kinds_of_connect.at(x) << endl;
    }

}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<commit_msg>calling it a night, still having trouble with parsing through string, almost there though<commit_after>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>

using namespace std;

//Global Variable vectors
vector<int> connect_Pos; //holds the positions of possible connectors in prompt
vector<int> kinds_of_connect; //holds what kind of connector are in prompt

void possible_connector(string prompt,int size)
{
for(int x = 0; x < size; x++)
    {
        if(prompt.at(x)  == ';')
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(0);
        }
        else if(prompt[x] ==  '|' && (x + 1 < size &&  prompt[x + 1] == '|'))
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(1);
            kinds_of_connect.push_back(1);
            x++;
        }
        else if(prompt[x] == '&' && (x + 1 < size && prompt[x + 1] == '&'))
        {
            connect_Pos.push_back(x);
            kinds_of_connect.push_back(2);
            kinds_of_connect.push_back(2);
            x++;

        }
        else
        {
            kinds_of_connect.push_back(-1);
        }
    }
}

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

    vector <string> Vctr_of_commands;
    char prompt_holder[50000];//orginal array to hold prompt
    char *token;//used to break up using string tokenizer

    cout  << "$ ";
    string converter;                           //converts all bits of string into one piece
    string to_be_tokenized;
    getline(cin, to_be_tokenized);
    for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
    {
        prompt_holder[x] =  to_be_tokenized.at(x);
    }
    prompt_holder[to_be_tokenized.size()] = '\0';

    possible_connector(to_be_tokenized ,to_be_tokenized.size());

    token = (prompt_holder);
    cout << "output what is suppose to be tokenized" << endl;
    while(token != NULL)
    {
        cout << token << endl;
        char foo[10000] = {*token};
        string s(foo);
        cout << "output strings: " << s << endl;
        Vctr_of_commands.push_back(s);
        cout<< "What is suppose to output: "  << Vctr_of_commands[0] << endl;
        token = strtok(NULL, "|;&");
    }

    string finished_tok = strtok(prompt_holder, " &|;");

    int i = fork();
    if(i == 0)
    {
        if(-1 == execvp(prompt_holder, argv))
        {
            perror("execvp");
        }
    }
    else
    {
        cout << "hello world" << endl;
    }

    for(unsigned int x = 0; x < connect_Pos.size() ; x++)
    {
        cout << "Connect_pos: " << connect_Pos.at(x) << endl;
    }

    for(unsigned int x = 0; x < kinds_of_connect.size() ; x++)
    {
        cout << "kinds of connect: " << kinds_of_connect.at(x) << endl;
    }

}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<|endoftext|>


<commit_before>/*The MIT License (MIT)

JSPlay Copyright (c) 2015 Jens Malmborg

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 <script/script-engine.h>
#include <audio/audio-manager.h>
#include <gl/glew.h>
#include <glfw/glfw3.h>
#include <memory>

int main(int argc, char *argv[]) {
    if (!glfwInit()) {
        //
    }
    std::unique_ptr<AudioManager> audio;
    try {
        audio = std::unique_ptr<AudioManager>(new AudioManager(nullptr));
    }
    catch (std::exception& error) {
        //
    }
    ScriptEngine::current().Run(argv[1], argc, argv);
    glfwTerminate();
    return 0;
}<commit_msg>Fix for running without arguments.<commit_after>/*The MIT License (MIT)

JSPlay Copyright (c) 2015 Jens Malmborg

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 <script/script-engine.h>
#include <audio/audio-manager.h>
#include <gl/glew.h>
#include <glfw/glfw3.h>
#include <memory>
#include <iostream>

int main(int argc, char *argv[]) {
    if (argc == 1) {
        std::cout << "Script argument is missing" << std::endl;
        return 0;
    }
    if (!glfwInit()) {
        //
    }
    std::unique_ptr<AudioManager> audio;
    try {
        audio = std::unique_ptr<AudioManager>(new AudioManager(nullptr));
    }
    catch (std::exception& error) {
        //
    }
    ScriptEngine::current().Run(argv[1], argc, argv);
    glfwTerminate();
    return 0;
}<|endoftext|>


<commit_before>/*
This file is part of qNotesManager.

qNotesManager is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

qNotesManager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/

#include <QApplication>
#include <stdio.h>
#include <stdlib.h>

#include "mainwindow.h"

#include <QTextCodec>
#include "application.h"

using namespace qNotesManager;

void myMessageOutput(QtMsgType type, const char *msg);

bool errorOutput;

int main(int argc, char** argv) {
	QString helpScreenText = QString().append("Usage: \n").append(APPNAME).append(
			" [-v] [-h] [options] [file]\n"
			"-v, --version				Print version and exit.\n"
			"-h, --help				Print this screen\n"
			"Options:\n"
			"-s, --silent			Do not send data to stderr\n"
			"-fo FILE, --file-output FILE		Send debug output to file FILE\n\n"
			"file					File to open\n");
	errorOutput = true;

	QApplication app(argc, argv);
	app.setQuitOnLastWindowClosed(false);
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

	QStringList arguments = QCoreApplication::arguments();

	if (arguments.count() > 1) {
		arguments.removeAt(0);

		if (arguments.count() == 1) {
			QString arg = arguments.at(0);
			if (arg == "-v" || arg == "--version") {
				fprintf(stdout, "%s version: %s\n", APPNAME, VERSION); // FIXME: add actual version
				return 0;
			} else if (arg == "-h" || arg == "--help") {
				fprintf(stdout, qPrintable(helpScreenText));
				return 0;
			}
			if (arguments.contains("-no") || arguments.contains("--no-output")) {
				errorOutput = false;
			}
		}
	}

	qInstallMsgHandler(myMessageOutput);

	Application::I()->Settings.Load();
	MainWindow w;
	QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));
	if (Application::I()->Settings.ShowWindowOnStart) {
		w.show();
	} else {
		w.hide();
	}

	if (Application::I()->Settings.OpenLastDocumentOnStart &&
		!Application::I()->Settings.LastDocumentName.isEmpty()) {
		w.OpenDocument(Application::I()->Settings.LastDocumentName);
	}

	return app.exec();
}

void myMessageOutput(QtMsgType type, const char *msg) {
	if (!errorOutput) {
		if (type == QtFatalMsg) {
			abort();
		}
		return;
	}
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s\n", msg);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s\n", msg);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s\n", msg);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s\n", msg);
		abort();
	}
}
<commit_msg>Last opened file existence check added<commit_after>/*
This file is part of qNotesManager.

qNotesManager is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

qNotesManager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/

#include <QApplication>
#include <QTextCodec>
#include <QFileInfo>

#include <stdio.h>
#include <stdlib.h>

#include "mainwindow.h"
#include "application.h"

using namespace qNotesManager;

void myMessageOutput(QtMsgType type, const char *msg);

bool errorOutput;

int main(int argc, char** argv) {
	QString helpScreenText = QString().append("Usage: \n").append(APPNAME).append(
			" [-v] [-h] [options] [file]\n"
			"-v, --version				Print version and exit.\n"
			"-h, --help				Print this screen\n"
			"Options:\n"
			"-s, --silent			Do not send data to stderr\n"
			"-fo FILE, --file-output FILE		Send debug output to file FILE\n\n"
			"file					File to open\n");
	errorOutput = true;

	QApplication app(argc, argv);
	app.setQuitOnLastWindowClosed(false);
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

	QStringList arguments = QCoreApplication::arguments();

	if (arguments.count() > 1) {
		arguments.removeAt(0);

		if (arguments.count() == 1) {
			QString arg = arguments.at(0);
			if (arg == "-v" || arg == "--version") {
				fprintf(stdout, "%s version: %s\n", APPNAME, VERSION); // FIXME: add actual version
				return 0;
			} else if (arg == "-h" || arg == "--help") {
				fprintf(stdout, qPrintable(helpScreenText));
				return 0;
			}
			if (arguments.contains("-no") || arguments.contains("--no-output")) {
				errorOutput = false;
			}
		}
	}

	qInstallMsgHandler(myMessageOutput);

	Application::I()->Settings.Load();
	MainWindow w;
	QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));
	if (Application::I()->Settings.ShowWindowOnStart) {
		w.show();
	} else {
		w.hide();
	}

	if (Application::I()->Settings.OpenLastDocumentOnStart &&
		!Application::I()->Settings.LastDocumentName.isEmpty() &&
		QFileInfo(Application::I()->Settings.LastDocumentName).exists()) {
		w.OpenDocument(Application::I()->Settings.LastDocumentName);
	}

	return app.exec();
}

void myMessageOutput(QtMsgType type, const char *msg) {
	if (!errorOutput) {
		if (type == QtFatalMsg) {
			abort();
		}
		return;
	}
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s\n", msg);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s\n", msg);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s\n", msg);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s\n", msg);
		abort();
	}
}
<|endoftext|>


<commit_before>#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/heap/priority_queue.hpp>
#include <boost/graph/graphviz.hpp>
#include <gameai/point2.hpp>
#include <gameai/astar_vertex.hpp>

struct vertex_pos_t { typedef boost::vertex_property_tag kind; };
struct edge_label_t { typedef boost::edge_property_tag kind; };

typedef boost::property<vertex_pos_t, gameai::point2<int>> vertex_pos_p;
typedef boost::property<boost::vertex_name_t, unsigned int, vertex_pos_p> vertex_p;
typedef boost::property<boost::edge_weight_t, unsigned int> edge_p;
typedef boost::no_property graph_p;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_p, edge_p, graph_p> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
typedef gameai::astar_vertex<vertex_t> astar_vertex_t;

template<typename T> class inverse_comparator {
public:
	bool operator()(const T &lhs, const T &rhs) const {
		return lhs > rhs;
	}
};

int main(int argc, char **argv) {
	std::ifstream in("assets/graph.dot");

	graph_t g;
	boost::dynamic_properties dp(boost::ignore_other_properties);
	dp.property("node_id", boost::get(boost::vertex_name, g));
	dp.property("pos", boost::get(vertex_pos_t(), g));
	dp.property("label", boost::get(boost::edge_weight, g));

	boost::read_graphviz(in, g, dp);

	boost::unordered_map<int, vertex_t> vertex_map;
	BGL_FORALL_VERTICES(v, g, graph_t) {
		vertex_map.emplace(boost::get(boost::vertex_name, g, v), v);
	}

	/* a heap-based priority queue is used to retrive the lowest-cost open node in O(1)
	 * hash-based sets are used to lookup nodes in O(1)
	 */
	boost::heap::priority_queue<astar_vertex_t, boost::heap::compare<inverse_comparator<astar_vertex_t>>> open_heap;
	boost::unordered_set<astar_vertex_t> open_set;
	boost::unordered_set<astar_vertex_t> closed_set;

	astar_vertex_t v{0, 0, 1, vertex_map.at(1)};
	open_heap.emplace(v);
	open_set.emplace(v);

	while(!open_heap.empty()) {
		auto current = open_heap.top();
		open_heap.pop();
		open_set.erase(current);

		std::cout << boost::get(boost::vertex_name, g, current.vertex) << std::endl;

		BOOST_FOREACH(auto edge, boost::out_edges(current.vertex, g)) {
			auto target = boost::target(edge, g);
			auto n = boost::get(boost::vertex_name, g, target);
			if(n == 61) {
				/* contrary to popular belief, goto is perfectly safe in C++
				 * in fact, it conforms to C++ scope and object lifetime
				 * so this is a perfectly valid optimization
				 */
				goto end;
			}
			auto dist_to_here = gameai::distance_squared(boost::get(vertex_pos_t(), g, current.vertex),
			                                             boost::get(vertex_pos_t(), g, target));
			auto dist_to_end  = gameai::distance_squared(boost::get(vertex_pos_t(), g, target),
			                                             boost::get(vertex_pos_t(), g, vertex_map.at(61)));
			astar_vertex_t next{current.base_cost + dist_to_here, dist_to_end, n, target};
		}
		closed_set.emplace(current);
	}
end:
	return 0;
}
<commit_msg>main: finish implementing A*<commit_after>#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/heap/priority_queue.hpp>
#include <boost/graph/graphviz.hpp>
#include <gameai/point2.hpp>
#include <gameai/astar_vertex.hpp>

struct vertex_pos_t { typedef boost::vertex_property_tag kind; };
struct edge_label_t { typedef boost::edge_property_tag kind; };

typedef boost::property<vertex_pos_t, gameai::point2<int>> vertex_pos_p;
typedef boost::property<boost::vertex_name_t, unsigned int, vertex_pos_p> vertex_p;
typedef boost::property<boost::edge_weight_t, unsigned int> edge_p;
typedef boost::no_property graph_p;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_p, edge_p, graph_p> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
typedef gameai::astar_vertex<vertex_t> astar_vertex_t;

template<typename T> class inverse_comparator {
public:
	bool operator()(const T &lhs, const T &rhs) const {
		return lhs > rhs;
	}
};

int main(int argc, char **argv) {
	std::ifstream in("assets/graph.dot");

	graph_t g;
	boost::dynamic_properties dp(boost::ignore_other_properties);
	dp.property("node_id", boost::get(boost::vertex_name, g));
	dp.property("pos", boost::get(vertex_pos_t(), g));
	dp.property("label", boost::get(boost::edge_weight, g));

	boost::read_graphviz(in, g, dp);

	boost::unordered_map<int, vertex_t> vertex_map;
	BGL_FORALL_VERTICES(v, g, graph_t) {
		vertex_map.emplace(boost::get(boost::vertex_name, g, v), v);
	}

	/* a heap-based priority queue is used to retrive the lowest-cost open node in O(1)
	 * hash-based sets are used to lookup nodes in O(1)
	 */
	boost::heap::priority_queue<astar_vertex_t, boost::heap::compare<inverse_comparator<astar_vertex_t>>> open_heap;
	boost::unordered_set<astar_vertex_t> open_set;
	boost::unordered_set<astar_vertex_t> closed_set;

	astar_vertex_t v{0, 0, 1, vertex_map.at(1)};
	open_heap.emplace(v);
	open_set.emplace(v);

	while(!open_heap.empty()) {
		auto current = open_heap.top();
		open_heap.pop();
		open_set.erase(current);

		std::cout << boost::get(boost::vertex_name, g, current.vertex) << std::endl;

		BOOST_FOREACH(auto edge, boost::out_edges(current.vertex, g)) {
			auto target = boost::target(edge, g);
			auto n = boost::get(boost::vertex_name, g, target);
			if(n == 61) {
				/* contrary to popular belief, goto is perfectly safe in C++
				 * in fact, it conforms to C++ scope and object lifetime
				 * so this is a perfectly valid optimization
				 */
				goto end;
			}

			auto w = boost::get(boost::edge_weight, g, edge);
			auto dist_to_end  = gameai::distance_squared(boost::get(vertex_pos_t(), g, target),
			                                             boost::get(vertex_pos_t(), g, vertex_map.at(61)));
			astar_vertex_t next{current.base_cost + w, dist_to_end, n, target};

			auto open_find = open_set.find(next);
			if(open_find != open_set.end() && open_find->total_cost() < next.total_cost()) { continue; }

			auto closed_find = closed_set.find(next);
			if(closed_find != closed_set.end() && closed_find->total_cost() < next.total_cost()) { continue; }

			open_heap.emplace(next);
			open_set.emplace(next);
		}
		closed_set.emplace(current);
	}
end:
	std::cout << 61 << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>

#include "Emulator.hpp"

void printHelpMessage() {
    std::cout
        << "A NES emulator. Takes .nes files.\n\n"
        << "Usage: turbones [options] <path-to-rom-file>\n\n"
        << "Options:\n"
        << "\t-h  --help\n"
        << "\t\tPrint this help text and exit."
        << std::endl;
}

void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "-h"
            || arg == "--help") {
            printHelpMessage();
            exit(EXIT_SUCCESS);
        }
        else if (i == argc - 1) {
            emulator.rom_path = arg;
        }
        else {
            std::cerr << "Unrecognized argument: " << arg << std::endl; }
    }
}

int main(const int argc, char* argv[]) {
    Emulator emulator;
    handleArguments(argc, argv, emulator);

    try {
        emulator.run();
    }
    catch (const std::runtime_error& e) {
        std::cerr << "\nFailed to run (" << e.what() << "). Shutting down." << std::endl;
        // The pause here is to make sure the error can be read.
        std::cout << "Press Enter to exit . . . ";
        // Waits until Enter ('\n') is pressed. It turns out to be simpler
        // to write this portably, if we wait for Enter, rather than "any key".
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return EXIT_FAILURE;
    }
}<commit_msg>Extricate failure shutdown code into separate function<commit_after>#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>

#include "Emulator.hpp"

void printHelpMessage() {
    std::cout
        << "A NES emulator. Takes .nes files.\n\n"
        << "Usage: turbones [options] <path-to-rom-file>\n\n"
        << "Options:\n"
        << "\t-h  --help\n"
        << "\t\tPrint this help text and exit."
        << std::endl;
}

void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "-h"
             || arg == "--help") {
            printHelpMessage();
            exit(EXIT_SUCCESS);
        }
        else if (i == argc - 1) {
            emulator.rom_path = arg;
        }
        else {
            std::cerr << "Unrecognized argument: " << arg << std::endl; }
    }
}

// Prints failure message, and then waits until Enter ('\n') is pressed,
// so there's time for the message to be read, in case the console closes itself immediately afterwards.
// It turns out to be simpler to write this portably, if we wait for Enter, rather than "any key".
void printFailureAndWait(const std::runtime_error& e) {
    std::cerr
        << "\nFailed to run (" << e.what() << "). Shutting down.\n"
        << "Press Enter to exit . . . " << std::flush;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Wait for enter key.
}

int main(const int argc, char* argv[]) {
    Emulator emulator;
    handleArguments(argc, argv, emulator);

    try {
        emulator.run(); }
    catch (const std::runtime_error& e) {
        printFailureAndWait(e);
        return EXIT_FAILURE;
    }
}<|endoftext|>


<commit_before>/**
 * LED Strip host.
 *
 * Turns LEDs red (for now)
 */

#include "Arduino.h"
#include <FastLED.h>

#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif

#define NUM_LEDS 300
#define DATA_PIN 6

CRGB leds[NUM_LEDS];
int count = 0;

void setup()
{
  // Init fastled
  FastLED.addLeds<WS2812, DATA_PIN, BGR>(leds, NUM_LEDS);
}

void loop()
{
  int i;
  for (i=0;i<=count;i++)
    leds[i] = CRGB::Blue;

  for (;i<NUM_LEDS;i++)
    leds[i] = CRGB::White;

  count++;
  if (count >= NUM_LEDS)
    count = 0;

  FastLED.show();
  // wait for a second
  delay(100);
}
<commit_msg>Did something and worked.<commit_after>/**
 * LED Strip host.
 *
 * Turns LEDs red (for now)
 */

#include "Arduino.h"
#include <FastLED.h>

#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif

#define NUM_LEDS 300
#define DATA_PIN 6

CRGB leds[NUM_LEDS];
int count = 0;

void setup()
{
  // Init fastled
  pinMode(LED_BUILTIN, OUTPUT);

  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
  for (int i=0;i<NUM_LEDS;i++)
    leds[i] = CRGB::White;
  FastLED.show();
}

void loop()
{
  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);
  int i = 0;
  for (;i<count;i++)
    leds[i] = CRGB::Blue;
  for (;i<NUM_LEDS;i++)
    leds[i] = CRGB::Green;
  count = (count+1) % NUM_LEDS;

  FastLED.show();
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
  delay(100);
}
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>
#include <Espfc.h>
#include <Kalman.h>
#include <Madgwick.h>
#include <Mahony.h>
#include <printf.h>
#include <blackbox/blackbox.h>
#include <EspSoftSerial.h>
#include <EspGpio.h>
#include <EscDriver.h>
#include <EspWire.h>

#if defined(ESP32)
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <WiFi.h>
#if !CONFIG_FREERTOS_UNICORE
#define ESPFC_DUAL_CORE 1
#endif
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif

Espfc::Espfc espfc;

#if defined(ESPFC_DUAL_CORE)
void otherTask(void *pvParameters)
{
  while(true) espfc.updateOther();
}
#endif

void setup()
{
  espfc.begin();
  #if defined(ESPFC_DUAL_CORE)
  xTaskCreatePinnedToCore(otherTask, "otherTask", 8192, NULL, 1, NULL, 0); // run on PRO(0) core, loopTask is on APP(1)
  #endif
}

void loop()
{
  espfc.update();
  #if !defined(ESPFC_DUAL_CORE)
  espfc.updateOther();
  #endif
}<commit_msg>fixes #10 - esp32 disable core0 wdt<commit_after>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>
#include <Espfc.h>
#include <Kalman.h>
#include <Madgwick.h>
#include <Mahony.h>
#include <printf.h>
#include <blackbox/blackbox.h>
#include <EspSoftSerial.h>
#include <EspGpio.h>
#include <EscDriver.h>
#include <EspWire.h>

#if defined(ESP32)
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
//#include "esp_task_wdt.h"
#include <WiFi.h>
  #if !CONFIG_FREERTOS_UNICORE
    #define ESPFC_DUAL_CORE 1
    TaskHandle_t otherTaskHandle = NULL;
  #endif
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif

Espfc::Espfc espfc;

#if defined(ESPFC_DUAL_CORE)
void otherTask(void *pvParameters)
{
  //esp_task_wdt_add(otherTaskHandle);
  while(true)
  {
    //esp_task_wdt_reset();
    espfc.updateOther();
  }
}
#endif

void setup()
{
  espfc.begin();
  #if defined(ESPFC_DUAL_CORE)
  disableCore0WDT();
  xTaskCreatePinnedToCore(otherTask, "otherTask", 8192, NULL, 1, &otherTaskHandle, 0); // run on PRO(0) core, loopTask is on APP(1)
  #endif
}

void loop()
{
  espfc.update();
  #if !defined(ESPFC_DUAL_CORE)
  espfc.updateOther();
  #endif
}<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"

#include <memory>

#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"

namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
  // Print the whole module after each pass, which requires disabling
  // multi-threading as well.
  pm->getContext()->disableMultithreading();
  pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
      /*print_module_scope=*/true));
  pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
}  // namespace

namespace TFTPU {

namespace {
tensorflow::Status RunTPUBridge(
    ModuleOp module, bool enable_logging,
    llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
  PassManager bridge(module.getContext());
  ::tensorflow::applyTensorflowAndCLOptions(bridge);
  if (enable_logging || VLOG_IS_ON(1)) {
    tensorflow::DumpMlirOpToFile("tpu_bridge_before", module);
    if (VLOG_IS_ON(2)) EnableLogging(&bridge);
  }

  // Populate a passmanager with the list of passes that implement the bridge.
  pipeline_builder(bridge);

  // Add set of passes to lower back to graph (from tf_executor).
  TF::AddGraphExportLoweringPasses(bridge);

  // Run the bridge on the module, in case of failure, the `diag_handler`
  // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  if (enable_logging || VLOG_IS_ON(1))
    tensorflow::DumpMlirOpToFile("tpu_bridge_after", module);
  return diag_handler.ConsumeStatus();
}
}  // namespace

void CreateTPUBridgePipeline(OpPassManager &pm) {
  // The following ops must be preserved regardless of reachability. Ideally,
  // all graphs should have control dependencies to enforce this but this is
  // currently not the case (see b/177478741).
  const llvm::SmallVector<std::string, 4> ops_to_preserve = {
      "tf.TPUReplicateMetadata", "tf.TPUCompilationResult",
      "tf.TPUReplicatedInput", "tf.TPUReplicatedOutput"};
  pm.addNestedPass<FuncOp>(
      tf_executor::CreateTFExecutorGraphPruningPass(ops_to_preserve));
  // It is assumed at this stage there are no V1 control flow ops as Graph
  // functionalization is ran before import. Ops can be lifted out of
  // tf_executor dialect islands/graphs.
  pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
  // Run shape inference so that tf_executor/tf_device ops created later will
  // likely to inherit more concrete types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  pm.addNestedPass<FuncOp>(CreateTPUReorderReplicateAndPartitionedInputsPass());
  // Encode this in its own scope so that func_pm is not mistakenly used
  // later on.
  {
    pm.addPass(CreateTPUClusterFormationPass());
    OpPassManager &func_pm = pm.nest<FuncOp>();
    // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
    // because DecomposeResourceOpsPass uses pattern rewriter which hoists
    // changed constants out of tf_device.Launch.
    func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
    func_pm.addPass(CreateTPUHostComputationExpansionPass());
    func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
  }
  // Run another shape inference pass because resource decomposition might have
  // created new partial types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  // Note that the region-based control-flow produced here still contains
  // function call ops which get inlined by the subsequent inliner pass.
  pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
  pm.addPass(mlir::createInlinerPass());
  pm.addPass(CreateTPUClusterCleanupAttributesPass());
  pm.addPass(TFDevice::CreateResourceOpLiftingPass());
  pm.addNestedPass<FuncOp>(createCSEPass());
  pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
  pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
  pm.addPass(CreateTPUExtractOutsideCompilationPass());

  pm.addNestedPass<FuncOp>(TFDevice::CreateClusterConstantSinkingPass());
  pm.addPass(TF::CreateResourceDeviceInferencePass());
  pm.addPass(TFDevice::CreateClusterOutliningPass());
  pm.addPass(CreateTPUDynamicPaddingMapperPass());
  pm.addPass(CreateTPUResourceReadForWritePass());
  pm.addPass(CreateTPUShardingIdentificationPass());
  pm.addNestedPass<FuncOp>(CreateTPUResourceReadsWritesPartitioningPass());
  pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
  pm.addPass(CreateTPURewritePass());
  pm.addPass(createSymbolDCEPass());
  pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
  pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
  pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
  pm.addPass(CreateTPUVariableReformattingPass());
  pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}

void CreateTPUBridgePipelineV1(OpPassManager &pm) {
  pm.addPass(TF::CreateTFShapeInferencePass());
  // For V1 compatibility, we process a module where the graph does not have
  // feeds and fetched. We extract first the TPU computation in a submodule,
  // where it'll be in a function with args and returned values, much more like
  // a TF v2 module. We can then run the usual pipeline on this nested module.
  // Afterward we inline back in the parent module and delete the nested one.
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
  OpPassManager &nested_module = pm.nest<ModuleOp>();
  CreateTPUBridgePipeline(nested_module);
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}

tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}

}  // namespace TFTPU

namespace TF {

void AddGraphExportLoweringPasses(OpPassManager &pm) {
  auto add_pass = [&](std::unique_ptr<Pass> pass) {
    pm.addNestedPass<FuncOp>(std::move(pass));
    pm.addPass(CreateBreakUpIslandsPass());
  };

  add_pass(CreateFunctionalToExecutorDialectConversionPass());
  add_pass(TFDevice::CreateReplicateToIslandPass());
  add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
  add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
  pm.addNestedPass<FuncOp>(TFTPU::CreateTPUDevicePropagationPass());
  pm.addPass(createSymbolDCEPass());
  pm.addPass(CreateVerifySuitableForExportPass());
}

tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
                                                 bool enable_logging,
                                                 bool enable_inliner) {
  PassManager bridge(module.getContext());
  if (enable_logging || VLOG_IS_ON(1)) {
    tensorflow::DumpMlirOpToFile("standard_pipeline_before", module);
    if (VLOG_IS_ON(2)) EnableLogging(&bridge);
  }

  StandardPipelineOptions pipeline_options;
  pipeline_options.enable_inliner.setValue(enable_inliner);
  CreateTFStandardPipeline(bridge, pipeline_options);
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  if (enable_logging || VLOG_IS_ON(1))
    tensorflow::DumpMlirOpToFile("standard_pipeline_after", module);
  return diag_handler.ConsumeStatus();
}

}  // namespace TF
}  // namespace mlir
<commit_msg>Enable pass to drop shape_invariant attribute from while ops in bridge and perform shape inference and canonicalization after it.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"

#include <memory>

#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"

namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
  // Print the whole module after each pass, which requires disabling
  // multi-threading as well.
  pm->getContext()->disableMultithreading();
  pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
      /*print_module_scope=*/true));
  pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
}  // namespace

namespace TFTPU {

namespace {
tensorflow::Status RunTPUBridge(
    ModuleOp module, bool enable_logging,
    llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
  PassManager bridge(module.getContext());
  ::tensorflow::applyTensorflowAndCLOptions(bridge);
  if (enable_logging || VLOG_IS_ON(1)) {
    tensorflow::DumpMlirOpToFile("tpu_bridge_before", module);
    if (VLOG_IS_ON(2)) EnableLogging(&bridge);
  }

  // Populate a passmanager with the list of passes that implement the bridge.
  pipeline_builder(bridge);

  // Add set of passes to lower back to graph (from tf_executor).
  TF::AddGraphExportLoweringPasses(bridge);

  // Run the bridge on the module, in case of failure, the `diag_handler`
  // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  if (enable_logging || VLOG_IS_ON(1))
    tensorflow::DumpMlirOpToFile("tpu_bridge_after", module);
  return diag_handler.ConsumeStatus();
}
}  // namespace

void CreateTPUBridgePipeline(OpPassManager &pm) {
  // The following ops must be preserved regardless of reachability. Ideally,
  // all graphs should have control dependencies to enforce this but this is
  // currently not the case (see b/177478741).
  const llvm::SmallVector<std::string, 4> ops_to_preserve = {
      "tf.TPUReplicateMetadata", "tf.TPUCompilationResult",
      "tf.TPUReplicatedInput", "tf.TPUReplicatedOutput"};
  pm.addNestedPass<FuncOp>(
      tf_executor::CreateTFExecutorGraphPruningPass(ops_to_preserve));
  // It is assumed at this stage there are no V1 control flow ops as Graph
  // functionalization is ran before import. Ops can be lifted out of
  // tf_executor dialect islands/graphs.
  pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
  // Run shape inference so that tf_executor/tf_device ops created later will
  // likely to inherit more concrete types.
  pm.addPass(TF::CreateTFShapeInferencePass());
  pm.addNestedPass<FuncOp>(CreateTPUReorderReplicateAndPartitionedInputsPass());
  // Encode this in its own scope so that func_pm is not mistakenly used
  // later on.
  {
    pm.addPass(CreateTPUClusterFormationPass());
    OpPassManager &func_pm = pm.nest<FuncOp>();
    // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
    // because DecomposeResourceOpsPass uses pattern rewriter which hoists
    // changed constants out of tf_device.Launch.
    func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
    func_pm.addPass(CreateTPUHostComputationExpansionPass());
    func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
  }

  // Note that the region-based control-flow produced here still contains
  // function call ops which get inlined by the subsequent inliner pass.
  pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
  pm.addPass(mlir::createInlinerPass());
  pm.addNestedPass<FuncOp>(
      TF::CreateDropWhileShapeInvariantInDeviceClusterPass());
  // Run another shape inference pass because resource decomposition might have
  // created new partial types. Also, after dropping `shape_invariant` attribute
  // from While/WhileRegion ops within cluster would lead to more precise
  // shapes.
  pm.addPass(TF::CreateTFShapeInferencePass());
  pm.addNestedPass<FuncOp>(createCanonicalizerPass());
  pm.addPass(CreateTPUClusterCleanupAttributesPass());
  pm.addPass(TFDevice::CreateResourceOpLiftingPass());
  pm.addNestedPass<FuncOp>(createCSEPass());
  pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
  pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
  pm.addPass(CreateTPUExtractOutsideCompilationPass());

  pm.addNestedPass<FuncOp>(TFDevice::CreateClusterConstantSinkingPass());
  pm.addPass(TF::CreateResourceDeviceInferencePass());
  pm.addPass(TFDevice::CreateClusterOutliningPass());
  pm.addPass(CreateTPUDynamicPaddingMapperPass());
  pm.addPass(CreateTPUResourceReadForWritePass());
  pm.addPass(CreateTPUShardingIdentificationPass());
  pm.addNestedPass<FuncOp>(CreateTPUResourceReadsWritesPartitioningPass());
  pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
  pm.addPass(CreateTPURewritePass());
  pm.addPass(createSymbolDCEPass());
  pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
  pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
  pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
  pm.addPass(CreateTPUVariableReformattingPass());
  pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}

void CreateTPUBridgePipelineV1(OpPassManager &pm) {
  pm.addPass(TF::CreateTFShapeInferencePass());
  // For V1 compatibility, we process a module where the graph does not have
  // feeds and fetched. We extract first the TPU computation in a submodule,
  // where it'll be in a function with args and returned values, much more like
  // a TF v2 module. We can then run the usual pipeline on this nested module.
  // Afterward we inline back in the parent module and delete the nested one.
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
  OpPassManager &nested_module = pm.nest<ModuleOp>();
  CreateTPUBridgePipeline(nested_module);
  pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}

tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
  return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}

}  // namespace TFTPU

namespace TF {

void AddGraphExportLoweringPasses(OpPassManager &pm) {
  auto add_pass = [&](std::unique_ptr<Pass> pass) {
    pm.addNestedPass<FuncOp>(std::move(pass));
    pm.addPass(CreateBreakUpIslandsPass());
  };

  add_pass(CreateFunctionalToExecutorDialectConversionPass());
  add_pass(TFDevice::CreateReplicateToIslandPass());
  add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
  add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
  pm.addNestedPass<FuncOp>(TFTPU::CreateTPUDevicePropagationPass());
  pm.addPass(createSymbolDCEPass());
  pm.addPass(CreateVerifySuitableForExportPass());
}

tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
                                                 bool enable_logging,
                                                 bool enable_inliner) {
  PassManager bridge(module.getContext());
  if (enable_logging || VLOG_IS_ON(1)) {
    tensorflow::DumpMlirOpToFile("standard_pipeline_before", module);
    if (VLOG_IS_ON(2)) EnableLogging(&bridge);
  }

  StandardPipelineOptions pipeline_options;
  pipeline_options.enable_inliner.setValue(enable_inliner);
  CreateTFStandardPipeline(bridge, pipeline_options);
  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  LogicalResult result = bridge.run(module);
  (void)result;
  if (enable_logging || VLOG_IS_ON(1))
    tensorflow::DumpMlirOpToFile("standard_pipeline_after", module);
  return diag_handler.ConsumeStatus();
}

}  // namespace TF
}  // namespace mlir
<|endoftext|>