<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.18.10); FILE MERGED 2008/04/01 15:44:44 thb 1.18.10.3: #i85898# Stripping all external header guards 2008/04/01 12:43:23 thb 1.18.10.2: #i85898# Stripping all external header guards 2008/03/31 13:01:23 rt 1.18.10.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before>/*
 *  caosVM_files.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sat Aug 13 2005.
 *  Copyright (c) 2005 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "caosVM.h"
#include "World.h"
#include <fstream>
#include <iostream>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

std::string calculateFilename(int directory, std::string filename) {
	std::string fullfilename;
	switch (directory) {
		// TODO: point at the correct journal directories
		case 0: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		case 1: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		case 2: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		default: throw caosException("unknown directory in FILE OOPE");
	}

	fs::path dir = fs::path(fullfilename, fs::native);
	if (!fs::exists(dir))
		fs::create_directory(dir);
	caos_assert(fs::exists(dir) && fs::is_directory(dir));

	// sanitise string: remove leading dots, replace slashes with underscores
	// todo: check DS behaviour for backslashes (a problem on Windows)
	std::string::size_type r;
	while ((r = filename.find("/", 0)) != std::string::npos)
		filename.replace(r, 1, "_");
	for (unsigned int i = 0; i < filename.size(); i++)
		if (filename[i] == '.') { filename.erase(i, 1); i--; }
		else break;

	return fullfilename + filename;
}

/**
 FILE GLOB (command) directory (integer) filespec (string)
 %status maybe

 Globs the given journal directory (pass 0 for the world directory, or 1 for the main directory) for the
 given filespec (you can use wildcards, and descend into subdirectories using '..').

 The result is placed on the input stream for reading with standard input commands (eg, INNI and INNL);
 this consists of the number of results on the first line, and then the full filename paths to the matched
 files on the remaining lines.
*/
void caosVM::c_FILE_GLOB() {
	VM_PARAM_STRING(filespec)
	VM_PARAM_INTEGER(directory)

	std::string::size_type n = filespec.find_last_of("/\\") + 1;
	std::string dirportion; dirportion.assign(filespec, 0, n);
	std::string specportion; specportion.assign(filespec, n, filespec.size() - n);

	if (directory == 1)
		dirportion = "Journal/" + dirportion;
	else
		throw creaturesException("whoops, openc2e doesn't support FILE GLOB in world journal directory yet, bug fuzzie");

	std::vector<std::string> possiblefiles = world.findFiles(dirportion, specportion);

	std::string str = boost::str(boost::format("%d\n") % possiblefiles.size());
	for (std::vector<std::string>::iterator i = possiblefiles.begin(); i != possiblefiles.end(); i++) {
		str += *i + "\n";
	}

	inputstream = new std::istringstream(str);
}

/**
 FILE ICLO (command)
 %status maybe

 Disconnects everything from the input stream.
*/
void caosVM::c_FILE_ICLO() {
	if (inputstream) {
		delete inputstream;
		inputstream = 0;
	}
}

/**
 FILE IOPE (command) directory (integer) filename (string)
 %status maybe

 Puts the given filename in the given directory (pass 1 for the world directory, or 0 for the main
 directory) on the current VM's input stream, for use by INOK, INNL, INNI and INNF.
 If a file is already open, it will be closed first.
*/
void caosVM::c_FILE_IOPE() {
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	c_FILE_ICLO();

	std::string fullfilename = calculateFilename(directory, filename);
	inputstream = new std::ifstream(fullfilename.c_str());

	if (inputstream->fail()) {
		delete inputstream;
		inputstream = 0;
	}
}

/**
 FILE JDEL (command) directory (integer) filename (string)
 %status stub

 Removes the given file in the given directory (pass 1 for the world directory, or 0 for the main
 directory) immediately.
*/
void caosVM::c_FILE_JDEL() {
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	std::string fullfilename = calculateFilename(directory, filename);

	// TODO
}

/**
 FILE OCLO (command)
 %status maybe

 Disconnects everything from the output stream.
*/
void caosVM::c_FILE_OCLO() {
	if (outputstream) {
		delete outputstream;
		outputstream = 0;
	}
}

/**
 FILE OFLU (command)
 %status maybe

 Flushes the current output stream; if this is a file, all data in the buffer will be written to it.
*/
void caosVM::c_FILE_OFLU() {
	if (outputstream)
		outputstream->flush();
}

/**
 FILE OOPE (command) directory (integer) filename (string) append (integer)
 %status maybe

 Puts the given filename in the given directory (pass 1 for the world directory, or 0 for the main
 directory) on the current VM's output stream.
 If a file is already open, it will be closed first.
*/
void caosVM::c_FILE_OOPE() {
	VM_PARAM_INTEGER(append)
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	c_FILE_OCLO();

	std::string fullfilename = calculateFilename(directory, filename);

	if (append)
		outputstream = new std::ofstream(fullfilename.c_str(), std::ios::app);
	else
		outputstream = new std::ofstream(fullfilename.c_str(), std::ios::trunc);

	if (outputstream->fail()) {
		outputstream = 0;
		throw caosException(boost::str(boost::format("FILE OOPE failed to open %s") % fullfilename));
	}
}

/**
 FVWM (string) name (string)
 %status stub

 Returns an safe (not-in-use) filename for naming worlds and other saved files.
*/
void caosVM::v_FVWM() {
	VM_PARAM_STRING(name)

	result.setString(name + "_something"); // TODO
}

/**
 INNF (float)
 %status maybe

 Fetches a float from the current input stream, or 0.0 if there is no data.
*/
void caosVM::v_INNF() {
	if (!inputstream)
		throw caosException("no input stream in INNF!");

	float f = 0.0f;
	*inputstream >> f;
	result.setFloat(f);
}

/**
 INNI (integer)
 %status maybe

 Fetches an integer from the current input stream, or 0 if there is no data.
*/
void caosVM::v_INNI() {
	if (!inputstream)
		throw caosException("no input stream in INNI!");

	int i = 0;
	*inputstream >> i;
	result.setInt(i);
}

/**
 INNL (string)
 %status maybe

 Fetches a string of text from the input stream.
*/
void caosVM::v_INNL() {
	if (!inputstream)
		throw caosException("no input stream in INNL!");
	std::string str;
	std::getline(*inputstream, str);
	result.setString(str);
}

/**
 INOK (integer)
 %status maybe

 Determines whether the current input stream is usable (0 or 1).
*/
void caosVM::v_INOK() {
	if (!inputstream)
		result.setInt(0);
	else if (inputstream->fail())
		result.setInt(0);
	else
		result.setInt(1);
}

/**
 WEBB (command) url (string)
 %status stub

 Launches the specified URL, prepended with 'http://' (so you'd only specify, for example, 'example.com/foo.html'), in the user's browser.
*/
void caosVM::c_WEBB() {
	VM_PARAM_STRING(url)

	// TODO
	std::string to_use = std::string("http://") + url;
}

/* vim: set noet: */
<commit_msg>support reading existing Journal files from the game data directories<commit_after>/*
 *  caosVM_files.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sat Aug 13 2005.
 *  Copyright (c) 2005 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "caosVM.h"
#include "World.h"
#include <fstream>
#include <iostream>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

std::string calculateJournalFilename(int directory, std::string filename, bool writable) {
	// sanitise string: remove leading dots, replace slashes with underscores
	// todo: check DS behaviour for backslashes (a problem on Windows)
	std::string::size_type r;
	while ((r = filename.find("/", 0)) != std::string::npos)
		filename.replace(r, 1, "_");
	for (unsigned int i = 0; i < filename.size(); i++) {
		if (filename[i] == '.') {
			filename.erase(i, 1);
			i--;
		} else break;
	}

	std::string fullfilename;

	// TODO: point at the correct journal directories!

	if (!writable) {
		// search all directories for a readable file
		fullfilename = world.findFile("/Journal/" + filename);

		// if we found one, return that
		if (fullfilename.size()) return fullfilename;
	}

	// otherwise, we should always write to the journal directory
	switch (directory) {
		case 0: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		case 1: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		case 2: fullfilename = world.getUserDataDir() + "/Journal/"; break;
		default: throw caosException("unknown Journal directory");
	}

	fs::path dir = fs::path(fullfilename, fs::native);
	if (!fs::exists(dir))
		fs::create_directory(dir);
	caos_assert(fs::exists(dir) && fs::is_directory(dir));

	return fullfilename + filename;
}

/**
 FILE GLOB (command) directory (integer) filespec (string)
 %status maybe

 Globs the given journal directory (pass 0 for the world directory, or 1 for the main directory) for the
 given filespec (you can use wildcards, and descend into subdirectories using '..').

 The result is placed on the input stream for reading with standard input commands (eg, INNI and INNL);
 this consists of the number of results on the first line, and then the full filename paths to the matched
 files on the remaining lines.
*/
void caosVM::c_FILE_GLOB() {
	VM_PARAM_STRING(filespec)
	VM_PARAM_INTEGER(directory)

	std::string::size_type n = filespec.find_last_of("/\\") + 1;
	std::string dirportion; dirportion.assign(filespec, 0, n);
	std::string specportion; specportion.assign(filespec, n, filespec.size() - n);

	if (directory == 1)
		dirportion = "Journal/" + dirportion;
	else
		throw creaturesException("whoops, openc2e doesn't support FILE GLOB in world journal directory yet, bug fuzzie");

	std::vector<std::string> possiblefiles = world.findFiles(dirportion, specportion);

	std::string str = boost::str(boost::format("%d\n") % possiblefiles.size());
	for (std::vector<std::string>::iterator i = possiblefiles.begin(); i != possiblefiles.end(); i++) {
		str += *i + "\n";
	}

	inputstream = new std::istringstream(str);
}

/**
 FILE ICLO (command)
 %status maybe

 Disconnects everything from the input stream.
*/
void caosVM::c_FILE_ICLO() {
	if (inputstream) {
		delete inputstream;
		inputstream = 0;
	}
}

