<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = directoryName;
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isL) {

		cout << 78 << endl;
		struct stat current;

		while ((direntp = readdir(dirp))) {

			//cout << "direntp: " << direntp << endl;
			if (-1 == (stat(direntp->d_name, &current))) {

				perror("stat failed");
				return -1;
			}
			if (direntp->d_name[0] == '-' && !isA)
				continue;
			else {

				if (current.st_mode & S_IFDIR)
					cout << "d";
				else if (current.st_mode & S_IFLNK)
					cout << "l";
				else if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
					cout << "-";

				if (current.st_mode & S_IRUSR)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWUSR)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXUSR)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IRGRP)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWGRP)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXGRP)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IROTH)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWOTH)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXOTH)
					cout << "x";
				else
					cout << "-";

			}
			cout << endl;

		}
		closedir(dirp);

	}

	else if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
		closedir(dirp);
	}
	return 0;
}

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

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			//cout << "directories: ";
			//for (unsigned i = 0; i < directories.size(); ++i)
				//cout << directories.at(i) << " ";
			//cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				//cout << 145 << endl;
				flags.clear();

				for (int k = directoryIndex.at(i) + 1; k < argc && !isDirectory(argv[k]); ++k) {
					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0 && directories.size() == 1) {
					//cout << 152 << endl;
					//cout << directories.at(i) << ":" << endl;
					ls(directoryName);
					cout << endl;
				}
				else if (flags.size() == 0) {
					//cout << 152 << endl;
					cout << directories.at(i) << ":" << endl;
					ls(directoryName);
					cout << endl;
				}
				else {
					cout << directories.at(i) << ":" << endl;
			   	if	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
					cout << endl;
				}

				delete [] directoryName;
			}
		}
	}

}

<commit_msg>added -l protection functionality<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = directoryName;
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isL) {

		cout << 78 << endl;
		struct stat current;

		while ((direntp = readdir(dirp))) {

			//cout << "direntp: " << direntp << endl;
			if (-1 == (stat(direntp->d_name, &current))) {

				perror("stat failed");
				return -1;
			}
			if (direntp->d_name[0] == '-' && !isA)
				continue;
			else {

				if (current.st_mode & S_IFDIR)
					cout << "d";

				if (current.st_mode & S_IFLNK)
					cout << "l";

				if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
					cout << "-";

				if (current.st_mode & S_IRUSR)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWUSR)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXUSR)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IRGRP)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWGRP)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXGRP)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IROTH)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWOTH)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXOTH)
					cout << "x";
				else
					cout << "-";

			}
			cout << endl;

		}
		closedir(dirp);

	}

	else if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
		closedir(dirp);
	}
	return 0;
}

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

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			//cout << "directories: ";
			//for (unsigned i = 0; i < directories.size(); ++i)
				//cout << directories.at(i) << " ";
			//cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				//cout << 145 << endl;
				flags.clear();

				for (int k = directoryIndex.at(i) + 1; k < argc && !isDirectory(argv[k]); ++k) {
					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0 && directories.size() == 1) {
					//cout << 152 << endl;
					//cout << directories.at(i) << ":" << endl;
					ls(directoryName);
					cout << endl;
				}
				else if (flags.size() == 0) {
					//cout << 152 << endl;
					cout << directories.at(i) << ":" << endl;
					ls(directoryName);
					cout << endl;
				}
				else {
					cout << directories.at(i) << ":" << endl;
			   	if	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
					cout << endl;
				}

				delete [] directoryName;
			}
		}
	}

}

<|endoftext|>


<commit_before>#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <sstream>
#include <set>

using namespace std;

struct classComp{
    bool operator()(char* a, char* b){
        int compare = strcmp(a, b);

        return compare <= 0;
    }
};

void readDirectories(const vector<string>& directories, const string& allFlags, int numOfDir);
void outputLS(char* dirName, const string& flags);
void displayFiles(const multiset<char*, classComp>& sortedFiles, bool hasL);

int main(int argc, char** argv)
{
    //Size I'll make vector after tranversing command line arguments
    int numOfDir = 0; stringstream dir;
    int numOfFlags = 0; stringstream flags;

    //Traversing command line here and populate stream for directories and flags
    for(unsigned i = 1; i < argc; i++){
        if(argv[i][0] != '-'){
            numOfDir++;
            dir << argv[i] << " ";
        }
        else{
            flags << argv[i];
        }
    }

    //Populate vector for directories
    vector<string> directories(numOfDir);
    for(unsigned i = 0; i < numOfDir; i++){
        dir >> directories.at(i);
    }

    //Populate string for flags
    string allFlags;
    flags >> allFlags;

    readDirectories(directories, allFlags, numOfDir);

    return 0;
}

//function to read directories
void readDirectories(const vector<string>& directories, const string& flags, int numOfDir){

    bool moreDir = numOfDir > 1;

    if(numOfDir == 0){
        char* dirName;
        dirName = (char*) ".";
        outputLS(dirName, flags);
    }

    //Loop through all directories inputted. Only once if no arguments.
    for(unsigned i = 0; numOfDir > 0; numOfDir--, i++){
        char* dirName;

        //If less than one, then current directory. Else, passed in directory.

        //Prints name of directory if multiple directories.
        if(moreDir){
            cout << directories.at(i) << ": " << endl;
        }
        dirName = (char*) directories.at(i).c_str();

        outputLS(dirName, flags);

        if(numOfDir > 1) cout << endl;
    }
}

//function to begin displaying all files in directory
void outputLS(char* dirName, const string& flags){
    //Opens directory name in "dirName"
    DIR *dirp = opendir(dirName);
    if(dirp == NULL){
        perror("opendir()");
        exit(-1);
    }

    bool hasA = false, hasL = false, hasR = false;

    for(int i = 0; i < flags.size(); i++){
        if(flags.at(i) == 'a') hasA = true;

        if(flags.at(i) == 'l') hasL = true;

        if(flags.at(i) == 'R') hasR = true;
    }

    //Reads contents of directory, saving contents and info into "dirent" struct
    dirent *direntp;
    multiset<char*, classComp> sortedFiles;
    int maxFileSize = 0;
    long numOfChars = 0;
    int compareSize = 0;

    //Branches to handle different flags.
    if(!hasR){
        while ((direntp = readdir(dirp))){
            if(direntp == NULL){
                perror("readdir");
                exit(-1);
            }
            if(!hasA && (direntp->d_name[0] != '.')){
                sortedFiles.insert(direntp->d_name); // use stat here to find attributes of file
            }
            else if(hasA){
                sortedFiles.insert(direntp->d_name);
            }

            compareSize = strlen(direntp->d_name);

            if(maxFileSize < compareSize)
                maxFileSize = compareSize;

            numOfChars += (compareSize + 1);
        }

        displayFiles(sortedFiles, hasL);
    }

    cout << endl;

    if(closedir(dirp) == -1){
        perror("closedir()");
    }
}

void displayFiles(const multiset<char*, classComp>& sortedFiles, bool hasL){

    if(!hasL){
        struct stat buf;

        for(multiset<char*, classComp>::iterator it = sortedFiles.begin(); it != sortedFiles.end(); it++){

            //Output for no or -a flag options with color
            if(stat(*it, &buf) == -1){
                perror("stat()");
                exit(-1);
            }

            if((*it)[0] == '.'){
                cout << "\033[2;47;33m";
            }

            if(S_ISDIR(buf.st_mode)){
                cout << "\033[1;34m";
            }

            cout << *it << "\033[0m" << '\t' <<  flush;
        }
    }
    else{
        struct stat buf;

        for(multiset<char*, classComp>::iterator it = sortedFiles.begin(); it != sortedFiles.end(); it++){
            if(stat(*it, &buf) == -1){
                perror("stat():");
                exit(-1);
            }

            //checks whether directory or file
            if(S_ISREG(buf.st_mode))
                cout << '-';
            else if(S_ISDIR(buf.st_mode))
                cout << 'd';

            //this will check for permissions for user

            (buf.st_mode & S_IRWXU & S_IRUSR) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXU & S_IWUSR) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXU & S_IXUSR) ? cout << 'x' : cout << '-';

            //this will check for permissions for groups

            (buf.st_mode & S_IRWXG & S_IRGRP) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXG & S_IWGRP) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXG & S_IXGRP) ? cout << 'x' : cout << '-';

            //this will check for permissions for all others

            (buf.st_mode & S_IRWXO & S_IROTH) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXO & S_IWOTH) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXO & S_IXOTH) ? cout << 'x' : cout << '-';

            //Used to get user name from user id
            struct passwd *pass;

            pass = getpwuid(buf.st_uid);
            if(pass == NULL){
                perror("getpwuid");
                exit(-1);
            }

            char* usr = pass->pw_name;

            //Used to get group name from group id
            struct group *gpass;

            gpass = getgrgid(buf.st_gid);
            if(gpass == NULL){
                perror("getgrgid");
            }

            char* grp = gpass->gr_name;

            //Used to get time format from time_t
            struct tm myTime;

            if(localtime_r(&buf.st_mtime, &myTime) == NULL){
                perror("localtime_r");
                exit(-1);
            }

            char month[5];
            char day[3];
            char time[6];

            if(strftime(month, sizeof(month), "%b", &myTime) == 0 || strftime(day, sizeof(day), "%d", &myTime) == 0 || strftime(time, sizeof(time), "%R", &myTime) == 0){
                perror("strftime");
                exit(-1);
            }

            //Output for -l flag with color

            cout << right <<  ' ' << buf.st_nlink << ' ' << usr << ' ' << grp << ' ' << setw (6) << buf.st_size << ' ' << month << ' ' << day << ' ' << time << ' ';
            if(S_ISDIR(buf.st_mode)){
                cout << "\033[1;34m";
            }

            if((*it)[0] == '.'){
                cout << "\033[2;47;33m";
            }

            cout << *it << "\033[0m" << endl;

        }
    }
}
<commit_msg>Just need to fix formatting<commit_after>#include <sys/types.h>
#include <math.h>
#include <list>
#include <grp.h>
#include <pwd.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <sstream>
#include <set>

using namespace std;

struct classComp{
    bool operator()(char* a, char* b){
        int compare = strcmp(a, b);

        return compare <= 0;
    }
};