/**
 FILE IOPE (command) directory (integer) filename (string)
 %status maybe

 Puts the given filename in the given directory (pass 1 for the world directory, or 0 for the main
 directory) on the current VM's input stream, for use by INOK, INNL, INNI and INNF.
 If a file is already open, it will be closed first.
*/
void caosVM::c_FILE_IOPE() {
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	c_FILE_ICLO();

	std::string fullfilename = calculateJournalFilename(directory, filename, false);
	inputstream = new std::ifstream(fullfilename.c_str());

	if (inputstream->fail()) {
		delete inputstream;
		inputstream = 0;
	}
}

/**
 FILE JDEL (command) directory (integer) filename (string)
 %status stub

 Removes the given file in the given directory (pass 1 for the world directory, or 0 for the main
 directory) immediately.
*/
void caosVM::c_FILE_JDEL() {
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	std::string fullfilename = calculateJournalFilename(directory, filename, true);

	// TODO
}

/**
 FILE OCLO (command)
 %status maybe

 Disconnects everything from the output stream.
*/
void caosVM::c_FILE_OCLO() {
	if (outputstream) {
		delete outputstream;
		outputstream = 0;
	}
}

/**
 FILE OFLU (command)
 %status maybe

 Flushes the current output stream; if this is a file, all data in the buffer will be written to it.
*/
void caosVM::c_FILE_OFLU() {
	if (outputstream)
		outputstream->flush();
}

/**
 FILE OOPE (command) directory (integer) filename (string) append (integer)
 %status maybe

 Puts the given filename in the given directory (pass 1 for the world directory, or 0 for the main
 directory) on the current VM's output stream.
 If a file is already open, it will be closed first.
*/
void caosVM::c_FILE_OOPE() {
	VM_PARAM_INTEGER(append)
	VM_PARAM_STRING(filename)
	VM_PARAM_INTEGER(directory)

	c_FILE_OCLO();

	std::string fullfilename = calculateJournalFilename(directory, filename, true);

	if (append)
		outputstream = new std::ofstream(fullfilename.c_str(), std::ios::app);
	else
		outputstream = new std::ofstream(fullfilename.c_str(), std::ios::trunc);

	if (outputstream->fail()) {
		outputstream = 0;
		throw caosException(boost::str(boost::format("FILE OOPE failed to open %s") % fullfilename));
	}
}

/**
 FVWM (string) name (string)
 %status stub

 Returns an safe (not-in-use) filename for naming worlds and other saved files.
*/
void caosVM::v_FVWM() {
	VM_PARAM_STRING(name)

	result.setString(name + "_something"); // TODO
}

/**
 INNF (float)
 %status maybe

 Fetches a float from the current input stream, or 0.0 if there is no data.
*/
void caosVM::v_INNF() {
	if (!inputstream)
		throw caosException("no input stream in INNF!");

	float f = 0.0f;
	*inputstream >> f;
	result.setFloat(f);
}

/**
 INNI (integer)
 %status maybe

 Fetches an integer from the current input stream, or 0 if there is no data.
*/
void caosVM::v_INNI() {
	if (!inputstream)
		throw caosException("no input stream in INNI!");

	int i = 0;
	*inputstream >> i;
	result.setInt(i);
}

/**
 INNL (string)
 %status maybe

 Fetches a string of text from the input stream.
*/
void caosVM::v_INNL() {
	if (!inputstream)
		throw caosException("no input stream in INNL!");
	std::string str;
	std::getline(*inputstream, str);
	result.setString(str);
}

/**
 INOK (integer)
 %status maybe

 Determines whether the current input stream is usable (0 or 1).
*/
void caosVM::v_INOK() {
	if (!inputstream)
		result.setInt(0);
	else if (inputstream->fail())
		result.setInt(0);
	else
		result.setInt(1);
}

/**
 WEBB (command) url (string)
 %status stub

 Launches the specified URL, prepended with 'http://' (so you'd only specify, for example, 'example.com/foo.html'), in the user's browser.
*/
void caosVM::c_WEBB() {
	VM_PARAM_STRING(url)

	// TODO
	std::string to_use = std::string("http://") + url;
}

/* vim: set noet: */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <error.h>
#include <sys/stat.h>

#include <readline/readline.h>
#include <readline/history.h>

#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus.h>
using namespace natus;

#define _str(s) # s
#define __str(s) _str(s)

#define PWSIZE 1024
#define PROMPT ">>> "
#define NPRMPT "... "

static Value alert(Value& ths, Value& fnc, vector<Value>& args, void *msc) {
	if (args.size() < 1)
		return ths.newString("Invalid number of arguments!").toException();
	fprintf(stderr, "%s\n", args[0].toString().c_str());
	return ths.newUndefined();
}

static Value dir(Value& ths, Value& fnc, vector<Value>& args, void *msc) {
	Value obj = ths.getGlobal();
	if (args.size() > 0)
		obj = args[0];
	set<string> names = obj.enumerate();
	for (set<string>::iterator i=names.begin() ; i != names.end() ; i++)
		fprintf(stderr, "\t%s\n", i->c_str());
	return ths.newUndefined();
}

bool inblock(const char *str) {
	char strstart = '\0';
	int cnt = 0;
	for (char prv='\0' ; *str ; prv=*str++) {
		if (strstart) {
			if (strstart == '"' && *str == '"' && prv != '\\')
				strstart = '\0';
			else if (strstart == '\'' && *str == '\'' && prv != '\\')
				strstart = '\0';
			continue;
		}

		// We are not inside a string literal
		switch (*str) {
			case '"':
				// We're starting a double-quoted string
				strstart = '"';
				break;
			case '\'':
				// We're starting a single-quoted string
				strstart = '\'';
				break;
			case '{':
				// We're starting a new block
				cnt++;
				break;
			case '}':
				// We're ending an existing block
				cnt--;
				break;
		}
	}
	return cnt > 0;
}

vector<string> pathparser(string path) {
	if (path.find(':') == string::npos) {
		vector<string> tmp;
		if (path != "")
			tmp.push_back(path);
		return tmp;
	}

	string segment = path.substr(path.find_last_of(':')+1);
	vector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));
	if (segment != "") paths.push_back(segment);
	return paths;
}

int main(int argc, char** argv) {
	const char *eng = NULL;
	const char *eval = NULL;
	int c=0, exitcode=0;

	vector<string> path = pathparser(string(__str(MODULEDIR)) + ":" + (getenv("NATUS_PATH") ? getenv("NATUS_PATH") : ""));
	vector<string> whitelist = pathparser(getenv("NATUS_WHITELIST") ? getenv("NATUS_WHITELIST") : "");

	opterr = 0;
	while ((c = getopt (argc, argv, "c:e:n")) != -1) {
		switch (c) {
		case 'c':
			eval = optarg;
			break;
		case 'e':
			eng = optarg;
			break;
		case 'n':
			path.erase(path.begin());
			break;
		case '?':
			if (optopt == 'e')
				fprintf(stderr, "Option -%c requires an engine name.\n", optopt);
			else {
				fprintf(stderr, "Usage: %s [-c <javascript>|-e <engine>|-n|<scriptfile>]\n\n", argv[0]);
				fprintf(stderr, "Unknown option `-%c'.\n", optopt);
			}
			return 1;
		default:
			abort();
	   }
	}

	Engine engine;
	if (!engine.initialize(eng))
		error(1, 0, "Unable to init engine!");

	Value global = engine.newGlobal(path, whitelist);
	if (global.isUndefined())
		error(2, 0, "Unable to init global!");
	global.set("alert", global.newFunction(alert, NULL, NULL));
	global.set("dir",   global.newFunction(dir,   NULL, NULL));

	// Do the evaluation
	if (eval) {
		Value res = global.evaluate(eval);

		// Print uncaught exceptions
		if (res.isException()) {
			string msg = res.toString();
			error(8, 0, "Uncaught Exception: %s", msg.c_str());
		}

		// Let the script return exitcodes
		if (res.isNumber())
			exitcode = (int) res.toLong();

		return exitcode;
	}

	// Start the shell
	if (optind >= argc) {
		fprintf(stderr, "Natus " PACKAGE_VERSION " - Using: %s\n", engine.getName().c_str());

		char* line;
		const char* prompt = PROMPT;
		string prev = "";

		long lcnt = 0;
		for (line=readline(prompt) ; line ; line=readline(prompt)) {
			// Strip the line
			string l = line;
			string::size_type start = l.find_first_not_of(" \t");
			l = start == string::npos ? string("") : l.substr(start, l.find_last_not_of(" \t")-start+1);
			if (l == "") continue;

			// Append the line to the buffer
			prev.append(l);

			// Continue to the next line
		    if (inblock(prev.c_str())) {
		    	prompt = NPRMPT;
		    	continue;
		    }
		    prompt = PROMPT;
			add_history(prev.c_str());

			Value res = global.evaluate(prev, string(), lcnt++, false);
			string msg;
			string fmt;
			msg = res.toString();
			if (res.isException()) {
				fmt = "Uncaught Exception: %s\n";
				if (prev == "exit" || prev == "quit") {
					res = res.newUndefined();
					fprintf(stderr, "Use Ctrl-D (i.e. EOF) to exit\n");
				}
			} else
				fmt = "%s\n";

			if (!res.isUndefined() && !res.isNull())
				fprintf(stderr, fmt.c_str(), msg.c_str());
			prev = "";
		}
		printf("\n");
		return 0;
	}

	// Get the script filename
	char *filename = argv[optind];

	// Stat our file
	struct stat st;
	if (stat(filename, &st))
		error(3, 0, "Script file does not exist: %s", filename);

	// Read in our script file
	FILE *file = fopen(filename, "r");
	if (!file)
		error(4, 0, "Unable to open file: %s", filename);
	char *jscript = new char[st.st_size + 1];
	if (!jscript) {
		fclose(file);
		error(5, 0, "Out of memory!");
	}
	if ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {
		delete[] jscript;
		fclose(file);
		error(6, 0, "Error reading file: %s", filename);
	}
	fclose(file);
	jscript[st.st_size] = '\0';

	// Evaluate it
	Value res = global.evaluate(jscript, filename ? filename : "");
	delete[] jscript;

	// Print uncaught exceptions
	if (res.isException()) {
		string msg = res.toString();
		error(8, 0, "Uncaught Exception: %s", msg.c_str());
	}

	// Let the script return exitcodes
	if (res.isNumber())
		exitcode = (int) res.toLong();

	return exitcode;
}
<commit_msg>enable tab-completion of the global hierarchy; enable ~/.natus_history<commit_after>/*
 * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <error.h>
#include <sys/stat.h>

#include <readline/readline.h>
#include <readline/history.h>

#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus.h>
using namespace natus;

#define _str(s) # s
#define __str(s) _str(s)

#define PWSIZE 1024
#define PROMPT ">>> "
#define NPRMPT "... "
#define HISTORYFILE ".natus_history"

Engine engine;
Value  global;

static Value alert(Value& ths, Value& fnc, vector<Value>& args, void *msc) {
	if (args.size() < 1)
		return ths.newString("Invalid number of arguments!").toException();
	fprintf(stderr, "%s\n", args[0].toString().c_str());
	return ths.newUndefined();
}

static Value dir(Value& ths, Value& fnc, vector<Value>& args, void *msc) {
	Value obj = ths.getGlobal();
	if (args.size() > 0)
		obj = args[0];
	set<string> names = obj.enumerate();
	for (set<string>::iterator i=names.begin() ; i != names.end() ; i++)
		fprintf(stderr, "\t%s\n", i->c_str());
	return ths.newUndefined();
}

static bool inblock(const char *str) {
	char strstart = '\0';
	int cnt = 0;
	for (char prv='\0' ; *str ; prv=*str++) {
		if (strstart) {
			if (strstart == '"' && *str == '"' && prv != '\\')
				strstart = '\0';
			else if (strstart == '\'' && *str == '\'' && prv != '\\')
				strstart = '\0';
			continue;
		}

		// We are not inside a string literal
		switch (*str) {
			case '"':
				// We're starting a double-quoted string
				strstart = '"';
				break;
			case '\'':
				// We're starting a single-quoted string
				strstart = '\'';
				break;
			case '{':
				// We're starting a new block
				cnt++;
				break;
			case '}':
				// We're ending an existing block
				cnt--;
				break;
		}
	}
	return cnt > 0;
}

static vector<string> pathparser(string path) {
	if (path.find(':') == string::npos) {
		vector<string> tmp;
		if (path != "")
			tmp.push_back(path);
		return tmp;
	}

	string segment = path.substr(path.find_last_of(':')+1);
	vector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));
	if (segment != "") paths.push_back(segment);
	return paths;
}

static char* completion_generator(const char* text, int state) {
	static set<string> names;
	static set<string>::iterator it;
	char* last = strrchr(text, '.');

	if (state == 0) {
		Value obj = global;
		if (last) {
			char* base = new char[last-text+1];
			memset(base, 0, sizeof(char) * (last-text+1));
			strncpy(base, text, last-text);
			obj = obj.get(base);
			delete[] base;
			if (obj.isUndefined()) return NULL;
		}

		names = obj.enumerate();
		it = names.begin();
	}
	if (last) last++;

	for ( ; it != names.end() ; it++) {
		if ((last && it->find(last) == 0) || (!last && it->find(text) == 0)) {
			string tmp = last ? (string(text) + (it->c_str()+strlen(last))) : *it;
			char* ret = strdup(tmp.c_str());
			it++;
			return ret;
		}
	}

	return NULL;
}

static char** completion(const char* text, int start, int end) {
	return rl_completion_matches(text, completion_generator);
}

int main(int argc, char** argv) {
	const char *eng = NULL;
	const char *eval = NULL;
	int c=0, exitcode=0;

	vector<string> path = pathparser(string(__str(MODULEDIR)) + ":" + (getenv("NATUS_PATH") ? getenv("NATUS_PATH") : ""));
	vector<string> whitelist = pathparser(getenv("NATUS_WHITELIST") ? getenv("NATUS_WHITELIST") : "");

	opterr = 0;
	while ((c = getopt (argc, argv, "c:e:n")) != -1) {
		switch (c) {
		case 'c':
			eval = optarg;
			break;
		case 'e':
			eng = optarg;
			break;
		case 'n':
			path.erase(path.begin());
			break;
		case '?':
			if (optopt == 'e')
				fprintf(stderr, "Option -%c requires an engine name.\n", optopt);
			else {
				fprintf(stderr, "Usage: %s [-c <javascript>|-e <engine>|-n|<scriptfile>]\n\n", argv[0]);
				fprintf(stderr, "Unknown option `-%c'.\n", optopt);
			}
			return 1;
		default:
			abort();
	   }
	}

	if (!engine.initialize(eng))
		error(1, 0, "Unable to init engine!");

	global = engine.newGlobal(path, whitelist);
	if (global.isUndefined())
		error(2, 0, "Unable to init global!");
	global.set("alert", global.newFunction(alert, NULL, NULL));
	global.set("dir",   global.newFunction(dir,   NULL, NULL));

	// Do the evaluation
	if (eval) {
		Value res = global.evaluate(eval);

		// Print uncaught exceptions
		if (res.isException()) {
			string msg = res.toString();
			error(8, 0, "Uncaught Exception: %s", msg.c_str());
		}

		// Let the script return exitcodes
		if (res.isNumber())
			exitcode = (int) res.toLong();

		return exitcode;
	}

	// Start the shell
	if (optind >= argc) {
		fprintf(stderr, "Natus v" PACKAGE_VERSION " - Using: %s\n", engine.getName().c_str());
		if (getenv("HOME"))
			read_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
		rl_readline_name = "natus";
		rl_attempted_completion_function = completion;
		read_history(HISTORYFILE);

		char* line;
		const char* prompt = PROMPT;
		string prev = "";

		long lcnt = 0;
		for (line=readline(prompt) ; line ; line=readline(prompt)) {
			// Strip the line
			string l = line;
			free(line);
			string::size_type start = l.find_first_not_of(" \t");
			l = start == string::npos ? string("") : l.substr(start, l.find_last_not_of(" \t")-start+1);
			if (l == "") continue;

			// Append the line to the buffer
			prev.append(l);

			// Continue to the next line
		    if (inblock(prev.c_str())) {
		    	prompt = NPRMPT;
		    	continue;
		    }
		    prompt = PROMPT;
			add_history(prev.c_str());

			Value res = global.evaluate(prev, string(), lcnt++, false);
			string msg;
			string fmt;
			msg = res.toString();
			if (res.isException()) {
				fmt = "Uncaught Exception: %s\n";
				if (prev == "exit" || prev == "quit") {
					res = res.newUndefined();
					fprintf(stderr, "Use Ctrl-D (i.e. EOF) to exit\n");
				}
			} else
				fmt = "%s\n";

			if (!res.isUndefined() && !res.isNull())
				fprintf(stderr, fmt.c_str(), msg.c_str());
			prev = "";
		}
		printf("\n");
		if (getenv("HOME"))
			write_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
		return 0;
	}

	// Get the script filename
	char *filename = argv[optind];

	// Stat our file
	struct stat st;
	if (stat(filename, &st))
		error(3, 0, "Script file does not exist: %s", filename);

	// Read in our script file
	FILE *file = fopen(filename, "r");
	if (!file)
		error(4, 0, "Unable to open file: %s", filename);
	char *jscript = new char[st.st_size + 1];
	if (!jscript) {
		fclose(file);
		error(5, 0, "Out of memory!");
	}
	if ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {
		delete[] jscript;
		fclose(file);
		error(6, 0, "Error reading file: %s", filename);
	}
	fclose(file);
	jscript[st.st_size] = '\0';

	// Evaluate it
	Value res = global.evaluate(jscript, filename ? filename : "");
	delete[] jscript;

	// Print uncaught exceptions
	if (res.isException()) {
		string msg = res.toString();
		error(8, 0, "Uncaught Exception: %s", msg.c_str());
	}

	// Let the script return exitcodes
	if (res.isNumber())
		exitcode = (int) res.toLong();

	return exitcode;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, Nagoya University
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>

#include "ros/ros.h"
#include <sensor_msgs/image_encodings.h>
#include "points2image/PointsImage.h"

#define IMAGE_WIDTH 800
#define IMAGE_HEIGHT 640

static bool existImage = false;
static bool existPoints = false;
static sensor_msgs::Image image_msg;
static points2image::PointsImageConstPtr points_msg;
static cv::Mat colormap;

static const char window_name[] = "points_image_viewer";

static void show(void)
{
	if(!existImage || !existPoints){
		return;
	}
	const auto& encoding = sensor_msgs::image_encodings::TYPE_8UC3;
	cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image_msg, encoding);
	IplImage frame = cv_image->image;

	cv::Mat matImage(&frame, false);
	cv::cvtColor(matImage, matImage, CV_BGR2RGB);

	int w = matImage.size().width;
	int h = matImage.size().height;
	int n = w * h;

	float min_d, max_d;
	min_d = max_d = points_msg->distance[0];
	for(int i=1; i<n; i++){
		float di = points_msg->distance[i];
		max_d = di > max_d ? di : max_d;
		min_d = di < min_d ? di : min_d;
	}
	float wid_d = max_d - min_d;

	for(int y=0; y<h; y++){
		for(int x=0; x<w; x++){
			int j = y * w + x;
			float distance = points_msg->distance[j];
			if(distance == 0){
				continue;
			}
			int colorid= wid_d ? ( (distance - min_d) * 255 / wid_d ) : 128;
			cv::Vec3b color=colormap.at<cv::Vec3b>(colorid);
			int g = color[1];
			int b = color[2];
			int r = color[0];
			cvRectangle(&frame, cvPoint(x, y), cvPoint(x+1, y+1), CV_RGB(r, g, b));
		}
	}

	if (cvGetWindowHandle(window_name) != NULL) // Guard not to write destroyed window by using close button on the window
	{
		cvShowImage(window_name, &frame);
		cvWaitKey(2);
	}
}

static void image_cb(const sensor_msgs::Image& msg)
{
	image_msg = msg;
	existImage = true;
	show();
}

static void points_cb(const points2image::PointsImageConstPtr& msg)
{
	points_msg = msg;
	existPoints = true;
	show();
}

int main(int argc, char **argv)
{
	/* create resizable window */
	cvNamedWindow(window_name, CV_WINDOW_NORMAL);
	cvStartWindowThread();

	ros::init(argc, argv, "points_image_viewer");
	ros::NodeHandle n;
	ros::Subscriber sub_image = n.subscribe("image_raw", 1, image_cb);
	ros::Subscriber sub_points = n.subscribe("points_image", 1, points_cb);

	cv::Mat grayscale(256,1,CV_8UC1);
	for(int i=0;i<256;i++)
	{
		grayscale.at<uchar>(i)=i;
	}
	cv::applyColorMap(grayscale,colormap,cv::COLORMAP_JET);

	ros::spin();

	cvDestroyWindow(window_name);
	return 0;
}
<commit_msg>Make pointCloud topic selectable subscribed in points_image_viewer<commit_after>/*
 *  Copyright (c) 2015, Nagoya University
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>

#include "ros/ros.h"
#include <sensor_msgs/image_encodings.h>
#include "points2image/PointsImage.h"

#define IMAGE_WIDTH 800
#define IMAGE_HEIGHT 640

static bool existImage = false;
static bool existPoints = false;
static sensor_msgs::Image image_msg;
static points2image::PointsImageConstPtr points_msg;
static cv::Mat colormap;

static const char window_name_base[] = "points_image_viewer";
static std::string window_name;

static void show(void)
{
	if(!existImage || !existPoints){
		return;
	}
	const auto& encoding = sensor_msgs::image_encodings::TYPE_8UC3;
	cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image_msg, encoding);
	IplImage frame = cv_image->image;

	cv::Mat matImage(&frame, false);
	cv::cvtColor(matImage, matImage, CV_BGR2RGB);

	int w = matImage.size().width;
	int h = matImage.size().height;
	int n = w * h;

	float min_d, max_d;
	min_d = max_d = points_msg->distance[0];
	for(int i=1; i<n; i++){
		float di = points_msg->distance[i];
		max_d = di > max_d ? di : max_d;
		min_d = di < min_d ? di : min_d;
	}
	float wid_d = max_d - min_d;

	for(int y=0; y<h; y++){
		for(int x=0; x<w; x++){
			int j = y * w + x;
			float distance = points_msg->distance[j];
			if(distance == 0){
				continue;
			}
			int colorid= wid_d ? ( (distance - min_d) * 255 / wid_d ) : 128;
			cv::Vec3b color=colormap.at<cv::Vec3b>(colorid);
			int g = color[1];
			int b = color[2];
			int r = color[0];
			cvRectangle(&frame, cvPoint(x, y), cvPoint(x+1, y+1), CV_RGB(r, g, b));
		}
	}

	if (cvGetWindowHandle(window_name.c_str()) != NULL) // Guard not to write destroyed window by using close button on the window
	{
		cvShowImage(window_name.c_str(), &frame);
		cvWaitKey(2);
	}
}

static void image_cb(const sensor_msgs::Image& msg)
{
	image_msg = msg;
	existImage = true;
	show();
}

static void points_cb(const points2image::PointsImageConstPtr& msg)
{
	points_msg = msg;
	existPoints = true;
	show();
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "points_image_viewer");
	ros::NodeHandle n;
	ros::NodeHandle private_nh("~");

	std::string points_topic;
	if (!private_nh.getParam("points_topic", points_topic)) {
		points_topic = "points_image";
	}

	std::string name_space_str = ros::this_node::getNamespace();
	window_name = std::string(window_name_base);
	if (name_space_str != "/") {
		window_name += " (" + name_space_str + ")";
	}

	/* create resizable window */
	cvNamedWindow(window_name.c_str(), CV_WINDOW_NORMAL);
	cvStartWindowThread();

	ros::Subscriber sub_image = n.subscribe("image_raw", 1, image_cb);
	ros::Subscriber sub_points = n.subscribe(points_topic, 1, points_cb);

	cv::Mat grayscale(256,1,CV_8UC1);
	for(int i=0;i<256;i++)
	{
		grayscale.at<uchar>(i)=i;
	}
	cv::applyColorMap(grayscale,colormap,cv::COLORMAP_JET);

	ros::spin();

	cvDestroyWindow(window_name.c_str());
	return 0;
}
<|endoftext|>