void readDirectories(const vector<string>& directories, const string& allFlags, int numOfDir);
void outputLS(char* dirName, const string& flags, char* orig);
void displayFiles(const multiset<char*, classComp>& sortedFiles, bool hasL, string dirName, int maxFileSize, int compareSize);

int main(int argc, char** argv)
{
    //Size I'll make vector after tranversing command line arguments
    int numOfDir = 0; stringstream dir;
    int numOfFlags = 0; stringstream flags;

    //Traversing command line here and populate stream for directories and flags
    for(unsigned i = 1; i < argc; i++){
        if(argv[i][0] != '-'){
            numOfDir++;
            dir << argv[i] << " ";
        }
        else{
            flags << argv[i];
        }
    }

    //Populate vector for directories
    vector<string> directories(numOfDir);
    for(unsigned i = 0; i < numOfDir; i++){
        dir >> directories.at(i);
    }

    //Populate string for flags
    string allFlags;
    flags >> allFlags;

    readDirectories(directories, allFlags, numOfDir);

    return 0;
}

//function to read directories
void readDirectories(const vector<string>& directories, const string& flags, int numOfDir){

    bool moreDir = numOfDir > 1;

    if(numOfDir == 0){
        char* dirName;
        dirName = (char*) ".";
        outputLS(dirName, flags, dirName);
    }

    //Loop through all directories inputted. Only once if no arguments.
    for(unsigned i = 0; numOfDir > 0; numOfDir--, i++){
        char* dirName;

        //If less than one, then current directory. Else, passed in directory.

        //Prints name of directory if multiple directories.
        if(moreDir){
            cout << directories.at(i) << ": " << endl;
        }
        dirName = (char*) directories.at(i).c_str();

        outputLS(dirName, flags, dirName);

        if(numOfDir > 1) cout << endl;
    }
}

//function to begin displaying all files in directory
void outputLS(char* dirName, const string& flags, char* orig){
    //Opens directory name in "dirName"
    DIR *dirp = opendir(dirName);
    if(dirp == NULL){
        perror("opendir()");
        exit(-1);
    }

    bool hasA = false, hasL = false, hasR = false;

    for(int i = 0; i < flags.size(); i++){
        if(flags.at(i) == 'a') hasA = true;

        if(flags.at(i) == 'l') hasL = true;

        if(flags.at(i) == 'R') hasR = true;
    }

    //Reads contents of directory, saving contents and info into "dirent" struct
    dirent *direntp;
    multiset<char*, classComp> sortedFiles;
    int maxFileSize = 0;
    long numOfChars = 0;
    int compareSize = 0;
    list<string> dirs;
    string copy = dirName;

    //Branches to handle different flags.
    while ((direntp = readdir(dirp))){
        if(direntp == NULL){
            perror("readdir");
            exit(-1);
        }
        if(!hasA && (direntp->d_name[0] != '.')){
            sortedFiles.insert(direntp->d_name); // use stat here to find attributes of file
        }
        else if(hasA){
            sortedFiles.insert(direntp->d_name);
        }

        if(hasR && (direntp->d_type & DT_DIR) && strcmp(direntp->d_name, ".") && strcmp(direntp->d_name, "..")){
            dirs.push_back(direntp->d_name);
        }

        compareSize = strlen(direntp->d_name);

        if(maxFileSize < compareSize)
            maxFileSize = compareSize;

        numOfChars += (compareSize + 1);
    }

    if(hasR){
        cout << dirName << ":" << endl;
    }

    displayFiles(sortedFiles, hasL, copy, maxFileSize, compareSize);

    while(hasR && !dirs.empty()){
        cout << endl;
        if(!hasL) cout << endl;
        copy = dirName;
        copy += "/" + dirs.front();
        outputLS((char*) copy.c_str(), flags, orig);
        dirs.pop_front();
    }

    if(strcmp(dirName, orig) == 0 && !hasL) cout << endl;

    if(closedir(dirp) == -1){
        perror("closedir()");
    }
}

void displayFiles(const multiset<char*, classComp>& sortedFiles, bool hasL, string dirName, int maxFileSize, int compareSize){

    if(!hasL){
        struct stat buf;
        string copy = "";

        int rows = ceil((double) compareSize / maxFileSize);
        int columns = ceil((double) sortedFiles.size() / rows);

        for(multiset<char*, classComp>::iterator it = sortedFiles.begin(); it != sortedFiles.end(); it++){

            copy = dirName +  "/";
            copy += *it;

            //Output for no or -a flag options with color
            if(stat((char*) copy.c_str(), &buf) == -1){
                perror("stat()");
                exit(-1);
            }

            if((*it)[0] == '.'){
                cout << "\033[2;47;33m";
            }

            if(S_ISDIR(buf.st_mode)){
                cout << "\033[1;34m";
            }

            cout << *it << "\033[0m" << "  " <<  flush;
        }
    }
    else{
        struct stat buf;

        string copy = "";

        for(multiset<char*, classComp>::iterator it = sortedFiles.begin(); it != sortedFiles.end(); it++){

            copy = dirName + "/";
            copy += *it;

            if(stat((char*) copy.c_str(), &buf) == -1){
                perror("stat():");
                exit(-1);
            }

            //checks whether directory or file
            if(S_ISREG(buf.st_mode))
                cout << '-';
            else if(S_ISDIR(buf.st_mode))
                cout << 'd';

            //this will check for permissions for user

            (buf.st_mode & S_IRWXU & S_IRUSR) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXU & S_IWUSR) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXU & S_IXUSR) ? cout << 'x' : cout << '-';

            //this will check for permissions for groups

            (buf.st_mode & S_IRWXG & S_IRGRP) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXG & S_IWGRP) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXG & S_IXGRP) ? cout << 'x' : cout << '-';

            //this will check for permissions for all others

            (buf.st_mode & S_IRWXO & S_IROTH) ? cout << 'r' : cout << '-';
            (buf.st_mode & S_IRWXO & S_IWOTH) ? cout << 'w' : cout << '-';
            (buf.st_mode & S_IRWXO & S_IXOTH) ? cout << 'x' : cout << '-';

            //Used to get user name from user id
            struct passwd *pass;

            pass = getpwuid(buf.st_uid);
            if(pass == NULL){
                perror("getpwuid");
                exit(-1);
            }

            char* usr = pass->pw_name;

            //Used to get group name from group id
            struct group *gpass;

            gpass = getgrgid(buf.st_gid);
            if(gpass == NULL){
                perror("getgrgid");
            }

            char* grp = gpass->gr_name;

            //Used to get time format from time_t
            struct tm myTime;

            if(localtime_r(&buf.st_mtime, &myTime) == NULL){
                perror("localtime_r");
                exit(-1);
            }

            char month[5];
            char day[3];
            char time[6];

            if(strftime(month, sizeof(month), "%b", &myTime) == 0 || strftime(day, sizeof(day), "%d", &myTime) == 0 || strftime(time, sizeof(time), "%R", &myTime) == 0){
                perror("strftime");
                exit(-1);
            }

            //Output for -l flag with color

            cout << right <<  ' ' << buf.st_nlink << ' ' << usr << ' ' << grp << ' ' << setw (6) << buf.st_size << ' ' << month << ' ' << day << ' ' << time << ' ';
            if(S_ISDIR(buf.st_mode)){
                cout << "\033[1;34m";
            }

            if((*it)[0] == '.'){
                cout << "\033[2;47;33m";
            }

            cout << *it << "\033[0m" << endl;

        }
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
using namespace std;

void getpath(char *pathname, char *path, char name[]){
	strcpy(pathname, path);
	strcat(pathname, "/");
	strcat(pathname, name);
}

void changeColor(int background, struct stat fileStat){
	if(background == 1) cout<<"\x1b[47m";

	if(S_ISDIR(fileStat.st_mode))
		cout<<"\x1b[34m";
	else if(fileStat.st_mode & S_IXUSR)
		cout<<"\x1b[32m";
}

void resetColor(){
	cout<<"\x1b[0m";
}

void head(char path[], char name[], struct stat sb, int background){
	struct passwd *log;
	struct passwd *grp;
	struct tm * timeinfo;
	char buffer [80];

	log = getpwuid(sb.st_uid);
	if(log == '\0') perror("Login error");

	grp = getpwuid(sb.st_gid);
	if(grp == '\0') perror("Group error");

	timeinfo = localtime(&sb.st_mtime);
	strftime(buffer,80, "%b %e %H:%M",timeinfo);

	 printf( (S_ISDIR(sb.st_mode)) ? "d" : "-");
    	 printf( (sb.st_mode & S_IRUSR) ? "r" : "-");
    	 printf( (sb.st_mode & S_IWUSR) ? "w" : "-");
   	 printf( (sb.st_mode & S_IXUSR) ? "x" : "-");
   	 printf( (sb.st_mode & S_IRGRP) ? "r" : "-");
   	 printf( (sb.st_mode & S_IWGRP) ? "w" : "-");
    	 printf( (sb.st_mode & S_IXGRP) ? "x" : "-");
    	 printf( (sb.st_mode & S_IROTH) ? "r" : "-");
    	 printf( (sb.st_mode & S_IWOTH) ? "w" : "-");
   	 printf( (sb.st_mode & S_IXOTH) ? "x" : "-");

	cout<<" "<<sb.st_nlink<<" "
	    <<log->pw_name<<" "
	    <<grp->pw_name<<" "
	    <<sb.st_size<<" "
	    <<buffer<<" ";
	    changeColor(background,sb);
	    cout<<name;
	    resetColor();
	    cout<<endl;
}