<commit_before>/*
 *  SinglePlayer.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 15.01.10.
 *  code under LGPL
 *
 */

#include "SinglePlayer.h"
#include "Options.h"
#include "ConfigHandler.h"
#include "game/Mod.h"
#include "game/Level.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/Menu.h"
#include "CClient.h"
#include "CServer.h"
#include "ProfileSystem.h"
#include "CWormHuman.h"

SinglePlayerGame singlePlayerGame;

int SinglePlayerGame::maxAllowedLevelForCurrentGame() {
	int level = 1;
	std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame);
	if(f != tLXOptions->localplayLevels.end())
		level = MAX(f->second, 1);
	return level;
}

void SinglePlayerGame::setGame(const std::string& game) {
	if(!stringcaseequal(currentGame, game)) {
		currentGame = game;
		setLevel(maxAllowedLevelForCurrentGame());
	}
}

static bool gameLevelExists(const std::string& game, int levelNr) {
	std::string level;
	if(!ReadString("games/games.cfg", game, "Level" + itoa(levelNr), level, "") || Trimmed(level) == "")
		return false;
	else
		return true;
}

static bool gameExists(const std::string& game) {
	return gameLevelExists(game, 1);
}

bool SinglePlayerGame::setLevel(int levelNr) {
	currentGameValid = false;
	image = NULL;
	levelInfo = LevelInfo();
	modInfo = ModInfo();
	description = "";

	if(!gameExists(currentGame)) {
		description = "Game " + currentGame + " is invalid";
		errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl;
		return false;
	}

	currentLevel = levelNr;
	if(currentLevel <= 0) currentLevel = 1;

	if(!gameLevelExists(currentGame, currentLevel)) {
		warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl;
		do { currentLevel--; }
		while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel));
		if(currentLevel <= 0) {
			errors << "SinglePlayerGame::setLevel: woot" << endl;
			return false;
		}
	}

	std::string level, mod, img;
	ReadString("games/games.cfg", currentGame, "Level" + itoa(currentLevel), level, ""); TrimSpaces(level);
	ReadString("games/games.cfg", currentGame, "Mod" + itoa(currentLevel), mod, "Classic"); TrimSpaces(mod);
	ReadString("games/games.cfg", currentGame, "Image" + itoa(currentLevel), img, ""); TrimSpaces(img);
	ReadString("games/games.cfg", currentGame, "Desc" + itoa(currentLevel), description, ""); TrimSpaces(description);

	level = "../games/" + currentGame + "/" + level; // it's relative to levels
	levelInfo = infoForLevel(level);
	if(!levelInfo.valid) {
		description = "Problem while loading level " + level + "";
		errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl;
		return false;
	}
	levelInfo.path = level; // to force this uncommon filename

	modInfo = infoForMod(mod);
	if(!modInfo.valid) {
		description = "Problem while loading mod " + mod + "";
		errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl;
		return false;
	}

	if(description == "")
		description = "Undescribed level " + itoa(currentLevel) + " of game " + currentGame + "";

	image = LoadGameImage("games/" + currentGame + "/" + img);
	if(image.get() == NULL) {
		warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl;
		image = gfxCreateSurfaceAlpha(200, 50);
		DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0));
	}

	currentGameValid = true;
	return true;
}

static bool addPlayerToClient() {
	// Initialize has cleaned up all worms, so this is not necessarily needed
	cClient->setNumWorms(0);

	std::string player = tLXOptions->sLastSelectedPlayer;
	profile_t *ply = (player == "") ? FindProfile(player) : NULL;
	if(ply == NULL) {
		for(ply = GetProfiles(); ply; ply = ply->tNext) {
			if(ply->iType == PRF_HUMAN->toInt())
				// ok
				break;
		}
	}
	if(ply == NULL) {
		// there is no single human player
		AddDefaultPlayers();
		// try again
		for(ply = GetProfiles(); ply; ply = ply->tNext) {
			if(ply->iType == PRF_HUMAN->toInt())
				// ok
				break;
		}
	}
	if(ply == NULL) {
		errors << "addPlayerToClient: this really should never happen, something very messed up happend" << endl;
		return false;
	}

	// this is the current (ugly) way to tell CClient to create a local worm later on with that profile
	// that is done in CClientNetEngine::ParseConnected or updateAddedWorms
	cClient->getLocalWormProfiles()[0] = ply;
	cClient->setNumWorms(1);

	return true;
}

static GameOptions::GameInfo oldSettings;

bool SinglePlayerGame::startGame() {
	if(!currentGameValid) {
		errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl;
		return false;
	}

	if(bDedicated) {
		errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl;
		// actually, we could but I really dont see a reason why we would want
		return false;
	}

	oldSettings = tLXOptions->tGameInfo;
	tLXOptions->tGameInfo.sMapFile = levelInfo.path;
	tLXOptions->tGameInfo.sMapName = levelInfo.name;

	tLX->iGameType = GME_LOCAL;

	if(! cClient->Initialize() )
	{
		errors << "Could not initialize client" << endl;
		return false;
	}

	if(!addPlayerToClient()) {
		errors << "SinglePlayerGame::startGame: didn't found human worm" << endl;
		return false;
	}

	if(!cServer->StartServer()) {
		errors << "Could not start server" << endl;
		return false;
	}

	tLXOptions->tGameInfo.sModDir = modInfo.path;
	tLXOptions->tGameInfo.sModName = modInfo.name;

	tLXOptions->tGameInfo.features[FT_NewNetEngine] = false;
	tLXOptions->tGameInfo.iLives = -2;
	tLXOptions->tGameInfo.iKillLimit = -1;
	tLXOptions->tGameInfo.fTimeLimit = -1;

	tLXOptions->tGameInfo.gameMode = this;

	levelSucceeded = false;
	return true;
}

void SinglePlayerGame::setLevelSucceeded() {
	levelSucceeded = true;

	if(gameLevelExists(currentGame, currentLevel + 1)) {
		setLevel(currentLevel + 1);
		tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel);
	}
}

void SinglePlayerGame::Simulate() {
	if(levelSucceeded)
		cServer->RecheckGame();
}

bool SinglePlayerGame::CheckGameOver() {
	return levelSucceeded;
}

int SinglePlayerGame::Winner() {
	for(int i = 0; i < cClient->getNumWorms(); ++i)
		if(dynamic_cast<CWormHumanInputHandler*>( cClient->getWorm(i)->getOwner() ) != NULL)
			return cClient->getWorm(i)->getID();
	return -1;
}

void SinglePlayerGame::GameOver() {
	tLXOptions->tGameInfo = oldSettings;
}

<commit_msg>small (ugly) fix<commit_after>/*
 *  SinglePlayer.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 15.01.10.
 *  code under LGPL
 *
 */

#include "SinglePlayer.h"
#include "Options.h"
#include "ConfigHandler.h"
#include "game/Mod.h"
#include "game/Level.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/Menu.h"
#include "CClient.h"
#include "CServer.h"
#include "ProfileSystem.h"
#include "CWormHuman.h"

SinglePlayerGame singlePlayerGame;

int SinglePlayerGame::maxAllowedLevelForCurrentGame() {
	int level = 1;
	std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame);
	if(f != tLXOptions->localplayLevels.end())
		level = MAX(f->second, 1);
	return level;
}

void SinglePlayerGame::setGame(const std::string& game) {
	if(!stringcaseequal(currentGame, game)) {
		currentGame = game;
		setLevel(maxAllowedLevelForCurrentGame());
	}
}

static bool gameLevelExists(const std::string& game, int levelNr) {
	std::string level;
	if(!ReadString("games/games.cfg", game, "Level" + itoa(levelNr), level, "") || Trimmed(level) == "")
		return false;
	else
		return true;
}

static bool gameExists(const std::string& game) {
	return gameLevelExists(game, 1);
}

bool SinglePlayerGame::setLevel(int levelNr) {
	currentGameValid = false;
	image = NULL;
	levelInfo = LevelInfo();
	modInfo = ModInfo();
	description = "";

	if(!gameExists(currentGame)) {
		description = "Game " + currentGame + " is invalid";
		errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl;
		return false;
	}

	currentLevel = levelNr;
	if(currentLevel <= 0) currentLevel = 1;

	if(!gameLevelExists(currentGame, currentLevel)) {
		warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl;
		do { currentLevel--; }
		while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel));
		if(currentLevel <= 0) {
			errors << "SinglePlayerGame::setLevel: woot" << endl;
			return false;
		}
	}

	std::string level, mod, img;
	ReadString("games/games.cfg", currentGame, "Level" + itoa(currentLevel), level, ""); TrimSpaces(level);
	ReadString("games/games.cfg", currentGame, "Mod" + itoa(currentLevel), mod, "Classic"); TrimSpaces(mod);
	ReadString("games/games.cfg", currentGame, "Image" + itoa(currentLevel), img, ""); TrimSpaces(img);
	ReadString("games/games.cfg", currentGame, "Desc" + itoa(currentLevel), description, ""); TrimSpaces(description);

	level = "../games/" + currentGame + "/" + level; // it's relative to levels
	levelInfo = infoForLevel(level);
	if(!levelInfo.valid) {
		description = "Problem while loading level " + level + "";
		errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl;
		return false;
	}
	levelInfo.path = level; // to force this uncommon filename

	modInfo = infoForMod(mod);
	if(!modInfo.valid) {
		description = "Problem while loading mod " + mod + "";
		errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl;
		return false;
	}

	if(description == "")
		description = "Undescribed level " + itoa(currentLevel) + " of game " + currentGame + "";

	image = LoadGameImage("games/" + currentGame + "/" + img);
	if(image.get() == NULL) {
		warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl;
		image = gfxCreateSurfaceAlpha(200, 50);
		DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0));
	}

	currentGameValid = true;
	return true;
}

static bool addPlayerToClient() {
	// Initialize has cleaned up all worms, so this is not necessarily needed
	cClient->setNumWorms(0);

	std::string player = tLXOptions->sLastSelectedPlayer;
	profile_t *ply = (player == "") ? FindProfile(player) : NULL;
	if(ply == NULL) {
		for(ply = GetProfiles(); ply; ply = ply->tNext) {
			if(ply->iType == PRF_HUMAN->toInt())
				// ok
				break;
		}
	}
	if(ply == NULL) {
		// there is no single human player
		AddDefaultPlayers();
		// try again
		for(ply = GetProfiles(); ply; ply = ply->tNext) {
			if(ply->iType == PRF_HUMAN->toInt())
				// ok
				break;
		}
	}
	if(ply == NULL) {
		errors << "addPlayerToClient: this really should never happen, something very messed up happend" << endl;
		return false;
	}

	// this is the current (ugly) way to tell CClient to create a local worm later on with that profile
	// that is done in CClientNetEngine::ParseConnected or updateAddedWorms
	cClient->getLocalWormProfiles()[0] = ply;
	cClient->setNumWorms(1);

	return true;
}

static GameOptions::GameInfo oldSettings;

bool SinglePlayerGame::startGame() {
	if(!currentGameValid) {
		errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl;
		return false;
	}

	if(bDedicated) {
		errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl;
		// actually, we could but I really dont see a reason why we would want
		return false;
	}

	oldSettings = tLXOptions->tGameInfo;
	tLXOptions->tGameInfo.sMapFile = levelInfo.path;
	tLXOptions->tGameInfo.sMapName = levelInfo.name;

	tLX->iGameType = GME_LOCAL;

	if(! cClient->Initialize() )
	{
		errors << "Could not initialize client" << endl;
		return false;
	}

	if(!addPlayerToClient()) {
		errors << "SinglePlayerGame::startGame: didn't found human worm" << endl;
		return false;
	}

	if(!cServer->StartServer()) {
		errors << "Could not start server" << endl;
		return false;
	}

	tLXOptions->tGameInfo.sModDir = modInfo.path;
	tLXOptions->tGameInfo.sModName = modInfo.name;

	tLXOptions->tGameInfo.features[FT_NewNetEngine] = false;
	tLXOptions->tGameInfo.iLives = -2;
	tLXOptions->tGameInfo.iKillLimit = -1;
	tLXOptions->tGameInfo.fTimeLimit = -1;

	tLXOptions->tGameInfo.gameMode = this;

	levelSucceeded = false;
	return true;
}

void SinglePlayerGame::setLevelSucceeded() {
	notes << "SinglePlayerGame: level was succeeded" << endl;
	levelSucceeded = true;

	if(gameLevelExists(currentGame, currentLevel + 1)) {
		setLevel(currentLevel + 1);
		tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel);
	}
}

void SinglePlayerGame::Simulate() {
	if(levelSucceeded)
		cServer->RecheckGame();
}

bool SinglePlayerGame::CheckGameOver() {
	return levelSucceeded;
}

int SinglePlayerGame::Winner() {
	for(int i = 0; i < cClient->getNumWorms(); ++i)
		if(dynamic_cast<CWormHumanInputHandler*>( cClient->getWorm(i)->getOwner() ) != NULL)
			return cClient->getWorm(i)->getID();
	return -1;
}

void SinglePlayerGame::GameOver() {
	tLXOptions->tGameInfo = oldSettings;
	// this is kind of a hack; we need it because in CClient::Draw for example,
	// we check for it to draw the congratulation msg
	tLXOptions->tGameInfo.gameMode = this;
}

<|endoftext|>


<commit_before>/*
 * mutation_class_test.cc
 */
#include "mutation_class.h"

#include "gtest/gtest.h"

#include "dynkin.h"

namespace cluster {

	TEST(MutationClass, A3) {
		QuiverMatrix mat = dynkin::A3;
		MutationClass c(mat);

		EXPECT_TRUE(c.is_finite());
		EXPECT_EQ(4, c.size());
		EXPECT_TRUE(c.contains(std::make_shared<EquivQuiverMatrix>(mat)));
	}
}
<commit_msg>Adds infinite quiver test case.<commit_after>/*
 * mutation_class_test.cc
 */
#include "mutation_class.h"

#include "gtest/gtest.h"

#include "dynkin.h"

namespace cluster {

	TEST(MutationClass, A3) {
		QuiverMatrix mat = dynkin::A3;
		MutationClass c(mat);

		EXPECT_TRUE(c.is_finite());
		EXPECT_EQ(4, c.size());
		EXPECT_TRUE(c.contains(std::make_shared<EquivQuiverMatrix>(mat)));
	}

	TEST(MutationClass, Infinite) {
		int v[] = {0,1,0,0, -1,0,1,1, 0,-1,0,1, 0,-1,-1,0};
		EquivQuiverMatrix m(4,4,v);
		MutationClass c(m);

		EXPECT_FALSE(c.is_finite());
	}
}
<|endoftext|>


<commit_before>#include <Halide.h>
#include <stdio.h>
#include "clock.h"

using namespace Halide;