void ls(char **argv, int flag, char directory[]){
	bool showFiles = false;
	DIR *dirp;
	if(!(dirp = opendir(directory))){
		perror("Opendir erro");
		return;
	}

	dirent *direntp;
	while((direntp = readdir(dirp))){

		if(errno != 0){
			 perror ("Readdir erro");
			 return;
		}

		char fullpath[512];

		getpath(fullpath, directory, direntp->d_name);

		struct stat fileStat;
		if(stat(fullpath, &fileStat) == -1){
			perror("Stat error");
			return;
		}

		switch(flag){
			//ls
			case 0:
				//avoid files starting with .
				if(direntp->d_name[0]!='.'){
					changeColor(0,fileStat);
					cout<<direntp->d_name<<"  ";
					resetColor();
				}
			break;

			//ls -a
			case 1:
				if(direntp->d_name[0]=='.')
					changeColor(1,fileStat);
				else
					changeColor(0,fileStat);

				cout<<direntp->d_name;
				resetColor();
				cout<<"  ";
			break;

			//ls -l
			case 2:
				//avoid files starting with .
				if(direntp->d_name[0]!='.')
					head(fullpath,direntp->d_name, fileStat,0);
			break;

			//ls -al
			case 3:
				if(direntp->d_name[0]=='.')
					head(fullpath, direntp->d_name,fileStat,1);
				else
					head(fullpath, direntp->d_name,fileStat,0);
			break;

			//ls -R
			case 4:
				//has this directory shown its files?
				if(!showFiles){
					showFiles = true;
					//show actual directory
					cout<<directory<<":"<<endl;
					//display its files
                                        ls(argv, 0, directory);
                                        cout<<endl;
				}
				//after showing the files, apply -R function
				//calling ls() to display the son directory
				if(direntp->d_type==DT_DIR){
					if(direntp->d_name[0]!='.'){
						//entry a level and call ls again
						ls(argv, flag,fullpath);
					}
				}
			break;

			//ls -aR
			case 5:
			break;

			//ls -lR
			case 6:
			break;

			//ls -laR
			case 7:
			break;
		}

	}
	closedir(dirp);
}

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

	char * find_flag;
	int flag=0;
	string path_folder="";

	//in case first parameter is not 'ls'
	if(memcmp(argv[1],"ls",2)!=0){
		cout<<"command not valid"<<endl;
		return 0;
	}

	for(int i=2; i<argc; i++){
		//checking how many flag are passed
		if(memcmp(argv[i],"-",1)==0){
			find_flag = strchr(argv[i],'a');
			if(find_flag != NULL){
				flag+= 1;
			}
			find_flag = strchr(argv[i],'l');
			if(find_flag != NULL){
				flag+=2;
			}
			find_flag = strchr(argv[i],'R');
			if(find_flag != NULL){
				flag+=4;
			}
		}else{
			//recieving folder as argument
			path_folder = argv[i];
		}
	}
	//if no folder has been passed as argument
	if(path_folder=="") path_folder = get_current_dir_name();

	char * directory = new char[path_folder.length()+1];
	strcpy(directory, path_folder.c_str());

	ls(argv, flag, directory);

        if(flag==0 || flag == 1) //formatting purpose
                cout<<endl;
	delete[] directory;

	return 0;
}
<commit_msg>ls -a -l -R working, printing colors<commit_after>#include <iostream>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
using namespace std;

void getpath(char *pathname, char *path, char name[]){
	strcpy(pathname, path);
	strcat(pathname, "/");
	strcat(pathname, name);
}

void changeColor(int background, struct stat fileStat){
	if(background == 1) cout<<"\x1b[47m";

	if(S_ISDIR(fileStat.st_mode))
		cout<<"\x1b[34m";
	else if(fileStat.st_mode & S_IXUSR)
		cout<<"\x1b[32m";
}

void resetColor(){
	cout<<"\x1b[0m";
}

void head(char path[], char name[], struct stat sb, int background){
	struct passwd *log;
	struct passwd *grp;
	struct tm * timeinfo;
	char buffer [80];

	log = getpwuid(sb.st_uid);
	if(log == '\0') perror("Login error");

	grp = getpwuid(sb.st_gid);
	if(grp == '\0') perror("Group error");

	timeinfo = localtime(&sb.st_mtime);
	strftime(buffer,80, "%b %e %H:%M",timeinfo);

	 printf( (S_ISDIR(sb.st_mode)) ? "d" : "-");
    	 printf( (sb.st_mode & S_IRUSR) ? "r" : "-");
    	 printf( (sb.st_mode & S_IWUSR) ? "w" : "-");
   	 printf( (sb.st_mode & S_IXUSR) ? "x" : "-");
   	 printf( (sb.st_mode & S_IRGRP) ? "r" : "-");
   	 printf( (sb.st_mode & S_IWGRP) ? "w" : "-");
    	 printf( (sb.st_mode & S_IXGRP) ? "x" : "-");
    	 printf( (sb.st_mode & S_IROTH) ? "r" : "-");
    	 printf( (sb.st_mode & S_IWOTH) ? "w" : "-");
   	 printf( (sb.st_mode & S_IXOTH) ? "x" : "-");

	cout<<" "<<sb.st_nlink<<" "
	    <<log->pw_name<<" "
	    <<grp->pw_name<<" "
	    <<sb.st_size<<" "
	    <<buffer<<" ";
	    changeColor(background,sb);
	    cout<<name;
	    resetColor();
	    cout<<endl;
}

void ls(int flag, char directory[]){
	bool showFiles = false;
	DIR *dirp;
	if(!(dirp = opendir(directory))){
		perror("Opendir erro");
		return;
	}

	dirent *direntp;
	while((direntp = readdir(dirp))){

		if(errno != 0){
			 perror ("Readdir erro");
			 return;
		}

		char fullpath[512];

		getpath(fullpath, directory, direntp->d_name);

		struct stat fileStat;
		if(stat(fullpath, &fileStat) == -1){
			perror("Stat error");
			return;
		}

		switch(flag){
			//ls
			case 0:
				//avoid files starting with .
				if(direntp->d_name[0]!='.'){
					changeColor(0,fileStat);
					cout<<direntp->d_name<<"  ";
					resetColor();
				}
			break;

			//ls -a
			case 1:
				if(direntp->d_name[0]=='.')
					changeColor(1,fileStat);
				else
					changeColor(0,fileStat);

				cout<<direntp->d_name;
				resetColor();
				cout<<"  ";
			break;

			//ls -l
			case 2:
				//avoid files starting with .
				if(direntp->d_name[0]!='.')
					head(fullpath,direntp->d_name, fileStat,0);
			break;

			//ls -al
			case 3:
				if(direntp->d_name[0]=='.')
					head(fullpath, direntp->d_name,fileStat,1);
				else
					head(fullpath, direntp->d_name,fileStat,0);
			break;

			//ls -R
			case 4:
				//has this directory shown its files?
				if(!showFiles){
					showFiles = true;
					//show actual directory
					cout<<directory<<":"<<endl;
					//display its files
                                        ls(0, directory);
                                        cout<<endl;
				}
				//after showing the files, apply -R function
				//calling ls() to display the son directory
				if(direntp->d_type==DT_DIR){
					if(direntp->d_name[0]!='.'){
                                                cout<<endl;
						//entry a level and call ls again
						ls(flag,fullpath);
                                        }
				}
			break;

			//ls -aR
			case 5:
				//has this directory shown its files?
				if(!showFiles){
					showFiles = true;
					//show actual directory
					cout<<directory<<":"<<endl;
					//display its files
                                        ls(1, directory);
                                        cout<<endl<<endl;
				}
				//after showing the files, apply -R function
				//calling ls() to display the son directory
				if(direntp->d_type==DT_DIR){
					if((direntp->d_name[0]=='.'&& direntp->d_name[1]=='\0') || (direntp->d_name[0]=='.' && direntp->d_name[1]=='.' && direntp->d_name[2]=='\0'));
                                        else{
						//entry a level and call ls again
						ls(flag,fullpath);
					}
				}
			break;

			//ls -lR
			case 6:
				//has this directory shown its files?
				if(!showFiles){
					showFiles = true;
					//show actual directory
					cout<<directory<<":"<<endl;
					//display its files
                                        ls( 2, directory);
                                        cout<<endl;
				}
				//after showing the files, apply -R function
				//calling ls() to display the son directory
				if(direntp->d_type==DT_DIR){
					if(direntp->d_name[0]!='.'){
						//entry a level and call ls again
						ls(flag,fullpath);
					}
				}
			break;

			//ls -laR
			case 7:
				//has this directory shown its files?
				if(!showFiles){
					showFiles = true;
					//show actual directory
					cout<<directory<<":"<<endl;
					//display its files
                                        ls(3, directory);
                                        cout<<endl;
				}
				//after showing the files, apply -R function
				//calling ls() to display the son directory
				if(direntp->d_type==DT_DIR){
					if((direntp->d_name[0]=='.'&& direntp->d_name[1]=='\0') || (direntp->d_name[0]=='.' && direntp->d_name[1]=='.' && direntp->d_name[2]=='\0'));
                                        else{
						//entry a level and call ls again
						ls(flag,fullpath);
					}
				}
			break;
		}

	}
	closedir(dirp);
}

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

	char * find_flag;
	int flag=0;
	string path_folder="";

	//in case first parameter is not 'ls'
	if(memcmp(argv[1],"ls",2)!=0){
		cout<<"first parameter must be ls"<<endl;
		return 0;
	}

	for(int i=2; i<argc; i++){
		//checking how many flag are passed
		if(memcmp(argv[i],"-",1)==0){
			find_flag = strchr(argv[i],'a');
			if(find_flag != NULL){
				flag+= 1;
			}
			find_flag = strchr(argv[i],'l');
			if(find_flag != NULL){
				flag+=2;
			}
			find_flag = strchr(argv[i],'R');
			if(find_flag != NULL){
				flag+=4;
			}
		}else{
			//recieving folder as argument
			path_folder = argv[i];
		}
	}
	//if no folder has been passed as argument
	if(path_folder=="") path_folder = get_current_dir_name();

	char * directory = new char[path_folder.length()+1];
	strcpy(directory, path_folder.c_str());

	ls(flag, directory);
        if(flag == 0 || flag ==1) cout<<endl;
	delete[] directory;

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_UTILS_THREAD_HPP
#define OUZEL_UTILS_THREAD_HPP

#include <system_error>
#include <thread>
#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__unix__) || defined(__APPLE__)
#  include <pthread.h>
#endif

namespace ouzel
{
    class Thread final
    {
    public:
        Thread() noexcept = default;

        Thread(const Thread&) = delete;
        Thread(Thread&& other) noexcept: t(std::move(other.t)) {}

        Thread(const std::thread&) = delete;
        Thread(std::thread&& other) noexcept: t(std::move(other)) {}

        Thread& operator=(const Thread&) = delete;
        Thread& operator=(Thread&& other) noexcept
        {
            t = std::move(other.t);
            return *this;
        }

        Thread& operator=(const std::thread&) = delete;
        Thread& operator=(std::thread&& other) noexcept
        {
            t = std::move(other);
            return *this;
        }

        template <typename Callable, typename... Args>
        explicit Thread(Callable&& f, Args&&... args):
            t(std::forward<Callable>(f), std::forward<Args>(args)...)
        {
        }

        ~Thread()
        {
            if (t.joinable()) t.join();
        }

        auto isJoinable() const noexcept { return t.joinable(); }
        auto getId() const noexcept { return t.get_id(); }
        auto getNativeHandle() { return t.native_handle(); }

        void join()
        {
            t.join();
        }

        void setPriority(float priority, bool realtime)
        {
#if defined(_MSC_VER)
            static_cast<void>(realtime);
            static constexpr int priorities[] = {
                THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL,
                THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL
            };

            if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)]))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to set thread name");
#else
            if (priority < 0.0F) priority = 0.0F;

            const int policy = realtime ? SCHED_RR : SCHED_OTHER;

            const int minPriority = sched_get_priority_min(policy);
            if (minPriority == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get thread min priority");
            const int maxPriority = sched_get_priority_max(policy);
            if (maxPriority == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get thread max priority");

            sched_param param;
            param.sched_priority = static_cast<int>(priority * (maxPriority - minPriority)) + minPriority;
            const int error = pthread_setschedparam(t.native_handle(), policy, &param);
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread priority");
#endif
        }

        static void setCurrentThreadName(const std::string& name)
        {
#if defined(_MSC_VER)
            constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;
#  pragma pack(push,8)
            typedef struct tagTHREADNAME_INFO
            {
                DWORD dwType; // Must be 0x1000.
                LPCSTR szName; // Pointer to name (in user addr space).
                DWORD dwThreadID; // Thread ID (-1=caller thread).
                DWORD dwFlags; // Reserved for future use, must be zero.
            } THREADNAME_INFO;
#  pragma pack(pop)

            THREADNAME_INFO info;
            info.dwType = 0x1000;
            info.szName = name.c_str();
            info.dwThreadID = static_cast<DWORD>(-1);
            info.dwFlags = 0;

            const DWORD numberOfArguments = sizeof(info) / sizeof(ULONG_PTR);
            ULONG_PTR arguments[numberOfArguments];
            std::memcpy(arguments, &info, sizeof(info));

            __try
            {
                RaiseException(MS_VC_EXCEPTION, 0, numberOfArguments, arguments);
            }
            __except (EXCEPTION_EXECUTE_HANDLER)
            {
            }
#else
#  ifdef __APPLE__
            const int error = pthread_setname_np(name.c_str());
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread name");
#  elif defined(__linux__)
            const int error = pthread_setname_np(pthread_self(), name.c_str());
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread name");
#  endif
#endif
        }

    private:
        std::thread t;
    };
}

#endif // OUZEL_UTILS_THREAD_HPP
<commit_msg>Add explicit cast to float<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_UTILS_THREAD_HPP
#define OUZEL_UTILS_THREAD_HPP

#include <system_error>
#include <thread>
#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__unix__) || defined(__APPLE__)
#  include <pthread.h>
#endif

namespace ouzel
{
    class Thread final
    {
    public:
        Thread() noexcept = default;

        Thread(const Thread&) = delete;
        Thread(Thread&& other) noexcept: t(std::move(other.t)) {}

        Thread(const std::thread&) = delete;
        Thread(std::thread&& other) noexcept: t(std::move(other)) {}

        Thread& operator=(const Thread&) = delete;
        Thread& operator=(Thread&& other) noexcept
        {
            t = std::move(other.t);
            return *this;
        }

        Thread& operator=(const std::thread&) = delete;
        Thread& operator=(std::thread&& other) noexcept
        {
            t = std::move(other);
            return *this;
        }

        template <typename Callable, typename... Args>
        explicit Thread(Callable&& f, Args&&... args):
            t(std::forward<Callable>(f), std::forward<Args>(args)...)
        {
        }

        ~Thread()
        {
            if (t.joinable()) t.join();
        }

        auto isJoinable() const noexcept { return t.joinable(); }
        auto getId() const noexcept { return t.get_id(); }
        auto getNativeHandle() { return t.native_handle(); }

        void join()
        {
            t.join();
        }

        void setPriority(float priority, bool realtime)
        {
#if defined(_MSC_VER)
            static_cast<void>(realtime);
            static constexpr int priorities[] = {
                THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL,
                THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL
            };

            if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)]))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to set thread name");
#else
            if (priority < 0.0F) priority = 0.0F;

            const int policy = realtime ? SCHED_RR : SCHED_OTHER;

            const int minPriority = sched_get_priority_min(policy);
            if (minPriority == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get thread min priority");
            const int maxPriority = sched_get_priority_max(policy);
            if (maxPriority == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get thread max priority");

            sched_param param;
            param.sched_priority = static_cast<int>(priority * static_cast<float>(maxPriority - minPriority)) + minPriority;
            const int error = pthread_setschedparam(t.native_handle(), policy, &param);
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread priority");
#endif
        }

        static void setCurrentThreadName(const std::string& name)
        {
#if defined(_MSC_VER)
            constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;
#  pragma pack(push,8)
            typedef struct tagTHREADNAME_INFO
            {
                DWORD dwType; // Must be 0x1000.
                LPCSTR szName; // Pointer to name (in user addr space).
                DWORD dwThreadID; // Thread ID (-1=caller thread).
                DWORD dwFlags; // Reserved for future use, must be zero.
            } THREADNAME_INFO;
#  pragma pack(pop)

            THREADNAME_INFO info;
            info.dwType = 0x1000;
            info.szName = name.c_str();
            info.dwThreadID = static_cast<DWORD>(-1);
            info.dwFlags = 0;

            const DWORD numberOfArguments = sizeof(info) / sizeof(ULONG_PTR);
            ULONG_PTR arguments[numberOfArguments];
            std::memcpy(arguments, &info, sizeof(info));

            __try
            {
                RaiseException(MS_VC_EXCEPTION, 0, numberOfArguments, arguments);
            }
            __except (EXCEPTION_EXECUTE_HANDLER)
            {
            }
#else
#  ifdef __APPLE__
            const int error = pthread_setname_np(name.c_str());
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread name");
#  elif defined(__linux__)
            const int error = pthread_setname_np(pthread_self(), name.c_str());
            if (error != 0)
                throw std::system_error(error, std::system_category(), "Failed to set thread name");
#  endif
#endif
        }

    private:
        std::thread t;
    };
}

#endif // OUZEL_UTILS_THREAD_HPP
<|endoftext|>


<commit_before>// evenement-cpp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "evenement/evenement.hpp"
#include "iostream"

using namespace evenement;

class Dog : public EventEmitter {
public:
	void bark()
	{
		std::cout << "Woof! Woof!" << std::endl;
	}
};

class Home : public EventEmitter {
	Dog _dog;
public:
	Home()
	{
		_dog.on("agression", [this](void* args) {_dog.bark(); });
	}

	void summonDog()
	{
		_dog.emit("agression");
	}
};

class Stranger {
	string _name;
public:
	Stranger(string name) :_name(name) {}

	void enter(Home home)
	{
		home.emit("enter", this);
	}

	const char* getName()
	{
		return _name.c_str();
	}
};

int main()
{
	Stranger stranger("Alice");
	Home home;

	home.on("enter", [&home](void* args) {
		auto enterer = static_cast<Stranger*>(args);
		std::cout << enterer->getName() << " just entered The Home! Summoning dog..." << std::endl;
		home.summonDog();
	});

	stranger.enter(home);

    return 0;
}

<commit_msg>redundant stuff<commit_after>#include "evenement/evenement.hpp"
#include "iostream"

using namespace evenement;

class Dog : public EventEmitter {
public:
	void bark()
	{
		std::cout << "Woof! Woof!" << std::endl;
	}
};

class Home : public EventEmitter {
	Dog _dog;
public:
	Home()
	{
		_dog.on("agression", [this](void* args) {_dog.bark(); });
	}

	void summonDog()
	{
		_dog.emit("agression");
	}
};

class Stranger {
	string _name;
public:
	Stranger(string name) :_name(name) {}

	void enter(Home home)
	{
		home.emit("enter", this);
	}

	const char* getName()
	{
		return _name.c_str();
	}
};

int main()
{
	Stranger stranger("Alice");
	Home home;

	home.on("enter", [&home](void* args) {
		auto enterer = static_cast<Stranger*>(args);
		std::cout << enterer->getName() << " just entered The Home! Summoning dog..." << std::endl;
		home.summonDog();
	});

	stranger.enter(home);

    return 0;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Monteverdi
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdAbstractLayerModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)
#include "ogr_spatialref.h"

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdAlgorithm.h"
#include "Core/mvdTypes.h"