int main(int argc, char **argv) {
    ImageParam src(UInt(8), 1);
    Func dst;
    Var x;
    dst(x) = src(x);

    Var xo;
    dst.split(x, xo, x, 8*4096);
    // dst.parallel(xo); speeds up halide's memcpy considerably, but doesn't seem sporting
    dst.vectorize(x, 16);

    dst.compile_to_assembly("memcpy.s", Internal::vec<Argument>(src), "memcpy");
    dst.compile_jit();

    Image<uint8_t> input(12345678);
    Image<uint8_t> output(12345678);

    src.set(input);

    // Get past one-time set-up issues for the ptx backend.
    dst.realize(output);

    double halide = 0, system = 0;
    for (int i = 0; i < 50; i++) {
        double t1 = currentTime();
        dst.realize(output);
        dst.realize(output);
        dst.realize(output);
        double t2 = currentTime();
        memcpy(output.data(), input.data(), input.width());
        memcpy(output.data(), input.data(), input.width());
        memcpy(output.data(), input.data(), input.width());
        double t3 = currentTime();
        system += t3-t2;
        halide += t2-t1;
    }

    printf("system memcpy: %f\n", system);
    printf("halide memcpy: %f\n", halide);

    // memcpy will win by a little bit for large inputs because it uses streaming stores
    if (halide > system * 1.2) {
        printf("Halide memcpy is slower than it should be.\n");
        return -1;
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Made memcpy test much more lax<commit_after>#include <Halide.h>
#include <stdio.h>
#include "clock.h"

using namespace Halide;

int main(int argc, char **argv) {
    ImageParam src(UInt(8), 1);
    Func dst;
    Var x;
    dst(x) = src(x);

    Var xo;
    dst.split(x, xo, x, 8*4096);
    // dst.parallel(xo); speeds up halide's memcpy considerably, but doesn't seem sporting
    dst.vectorize(x, 16);

    dst.compile_to_assembly("memcpy.s", Internal::vec<Argument>(src), "memcpy");
    dst.compile_jit();

    Image<uint8_t> input(12345678);
    Image<uint8_t> output(12345678);

    src.set(input);

    // Get past one-time set-up issues for the ptx backend.
    dst.realize(output);

    double halide = 0, system = 0;
    for (int i = 0; i < 50; i++) {
        double t1 = currentTime();
        dst.realize(output);
        dst.realize(output);
        dst.realize(output);
        double t2 = currentTime();
        memcpy(output.data(), input.data(), input.width());
        memcpy(output.data(), input.data(), input.width());
        memcpy(output.data(), input.data(), input.width());
        double t3 = currentTime();
        system += t3-t2;
        halide += t2-t1;
    }

    printf("system memcpy: %f\n", system);
    printf("halide memcpy: %f\n", halide);

    // memcpy will win by a little bit for large inputs because it uses streaming stores
    if (halide > system * 2) {
        printf("Halide memcpy is slower than it should be.\n");
        return -1;
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
#include <QVBoxLayout>
#include "qsoftkeystack.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow() {}
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *central = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(central);

    QPushButton *button = new QPushButton("Hello");
    layout->addWidget(button);

    QSoftKeyStack *stack = new QSoftKeyStack(central);
    QSoftKeyAction action(central);
    action.setRole(QSoftKeyAction::Back);
    int role = action.role();
    stack->push(&action);

    setCentralWidget(central);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

#include "main.moc"
<commit_msg>More code to test the stack implementatioMore code to test the stack implementationn<commit_after>
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
#include <QVBoxLayout>
#include "qsoftkeystack.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow() {}
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *central = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(central);

    QPushButton *button = new QPushButton("Hello");
    layout->addWidget(button);

    QSoftKeyStack *stack = new QSoftKeyStack(central);
    QSoftKeyAction action1(central);
    action1.setText(QString("text1"));
    action1.setRole(QSoftKeyAction::Ok);
    QSoftKeyAction action2(central);
    action2.setText(QString("text2"));
    action2.setRole(QSoftKeyAction::Back);
    QSoftKeyAction action3(central);
    action3.setText(QString("text3"));
    action3.setRole(QSoftKeyAction::Cancel);

    QList<QSoftKeyAction*> myActionList;
    myActionList.append(&action1);
    myActionList.append(&action2);
    myActionList.append(&action3);
    stack->push(myActionList);
    stack->pop();
    stack->push(&action1);

    setCentralWidget(central);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "PDBSetup.h"
#include "MolSetup.h"
#include "BondAdjacencyList.h"
#include "ConfigSetup.h"
#include "FFSetup.h"        //For geometry kinds
#include "FFConst.h"
#include "Reader.h"
#include "InputFileReader.h"
#include "Simulation.h"
#include<unistd.h>
#include "MoveSettings.h"

TEST(CheckpointTest, Check_PEN_HEX) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA
    int result = chdir("./test/input/Systems/PEN_HEX/Base/");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/PEN_HEX");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}

TEST(CheckpointTest, Check_BPTI_TIP3) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA

    int result = chdir("./test/input/Systems/BPTI_TIP3/Base/");

    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();
    Velocity & Continued_velocs = Continued.GetVelocities();
    Velocity & SingleRun_velocs = SingleRun.GetVelocities();
    BoxDimensions & Continued_boxDim = Continued.GetBoxDim();
    BoxDimensions & SingleRun_boxDim = SingleRun.GetBoxDim();
    PRNG & Continued_PRNG = Continued.GetPRNG();
    PRNG & SingleRun_PRNG = SingleRun.GetPRNG();
    Molecules & Continued_mols = Continued.GetMolecules();
    Molecules & SingleRun_mols = SingleRun.GetMolecules();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);
    EXPECT_EQ(Continued_velocs.operator==(SingleRun_velocs), true);
    EXPECT_EQ(Continued_boxDim.operator==(SingleRun_boxDim), true);
    EXPECT_EQ(Continued_PRNG.operator==(SingleRun_PRNG), true);
    EXPECT_EQ(Continued_mols.operator==(SingleRun_mols), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/BPTI_TIP3");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}

TEST(CheckpointTest, Check_K_CHANNEL_TIP3) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA

    int result = chdir("./test/input/Systems/K_CHANNEL_TIP3/Base/");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();
    Velocity & Continued_velocs = Continued.GetVelocities();
    Velocity & SingleRun_velocs = SingleRun.GetVelocities();
    BoxDimensions & Continued_boxDim = Continued.GetBoxDim();
    BoxDimensions & SingleRun_boxDim = SingleRun.GetBoxDim();
    PRNG & Continued_PRNG = Continued.GetPRNG();
    PRNG & SingleRun_PRNG = SingleRun.GetPRNG();
    Molecules & Continued_mols = Continued.GetMolecules();
    Molecules & SingleRun_mols = SingleRun.GetMolecules();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);
    EXPECT_EQ(Continued_velocs.operator==(SingleRun_velocs), true);
    EXPECT_EQ(Continued_boxDim.operator==(SingleRun_boxDim), true);
    EXPECT_EQ(Continued_PRNG.operator==(SingleRun_PRNG), true);
    EXPECT_EQ(Continued_mols.operator==(SingleRun_mols), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/K_CHANNEL_TIP3");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}<commit_msg>Dont delete trajs for KCh<commit_after>#include <gtest/gtest.h>
#include "PDBSetup.h"
#include "MolSetup.h"
#include "BondAdjacencyList.h"
#include "ConfigSetup.h"
#include "FFSetup.h"        //For geometry kinds
#include "FFConst.h"
#include "Reader.h"
#include "InputFileReader.h"
#include "Simulation.h"
#include<unistd.h>
#include "MoveSettings.h"

TEST(CheckpointTest, Check_PEN_HEX) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA
    int result = chdir("./test/input/Systems/PEN_HEX/Base/");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/PEN_HEX");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}

TEST(CheckpointTest, Check_BPTI_TIP3) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA

    int result = chdir("./test/input/Systems/BPTI_TIP3/Base/");

    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();
    Velocity & Continued_velocs = Continued.GetVelocities();
    Velocity & SingleRun_velocs = SingleRun.GetVelocities();
    BoxDimensions & Continued_boxDim = Continued.GetBoxDim();
    BoxDimensions & SingleRun_boxDim = SingleRun.GetBoxDim();
    PRNG & Continued_PRNG = Continued.GetPRNG();
    PRNG & SingleRun_PRNG = SingleRun.GetPRNG();
    Molecules & Continued_mols = Continued.GetMolecules();
    Molecules & SingleRun_mols = SingleRun.GetMolecules();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);
    EXPECT_EQ(Continued_velocs.operator==(SingleRun_velocs), true);
    EXPECT_EQ(Continued_boxDim.operator==(SingleRun_boxDim), true);
    EXPECT_EQ(Continued_PRNG.operator==(SingleRun_PRNG), true);
    EXPECT_EQ(Continued_mols.operator==(SingleRun_mols), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/BPTI_TIP3");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}

TEST(CheckpointTest, Check_K_CHANNEL_TIP3) {

    ulong base_runsteps, Continued_runsteps;
    ulong Continued_true_step;
#if !GOMC_CUDA

    int result = chdir("./test/input/Systems/K_CHANNEL_TIP3/Base/");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation base("in.conf");
    base.RunSimulation();
    result = chdir("../Continued");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    Simulation Continued("in.conf");
    result = chdir("../SingleRun");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    Simulation SingleRun("in100.conf");
    SingleRun.RunSimulation();

    MoleculeLookup & Continued_ml = Continued.GetMolLookup();
    MoleculeLookup & SingleRun_ml = SingleRun.GetMolLookup();
    MoveSettings & Continued_ms = Continued.GetMoveSettings();
    MoveSettings & SingleRun_ms = SingleRun.GetMoveSettings();
    Coordinates & Continued_coords = Continued.GetCoordinates();
    Coordinates & SingleRun_coords = SingleRun.GetCoordinates();
    Velocity & Continued_velocs = Continued.GetVelocities();
    Velocity & SingleRun_velocs = SingleRun.GetVelocities();
    BoxDimensions & Continued_boxDim = Continued.GetBoxDim();
    BoxDimensions & SingleRun_boxDim = SingleRun.GetBoxDim();
    PRNG & Continued_PRNG = Continued.GetPRNG();
    PRNG & SingleRun_PRNG = SingleRun.GetPRNG();
    Molecules & Continued_mols = Continued.GetMolecules();
    Molecules & SingleRun_mols = SingleRun.GetMolecules();

    EXPECT_EQ(Continued_ml.operator==(SingleRun_ml), true);
    EXPECT_EQ(Continued_ms.operator==(SingleRun_ms), true);
    EXPECT_EQ(Continued_coords.operator==(SingleRun_coords), true);
    EXPECT_EQ(Continued_velocs.operator==(SingleRun_velocs), true);
    EXPECT_EQ(Continued_boxDim.operator==(SingleRun_boxDim), true);
    EXPECT_EQ(Continued_PRNG.operator==(SingleRun_PRNG), true);
    EXPECT_EQ(Continued_mols.operator==(SingleRun_mols), true);

    result = chdir("../../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("./test/input/Systems/K_CHANNEL_TIP3");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    //result = system("exec rm -r ./Base/Base_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    //result = system("exec rm -r ./Continued/Continued_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }

    //result = system("exec rm -r ./SingleRun/SingleRun_*");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
    result = chdir("../../../..");
    if (result){
        std::cout << "System call failed!" << std::endl;
        exit(1);
    }
#endif
}<|endoftext|>


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

#include "syzygy/kasko/loader_lock.h"

#include "Psapi.h"

#include "base/files/file_path.h"
#include "base/strings/utf_string_conversions.h"
#include "gtest/gtest.h"
#include "syzygy/common/unittest_util.h"
#include "syzygy/pe/dia_util.h"
#include "syzygy/pe/find.h"

namespace kasko {

namespace {

base::FilePath GetModulePath(HMODULE module) {
  wchar_t module_path[MAX_PATH];
  DWORD size = ::GetModuleFileName(module, module_path, MAX_PATH);
  DCHECK(size != 0);

  return base::FilePath(module_path);
}

ULONGLONG GetModuleBaseAddress(HMODULE module) {
  return reinterpret_cast<ULONGLONG>(module);
}

class LoaderLockTest : public ::testing::Test {
 public:
  LoaderLockTest() {}
  ~LoaderLockTest() override {}

 private:
  void SetUp() override { scoped_symbol_path_.Setup(); }

  testing::ScopedSymbolPath scoped_symbol_path_;

  DISALLOW_COPY_AND_ASSIGN(LoaderLockTest);
};

}  // namespace

// Tests that the offset used for finding the loader lock address in the Process
// Environment Block is correct. This is done by looking into the PDB file for
// ntdll.
TEST_F(LoaderLockTest, SymbolOffset) {
  HMODULE ntdll_handle = ::GetModuleHandle(L"ntdll.dll");

  base::FilePath ntdll_path = GetModulePath(ntdll_handle);
  ASSERT_FALSE(ntdll_path.empty());

  base::FilePath ntdll_pdb_path;
  ASSERT_TRUE(pe::FindPdbForModule(ntdll_path, &ntdll_pdb_path));

  // Open the pdb file.
  base::win::ScopedComPtr<IDiaDataSource> source;
  ASSERT_TRUE(pe::CreateDiaSource(source.Receive()));
  base::win::ScopedComPtr<IDiaSession> session;
  ASSERT_TRUE(
      pe::CreateDiaSession(ntdll_pdb_path, source.get(), session.Receive()));

  // Set the load address of the dia session to get the computed virtual address
  // of the loader lock.
  ASSERT_HRESULT_SUCCEEDED(
      session->put_loadAddress(GetModuleBaseAddress(ntdll_handle)));

  base::win::ScopedComPtr<IDiaSymbol> global_scope;
  ASSERT_HRESULT_SUCCEEDED(session->get_globalScope(global_scope.Receive()));

  // Find the loader lock using its symbol name.
  base::win::ScopedComPtr<IDiaEnumSymbols> symbols_enum;
  ASSERT_HRESULT_SUCCEEDED(
      global_scope->findChildren(SymTagPublicSymbol, L"_LdrpLoaderLock",
                                 nsfCaseSensitive, symbols_enum.Receive()));

  // Sanity check. Only one symbol should have been found.
  LONG count = 0;
  ASSERT_HRESULT_SUCCEEDED(symbols_enum->get_Count(&count));
  ASSERT_EQ(1, count);

  base::win::ScopedComPtr<IDiaSymbol> loader_lock_symbol;
  ASSERT_HRESULT_SUCCEEDED(symbols_enum->Item(0, loader_lock_symbol.Receive()));
  ULONGLONG loader_lock_va = 0;
  ASSERT_HRESULT_SUCCEEDED(
      loader_lock_symbol->get_virtualAddress(&loader_lock_va));

  ASSERT_EQ(loader_lock_va, reinterpret_cast<uintptr_t>(GetLoaderLock()));
}

}  // namespace kasko
<commit_msg>Add missing asserts in the loader lock test<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "syzygy/kasko/loader_lock.h"

#include "Psapi.h"

#include "base/files/file_path.h"
#include "base/strings/utf_string_conversions.h"
#include "gtest/gtest.h"
#include "syzygy/common/unittest_util.h"
#include "syzygy/pe/dia_util.h"
#include "syzygy/pe/find.h"

namespace kasko {

namespace {

base::FilePath GetModulePath(HMODULE module) {
  wchar_t module_path[MAX_PATH];
  DWORD size = ::GetModuleFileName(module, module_path, MAX_PATH);
  DCHECK(size != 0);

  return base::FilePath(module_path);
}

ULONGLONG GetModuleBaseAddress(HMODULE module) {
  return reinterpret_cast<ULONGLONG>(module);
}

class LoaderLockTest : public ::testing::Test {
 public:
  LoaderLockTest() {}
  ~LoaderLockTest() override {}

 private:
  void SetUp() override { ASSERT_TRUE(scoped_symbol_path_.Setup()); }

  testing::ScopedSymbolPath scoped_symbol_path_;

  DISALLOW_COPY_AND_ASSIGN(LoaderLockTest);
};

}  // namespace

// Tests that the offset used for finding the loader lock address in the Process
// Environment Block is correct. This is done by looking into the PDB file for
// ntdll.
TEST_F(LoaderLockTest, SymbolOffset) {
  HMODULE ntdll_handle = ::GetModuleHandle(L"ntdll.dll");

  base::FilePath ntdll_path = GetModulePath(ntdll_handle);
  ASSERT_FALSE(ntdll_path.empty());

  base::FilePath ntdll_pdb_path;
  ASSERT_TRUE(pe::FindPdbForModule(ntdll_path, &ntdll_pdb_path));
  ASSERT_FALSE(ntdll_pdb_path.empty());

  // Open the pdb file.
  base::win::ScopedComPtr<IDiaDataSource> source;
  ASSERT_TRUE(pe::CreateDiaSource(source.Receive()));
  base::win::ScopedComPtr<IDiaSession> session;
  ASSERT_TRUE(
      pe::CreateDiaSession(ntdll_pdb_path, source.get(), session.Receive()));

  // Set the load address of the dia session to get the computed virtual address
  // of the loader lock.
  ASSERT_HRESULT_SUCCEEDED(
      session->put_loadAddress(GetModuleBaseAddress(ntdll_handle)));

  base::win::ScopedComPtr<IDiaSymbol> global_scope;
  ASSERT_HRESULT_SUCCEEDED(session->get_globalScope(global_scope.Receive()));

  // Find the loader lock using its symbol name.
  base::win::ScopedComPtr<IDiaEnumSymbols> symbols_enum;
  ASSERT_HRESULT_SUCCEEDED(
      global_scope->findChildren(SymTagPublicSymbol, L"_LdrpLoaderLock",
                                 nsfCaseSensitive, symbols_enum.Receive()));

  // Sanity check. Only one symbol should have been found.
  LONG count = 0;
  ASSERT_HRESULT_SUCCEEDED(symbols_enum->get_Count(&count));
  ASSERT_EQ(1, count);

  base::win::ScopedComPtr<IDiaSymbol> loader_lock_symbol;
  ASSERT_HRESULT_SUCCEEDED(symbols_enum->Item(0, loader_lock_symbol.Receive()));
  ULONGLONG loader_lock_va = 0;
  ASSERT_HRESULT_SUCCEEDED(
      loader_lock_symbol->get_virtualAddress(&loader_lock_va));

  ASSERT_EQ(loader_lock_va, reinterpret_cast<uintptr_t>(GetLoaderLock()));
}

}  // namespace kasko
<|endoftext|>


<commit_before>#include "prelude.hpp"
#include "park.hpp"
#include "builtin/thread.hpp"

namespace rubinius {
  Object* Park::park(STATE, CallFrame* call_frame) {
    utilities::thread::Mutex::LockGuard lg(mutex_);
    if(!state->check_async(call_frame)) return NULL;

    wake_ = false;
    sleeping_ = true;
    state->vm()->thread->sleep(state, cTrue);

    Object* result = cNil;
    while(!wake_) {
      {
        GCIndependent gc_guard(state, call_frame);

        cond_.wait(mutex_);
      }
      if(!state->check_async(call_frame)) {
        result = NULL;
        break;
      }
    }

    sleeping_ = false;
    state->vm()->thread->sleep(state, cFalse);
    return result;
  }

  Object* Park::park_timed(STATE, CallFrame* call_frame, struct timespec* ts) {
    utilities::thread::Mutex::LockGuard lg(mutex_);
    if(!state->check_async(call_frame)) return NULL;

    wake_ = false;
    sleeping_ = true;
    state->vm()->thread->sleep(state, cTrue);

    Object* timeout = cFalse;

    while(!wake_) {
      {
        GCIndependent gc_guard(state, call_frame);

        utilities::thread::Code status = cond_.wait_until(mutex_, ts);
        if(status == utilities::thread::cTimedOut) {
          timeout = cTrue;
          break;
        }
      }
      if(!state->check_async(call_frame)) {
        timeout = NULL;
        break;
      }
    }

    sleeping_ = false;
    state->vm()->thread->sleep(state, cFalse);

    return timeout;
  }
}
<commit_msg>Fix deadlock issue in signal handling of sleeping threads<commit_after>#include "prelude.hpp"
#include "park.hpp"
#include "builtin/thread.hpp"

namespace rubinius {
  Object* Park::park(STATE, CallFrame* call_frame) {
    utilities::thread::Mutex::LockGuard lg(mutex_);
    if(!state->check_async(call_frame)) return NULL;

    wake_ = false;
    sleeping_ = true;
    state->vm()->thread->sleep(state, cTrue);

    Object* result = cNil;
    while(!wake_) {
      {
        GCIndependent gc_guard(state, call_frame);

        cond_.wait(mutex_);
      }
      mutex_.unlock();
      if(!state->check_async(call_frame)) {
        mutex_.lock();
        result = NULL;
        break;
      }
      mutex_.lock();
    }

    sleeping_ = false;
    state->vm()->thread->sleep(state, cFalse);
    return result;
  }

  Object* Park::park_timed(STATE, CallFrame* call_frame, struct timespec* ts) {
    utilities::thread::Mutex::LockGuard lg(mutex_);
    if(!state->check_async(call_frame)) return NULL;

    wake_ = false;
    sleeping_ = true;
    state->vm()->thread->sleep(state, cTrue);

    Object* timeout = cFalse;

    while(!wake_) {
      {
        GCIndependent gc_guard(state, call_frame);

        utilities::thread::Code status = cond_.wait_until(mutex_, ts);
        if(status == utilities::thread::cTimedOut) {
          timeout = cTrue;
          break;
        }
      }
      mutex_.unlock();
      if(!state->check_async(call_frame)) {
        mutex_.lock();
        timeout = NULL;
        break;
      }
      mutex_.lock();
    }

    sleeping_ = false;
    state->vm()->thread->sleep(state, cFalse);

    return timeout;
  }
}
<|endoftext|>


<commit_before>/*
 Copyright 2017 Nervana Systems Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "base64.hpp"
#include "helpers.hpp"
#include "loader_remote.hpp"
#include "log.hpp"
#include "service.hpp"

using namespace std;
using namespace nervana;

using ::testing::Return;
using nlohmann::json;

class mock_service : public service
{
public:
    MOCK_METHOD1(create_session, service_response<string>(const std::string& config));
    MOCK_METHOD1(get_names_and_shapes, service_response<names_and_shapes>(const std::string& id));
    MOCK_METHOD1(next, service_response<next_response>(const std::string& id));
    MOCK_METHOD1(reset, service_status(const std::string& id));
    MOCK_METHOD1(close_session, service_status(const std::string& id));

    MOCK_METHOD1(record_count, service_response<int>(const std::string& id));
    MOCK_METHOD1(batch_size, service_response<int>(const std::string& id));
    MOCK_METHOD1(batch_count, service_response<int>(const std::string& id));
};

//namespace
//{
//pair<loader_remote, shared_ptr<mock_service>> create_loader_remote_with_mock();
//}

TEST(loader_remote, basic_scenario)
{
    auto           mock         = make_shared<mock_service>();
    string         config       = "{}";
    string         session_id   = "123";
    auto           nas          = get_names_and_shapes();
    int            batch_size   = 64;
    int            batch_count  = 3;
    int            record_count = batch_size * batch_count;
    service_status status_success(service_status_type::SUCCESS, "");

    auto expected_create_session = service_response<string>(status_success, session_id);
    auto expected_nas            = service_response<names_and_shapes>(status_success, nas);
    auto expected_record_count   = service_response<int>(status_success, record_count);
    auto expected_batch_size     = service_response<int>(status_success, batch_size);
    auto expected_batch_count    = service_response<int>(status_success, batch_count);
    EXPECT_CALL(*mock, create_session(config)).WillOnce(Return(expected_create_session));
    EXPECT_CALL(*mock, get_names_and_shapes(session_id)).WillOnce(Return(expected_nas));
    EXPECT_CALL(*mock, record_count(session_id)).WillOnce(Return(expected_record_count));
    EXPECT_CALL(*mock, batch_size(session_id)).WillOnce(Return(expected_batch_size));
    EXPECT_CALL(*mock, batch_count(session_id)).WillOnce(Return(expected_batch_count));

    loader_remote loader(mock, config);

    EXPECT_EQ(loader.get_names_and_shapes(), nas);
    EXPECT_EQ(loader.record_count(), record_count);
    EXPECT_EQ(loader.batch_size(), batch_size);
    EXPECT_EQ(loader.batch_count(), batch_count);

    // iteration
    {

        int index = 0;
        for(const auto& batch : loader)
        {
            index++;
        }

    }
}

//namespace
//{
//pair<loader_remote, shared_ptr<mock_service>> create_loader_remote_with_mock()
//{
//auto              mock = shared_ptr<mock_http_connector>(new mock_http_connector());
//service_connector connector(mock);

//EXPECT_CALL(
//}
//}
<commit_msg>remote_loader unit tests updated<commit_after>/*
 Copyright 2017 Nervana Systems Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "base64.hpp"
#include "helpers.hpp"
#include "loader_remote.hpp"
#include "log.hpp"
#include "service.hpp"

using namespace std;
using namespace nervana;

using ::testing::Return;
using nlohmann::json;

class mock_service : public service
{
public:
    MOCK_METHOD1(create_session, service_response<string>(const std::string& config));
    MOCK_METHOD1(get_names_and_shapes, service_response<names_and_shapes>(const std::string& id));
    MOCK_METHOD1(next, service_response<next_response>(const std::string& id));
    MOCK_METHOD1(reset, service_status(const std::string& id));
    MOCK_METHOD1(close_session, service_status(const std::string& id));

    MOCK_METHOD1(record_count, service_response<int>(const std::string& id));
    MOCK_METHOD1(batch_size, service_response<int>(const std::string& id));
    MOCK_METHOD1(batch_count, service_response<int>(const std::string& id));
};

TEST(loader_remote, new_session_scenario)
{
    auto           mock         = make_shared<mock_service>();
    json           config       = {{"server", {"address", "localhost"}, {"port", 34568}}};
    string         session_id   = "123";
    auto           nas          = get_names_and_shapes();
    int            batch_size   = 64;
    int            batch_count  = 3;
    int            record_count = batch_size * batch_count;
    service_status status_success(service_status_type::SUCCESS, "");

    auto expected_create_session = service_response<string>(status_success, session_id);
    auto expected_nas            = service_response<names_and_shapes>(status_success, nas);
    auto expected_record_count   = service_response<int>(status_success, record_count);
    auto expected_batch_size     = service_response<int>(status_success, batch_size);
    auto expected_batch_count    = service_response<int>(status_success, batch_count);
    EXPECT_CALL(*mock, create_session(config.dump())).WillOnce(Return(expected_create_session));
    EXPECT_CALL(*mock, get_names_and_shapes(session_id)).WillOnce(Return(expected_nas));
    EXPECT_CALL(*mock, record_count(session_id)).WillOnce(Return(expected_record_count));
    EXPECT_CALL(*mock, batch_size(session_id)).WillOnce(Return(expected_batch_size));
    EXPECT_CALL(*mock, batch_count(session_id)).WillOnce(Return(expected_batch_count));

    loader_remote loader(mock, config.dump());

    EXPECT_EQ(loader.get_names_and_shapes(), nas);
    EXPECT_EQ(loader.record_count(), record_count);
    EXPECT_EQ(loader.batch_size(), batch_size);
    EXPECT_EQ(loader.batch_count(), batch_count);
    EXPECT_EQ(loader.get_current_config(), config);

    // testing iteration
    {
        nervana::fixed_buffer_map* fbm = &(get_fixed_buffer_map());
        auto expected_batch = service_response<next_response>(status_success, next_response(fbm));
        auto expected_end_of_data = service_response<next_response>(
            service_status(service_status_type::END_OF_DATASET, ""), next_response());

        testing::InSequence dummy;
        EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_batch));
        EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_end_of_data));

        // iteration
        {
            int index = 0;
            for (const auto& batch : loader)
            {
                if (index == 0)
                {
                    ostringstream batch_serialized, fbm_serialized;
                    batch.serialize(batch_serialized);
                    fbm->serialize(fbm_serialized);
                    EXPECT_EQ(batch_serialized.str(), fbm_serialized.str());
                }
                index++;
            }
        }

        // reset successful
        {
            // batch is retrieved, because iteration has finished in previous step
            EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_batch));
            loader.get_current_iter();

            // no batch retrieval
            loader.get_current_iter();

            EXPECT_CALL(*mock, reset(session_id)).WillOnce(Return(status_success));
            loader.reset();

            // reset makes get_current_iter to retrieve data
            EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_batch));
            loader.get_current_iter();
        }

        // reset unsuccessful
        {
            EXPECT_CALL(*mock, reset(session_id))
                .WillOnce(Return(service_status(service_status_type::FAILURE, "some message")));
            EXPECT_THROW(loader.reset(), runtime_error);
        }
    }
}

TEST(loader_remote, shared_session_scenario)
{
    string session_id = "SESSION_ID";
    auto   mock       = make_shared<mock_service>();
    json   config     = {
        {"server", {{"address", "localhost"}, {"port", 34568}, {"session_id", session_id}}}};
    auto           nas          = get_names_and_shapes();
    int            batch_size   = 64;
    int            batch_count  = 3;
    int            record_count = batch_size * batch_count;
    service_status status_success(service_status_type::SUCCESS, "");

    auto expected_create_session = service_response<string>(status_success, session_id);
    auto expected_nas            = service_response<names_and_shapes>(status_success, nas);
    auto expected_record_count   = service_response<int>(status_success, record_count);
    auto expected_batch_size     = service_response<int>(status_success, batch_size);
    auto expected_batch_count    = service_response<int>(status_success, batch_count);
    EXPECT_CALL(*mock, get_names_and_shapes(session_id)).WillOnce(Return(expected_nas));
    EXPECT_CALL(*mock, record_count(session_id)).WillOnce(Return(expected_record_count));
    EXPECT_CALL(*mock, batch_size(session_id)).WillOnce(Return(expected_batch_size));
    EXPECT_CALL(*mock, batch_count(session_id)).WillOnce(Return(expected_batch_count));

    loader_remote loader(mock, config.dump());

    EXPECT_EQ(loader.get_names_and_shapes(), nas);
    EXPECT_EQ(loader.record_count(), record_count);
    EXPECT_EQ(loader.batch_size(), batch_size);
    EXPECT_EQ(loader.batch_count(), batch_count);
    EXPECT_EQ(loader.get_current_config(), config);

    // testing iteration
    {
        nervana::fixed_buffer_map* fbm = &(get_fixed_buffer_map());
        auto expected_batch = service_response<next_response>(status_success, next_response(fbm));
        auto expected_end_of_data = service_response<next_response>(
            service_status(service_status_type::END_OF_DATASET, ""), next_response());

        testing::InSequence dummy;
        EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_batch));
        EXPECT_CALL(*mock, next(session_id)).WillOnce(Return(expected_end_of_data));

        // iteration
        {
            int index = 0;
            for (const auto& batch : loader)
            {
                if (index == 0)
                {
                    ostringstream batch_serialized, fbm_serialized;
                    batch.serialize(batch_serialized);
                    fbm->serialize(fbm_serialized);
                    EXPECT_EQ(batch_serialized.str(), fbm_serialized.str());
                }
                index++;
            }
        }

        // reset does nothing in case of shared session
        {
            loader.reset();
        }
    }
}
<|endoftext|>