namespace mvd
{
/*
  TRANSLATOR mvd::AbstractLayerModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
char const * const STR_SENSOR = QT_TRANSLATE_NOOP( "mvd::AbstractLayerModel", "Sensor" );
char const * const STR_UNKNOWN = QT_TRANSLATE_NOOP( "mvd::AbstractLayerModel", "Unknown" );
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/
SpatialReferenceType
GetSpatialReferenceType( const std::string & filename )
{
  DefaultImageFileReaderType::Pointer reader( DefaultImageFileReaderType::New() );
  assert( !reader.IsNull() );

  reader->SetFileName( filename );
  reader->UpdateOutputInformation();

  DefaultImageType * image = reader->GetOutput();
  assert( image!=NULL );

  return GetSpatialReferenceType(
    image->GetProjectionRef(),
    image->GetImageKeywordlist().GetSize()>0
  );
}

/*****************************************************************************/
SpatialReferenceType
GetSpatialReferenceType( const std::string & wkt, bool hasKwl )
{
  if( wkt.empty() )
    return
      hasKwl
      ? SRT_SENSOR
      : SRT_UNKNOWN;

  OGRSpatialReference ogr_sr( wkt.c_str() );

  const char * epsg = ogr_sr.GetAuthorityCode( "PROJCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return SRT_CARTO;

  epsg = ogr_sr.GetAuthorityCode( "GEOGCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return SRT_GEO;

  return SRT_UNKNOWN;
}

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */
/*****************************************************************************/
AbstractLayerModel
::AbstractLayerModel( QObject* parent ) :
  AbstractModel( parent ),
  VisibleInterface()
{
}

/*******************************************************************************/
AbstractLayerModel
::~AbstractLayerModel()
{
}

/*******************************************************************************/
SpatialReferenceType
AbstractLayerModel
::GetSpatialReferenceType() const
{
  return mvd::GetSpatialReferenceType( GetWkt(), HasKwl() );
}

/*******************************************************************************/
std::string
AbstractLayerModel
::GetWkt() const
{
  return virtual_GetWkt();
}

/*******************************************************************************/
std::string
AbstractLayerModel
::GetAuthorityCode( bool isEnhanced ) const
{
  std::string wkt( GetWkt() );

  if( wkt.empty() )
    return
      !isEnhanced
      ? std::string()
      : ( HasKwl()
	  ? ToStdString( tr( STR_SENSOR ) )
	  : ToStdString( tr( STR_UNKNOWN ) ) );

  OGRSpatialReference ogr_sr( wkt.c_str() );

  const char * epsg = ogr_sr.GetAuthorityCode( "PROJCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return epsg;

  epsg = ogr_sr.GetAuthorityCode( "GEOGCS" );

  assert( epsg!=NULL && strcmp( epsg, "" )!=0 );

  return epsg;
}

/*******************************************************************************/
bool
AbstractLayerModel
::HasKwl() const
{
  return virtual_HasKwl();
}

/*****************************************************************************/
void
AbstractLayerModel
::ToWgs84( const PointType & p, PointType & wgs84, double & alt) const
{
  virtual_ToWgs84( p, wgs84, alt );
}

/*******************************************************************************/
bool
AbstractLayerModel
::virtual_HasKwl() const
{
  return false;
}

/*******************************************************************************/
void
AbstractLayerModel
::virtual_SignalVisibilityChanged( bool isVisible )
{
  emit VisibilityChanged( isVisible );
  emit VisibilityChanged( this, isVisible );
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>ENH: Fixed 'basic_string::_S_construct null not valid' exception thrown in AbstractLayerModel::GetAuthorityCode()<commit_after>/*=========================================================================

  Program:   Monteverdi
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdAbstractLayerModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)
#include "ogr_spatialref.h"

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdAlgorithm.h"
#include "Core/mvdTypes.h"

namespace mvd
{
/*
  TRANSLATOR mvd::AbstractLayerModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
char const * const STR_SENSOR = QT_TRANSLATE_NOOP( "mvd::AbstractLayerModel", "Sensor" );
char const * const STR_UNKNOWN = QT_TRANSLATE_NOOP( "mvd::AbstractLayerModel", "Unknown" );
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/
SpatialReferenceType
GetSpatialReferenceType( const std::string & filename )
{
  DefaultImageFileReaderType::Pointer reader( DefaultImageFileReaderType::New() );
  assert( !reader.IsNull() );

  reader->SetFileName( filename );
  reader->UpdateOutputInformation();

  DefaultImageType * image = reader->GetOutput();
  assert( image!=NULL );

  return GetSpatialReferenceType(
    image->GetProjectionRef(),
    image->GetImageKeywordlist().GetSize()>0
  );
}

/*****************************************************************************/
SpatialReferenceType
GetSpatialReferenceType( const std::string & wkt, bool hasKwl )
{
  if( wkt.empty() )
    return
      hasKwl
      ? SRT_SENSOR
      : SRT_UNKNOWN;

  OGRSpatialReference ogr_sr( wkt.c_str() );

  const char * epsg = ogr_sr.GetAuthorityCode( "PROJCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return SRT_CARTO;

  epsg = ogr_sr.GetAuthorityCode( "GEOGCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return SRT_GEO;

  return SRT_UNKNOWN;
}

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */
/*****************************************************************************/
AbstractLayerModel
::AbstractLayerModel( QObject* parent ) :
  AbstractModel( parent ),
  VisibleInterface()
{
}

/*******************************************************************************/
AbstractLayerModel
::~AbstractLayerModel()
{
}

/*******************************************************************************/
SpatialReferenceType
AbstractLayerModel
::GetSpatialReferenceType() const
{
  return mvd::GetSpatialReferenceType( GetWkt(), HasKwl() );
}

/*******************************************************************************/
std::string
AbstractLayerModel
::GetWkt() const
{
  return virtual_GetWkt();
}

/*******************************************************************************/
std::string
AbstractLayerModel
::GetAuthorityCode( bool isEnhanced ) const
{
  std::string wkt( GetWkt() );

  if( wkt.empty() )
    return
      !isEnhanced
      ? std::string()
      : ( HasKwl()
	  ? ToStdString( tr( STR_SENSOR ) )
	  : ToStdString( tr( STR_UNKNOWN ) ) );

  OGRSpatialReference ogr_sr( wkt.c_str() );

  const char * epsg = ogr_sr.GetAuthorityCode( "PROJCS" );

  if( epsg!=NULL && strcmp( epsg, "" )!=0 )
    return epsg;

  epsg = ogr_sr.GetAuthorityCode( "GEOGCS" );

  if( epsg==NULL || strcmp( epsg, "" )==0 )
    return ToStdString( tr( STR_UNKNOWN ) );

  return epsg;
}

/*******************************************************************************/
bool
AbstractLayerModel
::HasKwl() const
{
  return virtual_HasKwl();
}

/*****************************************************************************/
void
AbstractLayerModel
::ToWgs84( const PointType & p, PointType & wgs84, double & alt) const
{
  virtual_ToWgs84( p, wgs84, alt );
}

/*******************************************************************************/
bool
AbstractLayerModel
::virtual_HasKwl() const
{
  return false;
}

/*******************************************************************************/
void
AbstractLayerModel
::virtual_SignalVisibilityChanged( bool isVisible )
{
  emit VisibilityChanged( isVisible );
  emit VisibilityChanged( this, isVisible );
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>#include <config.h>

#include <gtest/gtest.h>
#include <primitiv/function_impl.h>

namespace primitiv {
namespace functions {

class FunctionImplTest : public testing::Test {};

TEST_F(FunctionImplTest, CheckFail) {
  FAIL();
}

}  // namespace functions
}  // namespace primitiv
<commit_msg>add test fixtures and some unit tests for Function implementations.<commit_after>#include <config.h>

#include <vector>
#include <gtest/gtest.h>
#include <primitiv/cpu_device.h>
#include <primitiv/function_impl.h>
#include <test_utils.h>

using std::vector;

namespace primitiv {
namespace functions {

class FunctionImplTest_0Arg : public testing::Test {
protected:
  CPUDevice dev;
  vector<const Shape *> arg_shapes;
  vector<const Tensor *> arg_values;
  vector<Tensor *> arg_grads;
};

TEST_F(FunctionImplTest_0Arg, CheckInput) {
  const Shape ret_shape({2, 2}, 3);
  const vector<float> ret_data {1, 2, 3, 4, 0, 0, 0, 0, -1, -2, -3, -4};
  const Input node(ret_shape, &dev, ret_data);
  const Shape cur_shape = node.forward_shape(arg_shapes);
  const Tensor cur_value = node.forward(arg_values);
  const Tensor cur_grad = dev.constant(ret_shape, 1);
  // backward() has no effect.
  EXPECT_NO_THROW(node.backward(cur_value, cur_grad, arg_values, arg_grads));
  EXPECT_EQ("Input", node.name());
  EXPECT_EQ(ret_shape, cur_shape);
  EXPECT_TRUE(test_utils::vector_match(ret_data, cur_value.to_vector()));
}

class FunctionImplTest_1Arg : public testing::Test {
protected:
  virtual void SetUp() override {
    arg_shapes.emplace_back(new Shape({2, 2}, 3));
    arg_values.emplace_back(new Tensor(
        *arg_shapes[0], &dev,
        vector<float> {1, 2, 3, 4, 0, 0, 0, 0, -1, -2, -3, -4}));
    arg_grads.emplace_back(new Tensor(
        *arg_shapes[0], &dev, vector<float>(arg_shapes[0]->size())));
  }

  virtual void TearDown() override {
    for (const Shape *x : arg_shapes) delete x;
    for (const Tensor *x : arg_values) delete x;
    for (Tensor *x : arg_grads) delete x;
  }

  CPUDevice dev;
  vector<const Shape *> arg_shapes;
  vector<const Tensor *> arg_values;
  vector<Tensor *> arg_grads;
};

#define TEST_ALL(name_) { \
  const Shape cur_shape = node.forward_shape(arg_shapes); \
  const Tensor cur_value = node.forward(arg_values); \
  const Tensor cur_grad = dev.constant(ret_shape, 1); \
  node.backward(cur_value, cur_grad, arg_values, arg_grads); \
  EXPECT_EQ(#name_, node.name()); \
  EXPECT_EQ(ret_shape, cur_shape); \
  EXPECT_TRUE(test_utils::vector_match(ret_data, cur_value.to_vector())); \
  EXPECT_TRUE(test_utils::vector_match(bw_grad, arg_grads[0]->to_vector())); \
}

TEST_F(FunctionImplTest_1Arg, CheckAddConst) {
  const Shape ret_shape({2, 2}, 3);
  const vector<float> ret_data {4, 5, 6, 7, 3, 3, 3, 3, 2, 1, 0, -1};
  const vector<float> bw_grad(arg_shapes[0]->size(), 1);
  const AddConst node(3);
  TEST_ALL(AddConst);
}

#undef TEST_ALL

class FunctionImplTest_2Args : public testing::Test {
protected:
  virtual void SetUp() override {
    arg_shapes.emplace_back(new Shape({2, 2}, 3));
    arg_shapes.emplace_back(new Shape({2, 2}, 3));
    arg_values.emplace_back(new Tensor(
        *arg_shapes[0], &dev,
        vector<float> {1, 2, 3, 4, 0, 0, 0, 0, -1, -2, -3, -4}));
    arg_values.emplace_back(new Tensor(
        *arg_shapes[1], &dev,
        vector<float> {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}));
    arg_grads.emplace_back(new Tensor(
        *arg_shapes[0], &dev, vector<float>(arg_shapes[0]->size())));
    arg_grads.emplace_back(new Tensor(
        *arg_shapes[1], &dev, vector<float>(arg_shapes[1]->size())));
  }

  virtual void TearDown() override {
    for (const Shape *x : arg_shapes) delete x;
    for (const Tensor *x : arg_values) delete x;
    for (Tensor *x : arg_grads) delete x;
  }

  CPUDevice dev;
  vector<const Shape *> arg_shapes;
  vector<const Tensor *> arg_values;
  vector<Tensor *> arg_grads;
};

#define TEST_ALL(name_) { \
  const Shape cur_shape = node.forward_shape(arg_shapes); \
  const Tensor cur_value = node.forward(arg_values); \
  const Tensor cur_grad = dev.constant(ret_shape, 1); \
  node.backward(cur_value, cur_grad, arg_values, arg_grads); \
  EXPECT_EQ(#name_, node.name()); \
  EXPECT_EQ(ret_shape, cur_shape); \
  EXPECT_TRUE(test_utils::vector_match(ret_data, cur_value.to_vector())); \
  EXPECT_TRUE( \
      test_utils::vector_match(bw_grads[0], arg_grads[0]->to_vector())); \
  EXPECT_TRUE( \
      test_utils::vector_match(bw_grads[1], arg_grads[1]->to_vector())); \
}

TEST_F(FunctionImplTest_2Args, CheckAdd) {
  const Shape ret_shape({2, 2}, 3);
  const vector<float> ret_data {2, 3, 4, 5, 2, 2, 2, 2, 2, 1, 0, -1};
  const vector<vector<float>> bw_grads {
    vector<float>(arg_shapes[0]->size(), 1),
    vector<float>(arg_shapes[1]->size(), 1),
  };
  const Add node;
  TEST_ALL(Add);
}

TEST_F(FunctionImplTest_2Args, CheckSubtract) {
  const Shape ret_shape({2, 2}, 3);
  const vector<float> ret_data {0, 1, 2, 3, -2, -2, -2, -2, -4, -5, -6, -7};
  const vector<vector<float>> bw_grads {
    vector<float>(arg_shapes[0]->size(), 1),
    vector<float>(arg_shapes[1]->size(), -1),
  };
  const Subtract node;
  TEST_ALL(Subtract);
}

TEST_F(FunctionImplTest_2Args, CheckMultiply) {
  const Shape ret_shape({2, 2}, 3);
  const vector<float> ret_data {1, 2, 3, 4, 0, 0, 0, 0, -3, -6, -9, -12};
  const vector<vector<float>> bw_grads {
    vector<float> {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3},
    vector<float> {1, 2, 3, 4, 0, 0, 0, 0, -1, -2, -3, -4},
  };
  const Multiply node;
  TEST_ALL(Multiply);
}

#undef TEST_ALL

}  // namespace functions
}  // namespace primitiv
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <unistd.h>
#include <stdarg.h>
#ifdef __MACH__
#include <stdlib.h>
#include <stddef.h>
#include <gsl/gsl_assert>
#include <errno.h>

void* memalign(size_t align, size_t size) {
  void* ptr {nullptr};

  if (align < sizeof(void*))
    align = sizeof(void*);
  if (size < sizeof(void*))
    size = sizeof(void*);

  int res = posix_memalign(&ptr, align, size);
  if (res == EINVAL)
    printf("Error %i: posix_memalign got invalid alignment param %zu \n", res, align);
  if (res == ENOMEM)
    printf("Error %i: posix_memalign failed, not enough memory  %zu \n", res);
  return ptr;
}
void* aligned_alloc(size_t align, size_t size) {
  return memalign(align, size);
}
#endif

char _DISK_START_;
char _DISK_END_;
char _ELF_SYM_START_;

/// RTC ///
#include <rtc>
RTC::timestamp_t RTC::booted_at = 0;
void RTC::init() {}

#include <service>
const char* service_binary_name__ = "Service binary name";
const char* service_name__        = "Service name";

void Service::ready()
{
  printf("Service::ready() called\n");
}

extern "C"
void kprintf(char* format, ...)
{
  va_list args;
  va_start(args, format);
  vprintf(format, args);
  va_end(args);
}

extern "C"
void kprint(char* str)
{
printf("%s", str);
}

#include <kernel/os.hpp>
void OS::start(unsigned, unsigned) {}
void OS::default_stdout(const char*, size_t) {}
void OS::event_loop() {}
void OS::block() {}
void OS::halt() {}
void OS::resume_softreset(intptr_t) {}
bool OS::is_softreset_magic(uint32_t) {
  return true;
}

void __x86_init_paging(void*){};
namespace x86 {
namespace paging {
  void invalidate(void* pageaddr){};
}}

__attribute__((constructor))
void paging_test_init(){
  extern uintptr_t __exec_begin;
  extern uintptr_t __exec_end;
  __exec_begin = 0xa00000;
  __exec_end = 0xb0000b;
}

void OS::multiboot(unsigned) {}

#include <system_log>
void SystemLog::initialize() {}
void SystemLog::set_flags(uint32_t) {}

/// Kernel ///
char _binary_apic_boot_bin_end;
char _binary_apic_boot_bin_start;
char __plugin_ctors_start;
char __plugin_ctors_end;
char __service_ctors_start;
char __service_ctors_end;

char _ELF_START_;
char _ELF_END_;
uintptr_t _MULTIBOOT_START_;
uintptr_t _LOAD_START_;
uintptr_t _LOAD_END_;
uintptr_t _BSS_END_;
uintptr_t _TEXT_START_;
uintptr_t _TEXT_END_;
uintptr_t _EXEC_END_;

extern "C" {
  uintptr_t get_cpu_esp() {
    return 0xdeadbeef;
  }

/// C ABI ///
  void _init_c_runtime() {}
  void _init_bss() {}

#ifdef __MACH__
  void _init() {}
#endif

  void __libc_init_array () {}

  uintptr_t _multiboot_free_begin(uintptr_t) {
    return 0;
  }
  uintptr_t _move_symbols(uintptr_t) {
    return 0;
  }

  /// malloc ///
  struct mallinfo { int x; };
  struct mallinfo mallinfo() {
    return {0};
  }
  void malloc_trim() {}
  uintptr_t heap_end = std::numeric_limits<uintptr_t>::max();

  void __init_serial1 () {}

  void __serial_print1(const char* cstr) {
    printf("<serial print1> %s\n", cstr);
  }

  void __serial_print(const char* cstr, int len) {
    printf("<serial print> %.*s", len, cstr);
  }
} // ~ extern "C"

/// platform ///
void* __multiboot_addr;

void __platform_init() {}
extern "C" void __init_sanity_checks() {}
extern "C" void kernel_sanity_checks() {}

/// arch ///
void __arch_poweroff() {}
void __arch_reboot() {}
void __arch_subscribe_irq(uint8_t) {}
void __arch_enable_legacy_irq(uint8_t) {}
void __arch_disable_legacy_irq(uint8_t) {}
void __arch_system_deactivate() {}

delegate<uint64_t()> systime_override = [] () -> uint64_t { return 0; };
uint64_t __arch_system_time() noexcept {
  return systime_override();
}
#include <sys/time.h>
timespec __arch_wall_clock() noexcept {
  return timespec{0, 0};
}

/// smp ///
#include <smp>
int SMP::cpu_id() noexcept {
  return 0;
}
void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
void SMP::add_task(SMP::task_func func, int) { func(); }
void SMP::signal(int) {}

extern "C"
void (*current_eoi_mechanism) () = nullptr;

#ifdef ARCH_X86
#include "../../src/arch/x86/apic.hpp"
namespace x86 {
  IApic& APIC::get() noexcept { return *(IApic*) 0; }
}
#endif

#ifndef ARCH_X86
bool rdrand32(uint32_t* result) {
  *result = rand();
  return true;
}

/// heap ///
uintptr_t __brk_max = 0;
uintptr_t OS::heap_begin() noexcept {
  return 0;
}

uintptr_t OS::memory_end_ = 1 << 30;

uintptr_t OS::heap_end() noexcept {
  return memory_end_;
}

size_t OS::heap_usage() noexcept {
  return OS::heap_end();
}

uintptr_t OS::heap_max() noexcept {
  return -1;
}

size_t OS::total_memuse() noexcept {
  return heap_end();
}

#endif
<commit_msg>test: Have mock arch clock use the systime delg to set seconds<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <unistd.h>
#include <stdarg.h>
#ifdef __MACH__
#include <stdlib.h>
#include <stddef.h>
#include <gsl/gsl_assert>
#include <errno.h>

void* memalign(size_t align, size_t size) {
  void* ptr {nullptr};

  if (align < sizeof(void*))
    align = sizeof(void*);
  if (size < sizeof(void*))
    size = sizeof(void*);

  int res = posix_memalign(&ptr, align, size);
  if (res == EINVAL)
    printf("Error %i: posix_memalign got invalid alignment param %zu \n", res, align);
  if (res == ENOMEM)
    printf("Error %i: posix_memalign failed, not enough memory  %zu \n", res);
  return ptr;
}
void* aligned_alloc(size_t align, size_t size) {
  return memalign(align, size);
}
#endif

char _DISK_START_;
char _DISK_END_;
char _ELF_SYM_START_;

/// RTC ///
#include <rtc>
RTC::timestamp_t RTC::booted_at = 0;
void RTC::init() {}

#include <service>
const char* service_binary_name__ = "Service binary name";
const char* service_name__        = "Service name";

void Service::ready()
{
  printf("Service::ready() called\n");
}

extern "C"
void kprintf(char* format, ...)
{
  va_list args;
  va_start(args, format);
  vprintf(format, args);
  va_end(args);
}

extern "C"
void kprint(char* str)
{
printf("%s", str);
}

#include <kernel/os.hpp>
void OS::start(unsigned, unsigned) {}
void OS::default_stdout(const char*, size_t) {}
void OS::event_loop() {}
void OS::block() {}
void OS::halt() {}
void OS::resume_softreset(intptr_t) {}
bool OS::is_softreset_magic(uint32_t) {
  return true;
}

void __x86_init_paging(void*){};
namespace x86 {
namespace paging {
  void invalidate(void* pageaddr){};
}}

__attribute__((constructor))
void paging_test_init(){
  extern uintptr_t __exec_begin;
  extern uintptr_t __exec_end;
  __exec_begin = 0xa00000;
  __exec_end = 0xb0000b;
}

void OS::multiboot(unsigned) {}

#include <system_log>
void SystemLog::initialize() {}
void SystemLog::set_flags(uint32_t) {}

/// Kernel ///
char _binary_apic_boot_bin_end;
char _binary_apic_boot_bin_start;
char __plugin_ctors_start;
char __plugin_ctors_end;
char __service_ctors_start;
char __service_ctors_end;

char _ELF_START_;
char _ELF_END_;
uintptr_t _MULTIBOOT_START_;
uintptr_t _LOAD_START_;
uintptr_t _LOAD_END_;
uintptr_t _BSS_END_;
uintptr_t _TEXT_START_;
uintptr_t _TEXT_END_;
uintptr_t _EXEC_END_;

extern "C" {
  uintptr_t get_cpu_esp() {
    return 0xdeadbeef;
  }

/// C ABI ///
  void _init_c_runtime() {}
  void _init_bss() {}

#ifdef __MACH__
  void _init() {}
#endif

  void __libc_init_array () {}

  uintptr_t _multiboot_free_begin(uintptr_t) {
    return 0;
  }
  uintptr_t _move_symbols(uintptr_t) {
    return 0;
  }

  /// malloc ///
  struct mallinfo { int x; };
  struct mallinfo mallinfo() {
    return {0};
  }
  void malloc_trim() {}
  uintptr_t heap_end = std::numeric_limits<uintptr_t>::max();

  void __init_serial1 () {}

  void __serial_print1(const char* cstr) {
    printf("<serial print1> %s\n", cstr);
  }

  void __serial_print(const char* cstr, int len) {
    printf("<serial print> %.*s", len, cstr);
  }
} // ~ extern "C"

/// platform ///
void* __multiboot_addr;

void __platform_init() {}
extern "C" void __init_sanity_checks() {}
extern "C" void kernel_sanity_checks() {}

/// arch ///
void __arch_poweroff() {}
void __arch_reboot() {}
void __arch_subscribe_irq(uint8_t) {}
void __arch_enable_legacy_irq(uint8_t) {}
void __arch_disable_legacy_irq(uint8_t) {}
void __arch_system_deactivate() {}

delegate<uint64_t()> systime_override = [] () -> uint64_t { return 0; };
uint64_t __arch_system_time() noexcept {
  return systime_override();
}
#include <sys/time.h>
timespec __arch_wall_clock() noexcept {
  return timespec{static_cast<long>(systime_override()), 0};
}

/// smp ///
#include <smp>
int SMP::cpu_id() noexcept {
  return 0;
}
void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
void SMP::add_task(SMP::task_func func, int) { func(); }
void SMP::signal(int) {}

extern "C"
void (*current_eoi_mechanism) () = nullptr;

#ifdef ARCH_X86
#include "../../src/arch/x86/apic.hpp"
namespace x86 {
  IApic& APIC::get() noexcept { return *(IApic*) 0; }
}
#endif

#ifndef ARCH_X86
bool rdrand32(uint32_t* result) {
  *result = rand();
  return true;
}

/// heap ///
uintptr_t __brk_max = 0;
uintptr_t OS::heap_begin() noexcept {
  return 0;
}

uintptr_t OS::memory_end_ = 1 << 30;

uintptr_t OS::heap_end() noexcept {
  return memory_end_;
}

size_t OS::heap_usage() noexcept {
  return OS::heap_end();
}

uintptr_t OS::heap_max() noexcept {
  return -1;
}

size_t OS::total_memuse() noexcept {
  return heap_end();
}

#endif
<|endoftext|>


<commit_before>#include <iostream>

int main ()
{
  for(int i = 1; i <= 100; i++)
  {
    if(i % 3 == 0 && i % 5 == 0)
      std::cout << "FizzBuzz" << '\n';
    else
    if(i % 3 == 0)
      std::cout << "Fizz" << '\n';
    else
    if(i % 5 == 0)
      std::cout << "Buzz" << '\n';
    else std::cout << i << "\n\t\n";
  }
  return 0;
}
<commit_msg>Fix merge conflict<commit_after>#include <iostream>

int main ()
{
  for(int i = 1; i <= 100; i++)
  {
    if(i % 3 == 0 && i % 5 == 0)
        std::cout << "FizzBuzz\n";
    else
    if(i % 3 == 0)
        std::cout << "Fizz\n";
    else
    if(i % 5 == 0)
        std::cout << "Buzz\n";
    else std::cout << i << "\n\n\n";
  }
  return 0;
}
<|endoftext|>


<commit_before>#include "lanescene.h"
#include "leftheaderscene.h"
#include "lanebgitem.h"
#include "taskmanager.h"
#include "common.h"
#include <QGraphicsRectItem>

LaneScene::LaneScene(LeftHeaderScene *leftHeaderScene, qreal w, QObject *parent)
    : QGraphicsScene(0, 0, w, leftHeaderScene->height(), parent)
    , leftHeaderScene_(leftHeaderScene)
{
    // add background
    bgItem_ = new QGraphicsRectItem(sceneRect());
    bgItem_->setBrush(QBrush(QColor("#eeeeee")));
    bgItem_->setZValue(-1);
    addItem(bgItem_);
}

void LaneScene::refresh()
{
    // note: we assume that leftHeaderScene_ is already refreshed at this point

    const QList<qint64> tmRoleIds = TaskManager::instance()->roleIds();

    // remove lane items for roles that no longer exist in the task manager
    foreach (LaneBGItem *lItem, laneItems()) {
        if (!tmRoleIds.contains(lItem->roleId()))
            removeItem(lItem);
    }

    // add lane items for unrepresented roles in the task manager
    const QList<qint64> liRoleIds = laneItemRoleIds();
    foreach (qint64 tmRoleId, tmRoleIds) {
        if (!liRoleIds.contains(tmRoleId))
            addLaneItem(tmRoleId);
    }

    // update scene rect
    const QRectF srect = sceneRect();
    setSceneRect(srect.x(), srect.y(), srect.width(), laneItems().size() * leftHeaderScene_->laneHeight() + leftHeaderScene_->lanePadding());

    // update header item rects
    const qreal lpadding = leftHeaderScene_->lanePadding();
    const qreal lheight = leftHeaderScene_->laneHeight();
    int i = 0;
    foreach (LaneBGItem *item, laneItems()) {
        item->setPos(0, 0);
        item->setRect(lpadding, i * lheight + lpadding, width() - 2 * lpadding, lheight - lpadding);
        i++;
    }

    // update background item
    bgItem_->setRect(sceneRect());
}

QList<LaneBGItem *> LaneScene::laneItems() const
{
    QList<LaneBGItem *> lItems;
    foreach (QGraphicsItem *item, items()) {
        LaneBGItem *lItem = dynamic_cast<LaneBGItem *>(item);
        if (lItem)
            lItems.append(lItem);
    }
    return lItems;
}

QList<qint64> LaneScene::laneItemRoleIds() const
{
    QList<qint64> liRoleIds;
    foreach (QGraphicsItem *item, items()) {
        LaneBGItem *lItem = dynamic_cast<LaneBGItem *>(item);
        if (lItem)
            liRoleIds.append(lItem->roleId());
    }
    return liRoleIds;
}

void LaneScene::addLaneItem(qint64 roleId)
{
    addItem(new LaneBGItem(roleId));
}
<commit_msg>Fixed typo<commit_after>#include "lanescene.h"
#include "leftheaderscene.h"
#include "lanebgitem.h"
#include "taskmanager.h"
#include "common.h"
#include <QGraphicsRectItem>

LaneScene::LaneScene(LeftHeaderScene *leftHeaderScene, qreal w, QObject *parent)
    : QGraphicsScene(0, 0, w, leftHeaderScene->height(), parent)
    , leftHeaderScene_(leftHeaderScene)
{
    // add background
    bgItem_ = new QGraphicsRectItem(sceneRect());
    bgItem_->setBrush(QBrush(QColor("#eeeeee")));
    bgItem_->setZValue(-1);
    addItem(bgItem_);
}

void LaneScene::refresh()
{
    // note: we assume that leftHeaderScene_ is already refreshed at this point

    const QList<qint64> tmRoleIds = TaskManager::instance()->roleIds();

    // remove lane items for roles that no longer exist in the task manager
    foreach (LaneBGItem *lItem, laneItems()) {
        if (!tmRoleIds.contains(lItem->roleId()))
            removeItem(lItem);
    }

    // add lane items for unrepresented roles in the task manager
    const QList<qint64> liRoleIds = laneItemRoleIds();
    foreach (qint64 tmRoleId, tmRoleIds) {
        if (!liRoleIds.contains(tmRoleId))
            addLaneItem(tmRoleId);
    }

    // update scene rect
    const QRectF srect = sceneRect();
    setSceneRect(srect.x(), srect.y(), srect.width(), laneItems().size() * leftHeaderScene_->laneHeight() + leftHeaderScene_->lanePadding());

    // update lane item rects
    const qreal lpadding = leftHeaderScene_->lanePadding();
    const qreal lheight = leftHeaderScene_->laneHeight();
    int i = 0;
    foreach (LaneBGItem *item, laneItems()) {
        item->setPos(0, 0);
        item->setRect(lpadding, i * lheight + lpadding, width() - 2 * lpadding, lheight - lpadding);
        i++;
    }

    // update background item
    bgItem_->setRect(sceneRect());
}

QList<LaneBGItem *> LaneScene::laneItems() const
{
    QList<LaneBGItem *> lItems;
    foreach (QGraphicsItem *item, items()) {
        LaneBGItem *lItem = dynamic_cast<LaneBGItem *>(item);
        if (lItem)
            lItems.append(lItem);
    }
    return lItems;
}

QList<qint64> LaneScene::laneItemRoleIds() const
{
    QList<qint64> liRoleIds;
    foreach (QGraphicsItem *item, items()) {
        LaneBGItem *lItem = dynamic_cast<LaneBGItem *>(item);
        if (lItem)
            liRoleIds.append(lItem->roleId());
    }
    return liRoleIds;
}

void LaneScene::addLaneItem(qint64 roleId)
{
    addItem(new LaneBGItem(roleId));
}
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------
#define _USE_MATH_DEFINES

#include "renderer.hpp"
#include "SDFloader.hpp"
#include "ray.hpp"
#include <cmath>
#include <glm/glm.hpp>

using namespace std;

Renderer::Renderer(unsigned w, unsigned h)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , ppm_(width_, height_)
  ,finished_(false)
{}

Renderer::Renderer(unsigned w, unsigned h, string const& scenefile)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , scenefile_(scenefile)
  , ppm_(width_, height_)
  ,finished_(false)
{
   scene_ = SDFLoader::load(scenefile);
}

void Renderer::render() {
    if (width_<scene_.resX){
        cout << "ERROR: Resolution X to big. Forcing: "<<width_<<endl;
        scene_.resX=width_;
    }
    if (height_<scene_.resY){
        cout << "ERROR: Resolution Y to big. Forcing: "<<height_<<endl;
        scene_.resY=height_;
    }
    if (scene_.renderObjects.find("root")!= scene_.renderObjects.end()){
        cout << "#####RENDERING####"<<endl;
        cout << "Resolution: "<<scene_.resX<<"x"<<scene_.resY<<endl;
        cout << "Camera: "<<scene_.camname<<endl;
        cout << "ambient light "<<scene_.amb<<endl;

        float d = -scene_.resX/tan(scene_.camera.GetFovX()*M_PI/180); //apply camera fov, little different angle for each pixel

        for (unsigned yr = 0; yr < scene_.resY; ++yr) {
            for (unsigned xr = 0; xr < scene_.resX; ++xr) {
                unsigned x=xr;
                unsigned y=yr;

                //allow random pixel rendering
                if (scene_.random){
                    x=rand() % scene_.resX;
                    y=rand() % scene_.resY;
                    for (int i = 0; i < 100; i++) {//try 100 times
                        auto coloratp = colorbuffer_[(width_*y + x)];
                        if (!(coloratp.r == 0 && coloratp.g==0 && coloratp.b==0)){//again if already filled
                            x=rand() % scene_.resX;
                            y=rand() % scene_.resY;
                        }else break;
                    }
                }

                Pixel p(x,y);

                if (scene_.antialiase>0){//SSAA

                    for (int xSSAA=1;xSSAA<sqrt(scene_.antialiase)+1;++xSSAA){
                        for (int ySSAA=1;ySSAA<sqrt(scene_.antialiase)+1;++ySSAA){
                            Ray ray = Ray();
                            ray.direction.x = -scene_.resX/2.0f+x+(float) (xSSAA/(float)sqrt(scene_.antialiase))-0.5f;
                            ray.direction.y = -scene_.resY/2.0f+y+(float) (ySSAA/(float)sqrt(scene_.antialiase))-0.5f;
                            ray.direction.z = d;
                            p.color +=getColor(ray);
                        }
                    }
                    p.color /=scene_.antialiase;
                } else {
                    Ray ray = Ray();
                    ray.direction.x = -scene_.resX/2.0f+x;
                    ray.direction.y = -scene_.resY/2.0f+y;
                    ray.direction.z = d;

                    //here should get the camera transformation applied
                    //cout << "Ray@("<<x<<"x"<<y<<"): "<<ray<<endl;

                    p.color +=getColor(ray);
                }
                p.color += scene_.amb;
                write(p);
            }
        }
        ppm_.save(scene_.outputFile);
        finished_ = true;
    } else {
        cout << "no root found!"<<endl;
    }
}

Color Renderer::getColor(const Ray& ray) {
    Color diff;

    auto intersection( scene_.renderObjects["root"]->intersect(ray) );

    if (intersection.hit){//if intersection happened
        //starting from the intersection go to every light source
        for(auto lightIt = scene_.lights.begin(); lightIt != scene_.lights.end(); lightIt++) {
            auto light = lightIt->second;
            //a ray pointing to the current light source
            auto lightRay = Ray(
                intersection.ray.origin,
                glm::normalize(light.GetPos()-intersection.ray.origin)//l=IL =L-I
            );
            lightRay.origin += lightRay.direction*2.0f;

            //shaddow
            auto lighintersect = scene_.renderObjects["root"]->intersect(lightRay);
            if (!(lighintersect.hit && lighintersect.distance < glm::length(light.GetPos()-intersection.ray.origin))){//check if intersec between p and light source
                //diffuse light
                double fDiffuse = glm::dot(lightRay.direction, intersection.ray.direction);//l*n
                fDiffuse = fDiffuse < 0 ? 0 : fDiffuse;//allow no negative diffuse light

                diff +=  light.GetDiff()//get light color
                        * intersection.material.getKd()//multiply by material, (l_p * k_d)
                        * fDiffuse;
            }
        }
    }
    return diff;
}

void Renderer::write(Pixel const& p) {
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<commit_msg>default is "scene.sdf"<commit_after>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------
#define _USE_MATH_DEFINES

#include "renderer.hpp"
#include "SDFloader.hpp"
#include "ray.hpp"
#include <cmath>
#include <glm/glm.hpp>

using namespace std;

Renderer::Renderer(unsigned w, unsigned h)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , scenefile_("scene.sdf")
  , ppm_(width_, height_)
  ,finished_(false)
{
    scene_ = SDFLoader::load(scenefile);
}

Renderer::Renderer(unsigned w, unsigned h, string const& scenefile)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , scenefile_(scenefile)
  , ppm_(width_, height_)
  ,finished_(false)
{
   scene_ = SDFLoader::load(scenefile);
}

void Renderer::render() {
    if (width_<scene_.resX){
        cout << "ERROR: Resolution X to big. Forcing: "<<width_<<endl;
        scene_.resX=width_;
    }
    if (height_<scene_.resY){
        cout << "ERROR: Resolution Y to big. Forcing: "<<height_<<endl;
        scene_.resY=height_;
    }
    if (scene_.renderObjects.find("root")!= scene_.renderObjects.end()){
        cout << "#####RENDERING####"<<endl;
        cout << "Resolution: "<<scene_.resX<<"x"<<scene_.resY<<endl;
        cout << "Camera: "<<scene_.camname<<endl;
        cout << "ambient light "<<scene_.amb<<endl;

        float d = -scene_.resX/tan(scene_.camera.GetFovX()*M_PI/180); //apply camera fov, little different angle for each pixel

        for (unsigned yr = 0; yr < scene_.resY; ++yr) {
            for (unsigned xr = 0; xr < scene_.resX; ++xr) {
                unsigned x=xr;
                unsigned y=yr;

                //allow random pixel rendering
                if (scene_.random){
                    x=rand() % scene_.resX;
                    y=rand() % scene_.resY;
                    for (int i = 0; i < 100; i++) {//try 100 times
                        auto coloratp = colorbuffer_[(width_*y + x)];
                        if (!(coloratp.r == 0 && coloratp.g==0 && coloratp.b==0)){//again if already filled
                            x=rand() % scene_.resX;
                            y=rand() % scene_.resY;
                        }else break;
                    }
                }

                Pixel p(x,y);

                if (scene_.antialiase>0){//SSAA

                    for (int xSSAA=1;xSSAA<sqrt(scene_.antialiase)+1;++xSSAA){
                        for (int ySSAA=1;ySSAA<sqrt(scene_.antialiase)+1;++ySSAA){
                            Ray ray = Ray();
                            ray.direction.x = -scene_.resX/2.0f+x+(float) (xSSAA/(float)sqrt(scene_.antialiase))-0.5f;
                            ray.direction.y = -scene_.resY/2.0f+y+(float) (ySSAA/(float)sqrt(scene_.antialiase))-0.5f;
                            ray.direction.z = d;
                            p.color +=getColor(ray);
                        }
                    }
                    p.color /=scene_.antialiase;
                } else {
                    Ray ray = Ray();
                    ray.direction.x = -scene_.resX/2.0f+x;
                    ray.direction.y = -scene_.resY/2.0f+y;
                    ray.direction.z = d;

                    //here should get the camera transformation applied
                    //cout << "Ray@("<<x<<"x"<<y<<"): "<<ray<<endl;

                    p.color +=getColor(ray);
                }
                p.color += scene_.amb;
                write(p);
            }
        }
        ppm_.save(scene_.outputFile);
        finished_ = true;
    } else {
        cout << "no root found!"<<endl;
    }
}

Color Renderer::getColor(const Ray& ray) {
    Color diff;

    auto intersection( scene_.renderObjects["root"]->intersect(ray) );

    if (intersection.hit){//if intersection happened
        //starting from the intersection go to every light source
        for(auto lightIt = scene_.lights.begin(); lightIt != scene_.lights.end(); lightIt++) {
            auto light = lightIt->second;
            //a ray pointing to the current light source
            auto lightRay = Ray(
                intersection.ray.origin,
                glm::normalize(light.GetPos()-intersection.ray.origin)//l=IL =L-I
            );
            lightRay.origin += lightRay.direction*2.0f;

            //shaddow
            auto lighintersect = scene_.renderObjects["root"]->intersect(lightRay);
            if (!(lighintersect.hit && lighintersect.distance < glm::length(light.GetPos()-intersection.ray.origin))){//check if intersec between p and light source
                //diffuse light
                double fDiffuse = glm::dot(lightRay.direction, intersection.ray.direction);//l*n
                fDiffuse = fDiffuse < 0 ? 0 : fDiffuse;//allow no negative diffuse light

                diff +=  light.GetDiff()//get light color
                        * intersection.material.getKd()//multiply by material, (l_p * k_d)
                        * fDiffuse;
            }
        }
    }
    return diff;
}

void Renderer::write(Pixel const& p) {
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<|endoftext|>