<commit_before>#include "ROOT/RDataFrame.hxx"
#include "ROOT/RTrivialDS.hxx"
#include "TMemFile.h"
#include "TTree.h"

#include "gtest/gtest.h"

using namespace ROOT;
using namespace ROOT::RDF;

TEST(RDataFrameInterface, CreateFromCStrings)
{
   RDataFrame tdf("t", "file");
}

TEST(RDataFrameInterface, CreateFromStrings)
{
   std::string t("t"), f("file");
   RDataFrame tdf(t, f);
}

TEST(RDataFrameInterface, CreateFromContainer)
{
   std::string t("t");
   std::vector<std::string> f({"f1", "f2"});
   RDataFrame tdf(t, f);
}

TEST(RDataFrameInterface, CreateFromInitList)
{
   RDataFrame tdf("t", {"f1", "f2"});
}

TEST(RDataFrameInterface, CreateFromNullTDirectory)
{
   int ret = 1;
   try {
      RDataFrame tdf("t", nullptr);
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret);
}

TEST(RDataFrameInterface, CreateFromNonExistingTree)
{
   int ret = 1;
   try {
      RDataFrame tdf("theTreeWhichDoesNotExist", gDirectory);
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret);
}

TEST(RDataFrameInterface, CreateFromTree)
{
   TMemFile f("dataframe_interfaceAndUtils_0.root", "RECREATE");
   TTree t("t", "t");
   RDataFrame tdf(t);
   auto c = tdf.Count();
   EXPECT_EQ(0U, *c);
}

TEST(RDataFrameInterface, CreateAliases)
{
   RDataFrame tdf(1);
   auto aliased_tdf = tdf.Define("c0", []() { return 0; }).Alias("c1", "c0").Alias("c2", "c0").Alias("c3", "c1");
   auto c = aliased_tdf.Count();
   EXPECT_EQ(1U, *c);

   int ret(1);
   try {
      aliased_tdf.Alias("c4", "c");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column.";

   ret = 1;
   try {
      aliased_tdf.Alias("c0", "c2");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when specifying an alias name which is the name of a column.";

   ret = 1;
   try {
      aliased_tdf.Alias("c2", "c1");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when re-using an alias for a different column.";
}

TEST(RDataFrameInterface, CheckAliasesPerChain)
{
   RDataFrame tdf(1);
   auto d = tdf.Define("c0", []() { return 0; });
   // Now branch the graph
   auto ok = []() { return true; };
   auto f0 = d.Filter(ok);
   auto f1 = d.Filter(ok);
   auto f0a = f0.Alias("c1", "c0");
   // must work
   auto f0aa = f0a.Alias("c2", "c1");
   // must fail
   auto ret = 1;
   try {
      auto f1a = f1.Alias("c2", "c1");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column.";
}

TEST(RDataFrameInterface, GetColumnNamesFromScratch)
{
   RDataFrame f(1);
   auto dummyGen = []() { return 1; };
   auto names = f.Define("a", dummyGen).Define("b", dummyGen).Define("tdfDummy_", dummyGen).GetColumnNames();
   EXPECT_STREQ("a", names[0].c_str());
   EXPECT_STREQ("b", names[1].c_str());
   EXPECT_EQ(2U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromTree)
{
   TTree t("t", "t");
   int a, b;
   t.Branch("a", &a);
   t.Branch("b", &b);
   RDataFrame tdf(t);
   auto names = tdf.GetColumnNames();
   EXPECT_STREQ("a", names[0].c_str());
   EXPECT_STREQ("a.a", names[1].c_str());
   EXPECT_STREQ("b", names[2].c_str());
   EXPECT_STREQ("b.b", names[3].c_str());
   EXPECT_EQ(4U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromOrdering)
{
   TTree t("t", "t");
   int a, b;
   t.Branch("zzz", &a);
   t.Branch("aaa", &b);
   RDataFrame tdf(t);
   auto names = tdf.GetColumnNames();
   EXPECT_STREQ("zzz", names[0].c_str());
   EXPECT_STREQ("zzz.zzz", names[1].c_str());
   EXPECT_STREQ("aaa", names[2].c_str());
   EXPECT_STREQ("aaa.aaa", names[3].c_str());
   EXPECT_EQ(4U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromSource)
{
   std::unique_ptr<RDataSource> tds(new RTrivialDS(1));
   RDataFrame tdf(std::move(tds));
   auto names = tdf.Define("b", []() { return 1; }).GetColumnNames();
   EXPECT_STREQ("b", names[0].c_str());
   EXPECT_STREQ("col0", names[1].c_str());
   EXPECT_EQ(2U, names.size());
}

TEST(RDataFrameInterface, DefaultColumns)
{
   RDataFrame tdf(8);
   ULong64_t i(0ULL);
   auto checkSlotAndEntries = [&i](unsigned int slot, ULong64_t entry) {
      EXPECT_EQ(entry, i);
      EXPECT_EQ(slot, 0U);
      i++;
   };
   tdf.Foreach(checkSlotAndEntries, {"tdfslot_", "tdfentry_"});
}

TEST(RDataFrameInterface, JitDefaultColumns)
{
   RDataFrame tdf(8);
   auto f = tdf.Filter("tdfslot_ + tdfentry_ == 3");
   auto maxEntry = f.Max("tdfentry_");
   auto minEntry = f.Min("tdfentry_");
   EXPECT_EQ(*maxEntry, *minEntry);
}
<commit_msg>[DF] Add test for validation of custom column names<commit_after>#include "ROOT/RDataFrame.hxx"
#include "ROOT/RTrivialDS.hxx"
#include "TMemFile.h"
#include "TTree.h"

#include "gtest/gtest.h"

using namespace ROOT;
using namespace ROOT::RDF;

TEST(RDataFrameInterface, CreateFromCStrings)
{
   RDataFrame tdf("t", "file");
}

TEST(RDataFrameInterface, CreateFromStrings)
{
   std::string t("t"), f("file");
   RDataFrame tdf(t, f);
}

TEST(RDataFrameInterface, CreateFromContainer)
{
   std::string t("t");
   std::vector<std::string> f({"f1", "f2"});
   RDataFrame tdf(t, f);
}

TEST(RDataFrameInterface, CreateFromInitList)
{
   RDataFrame tdf("t", {"f1", "f2"});
}

TEST(RDataFrameInterface, CreateFromNullTDirectory)
{
   int ret = 1;
   try {
      RDataFrame tdf("t", nullptr);
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret);
}

TEST(RDataFrameInterface, CreateFromNonExistingTree)
{
   int ret = 1;
   try {
      RDataFrame tdf("theTreeWhichDoesNotExist", gDirectory);
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret);
}

TEST(RDataFrameInterface, CreateFromTree)
{
   TMemFile f("dataframe_interfaceAndUtils_0.root", "RECREATE");
   TTree t("t", "t");
   RDataFrame tdf(t);
   auto c = tdf.Count();
   EXPECT_EQ(0U, *c);
}

TEST(RDataFrameInterface, CreateAliases)
{
   RDataFrame tdf(1);
   auto aliased_tdf = tdf.Define("c0", []() { return 0; }).Alias("c1", "c0").Alias("c2", "c0").Alias("c3", "c1");
   auto c = aliased_tdf.Count();
   EXPECT_EQ(1U, *c);

   int ret(1);
   try {
      aliased_tdf.Alias("c4", "c");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column.";

   ret = 1;
   try {
      aliased_tdf.Alias("c0", "c2");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when specifying an alias name which is the name of a column.";

   ret = 1;
   try {
      aliased_tdf.Alias("c2", "c1");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when re-using an alias for a different column.";
}

TEST(RDataFrameInterface, CheckAliasesPerChain)
{
   RDataFrame tdf(1);
   auto d = tdf.Define("c0", []() { return 0; });
   // Now branch the graph
   auto ok = []() { return true; };
   auto f0 = d.Filter(ok);
   auto f1 = d.Filter(ok);
   auto f0a = f0.Alias("c1", "c0");
   // must work
   auto f0aa = f0a.Alias("c2", "c1");
   // must fail
   auto ret = 1;
   try {
      auto f1a = f1.Alias("c2", "c1");
   } catch (const std::runtime_error &e) {
      ret = 0;
   }
   EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column.";
}

TEST(RDataFrameInterface, GetColumnNamesFromScratch)
{
   RDataFrame f(1);
   auto dummyGen = []() { return 1; };
   auto names = f.Define("a", dummyGen).Define("b", dummyGen).Define("tdfDummy_", dummyGen).GetColumnNames();
   EXPECT_STREQ("a", names[0].c_str());
   EXPECT_STREQ("b", names[1].c_str());
   EXPECT_EQ(2U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromTree)
{
   TTree t("t", "t");
   int a, b;
   t.Branch("a", &a);
   t.Branch("b", &b);
   RDataFrame tdf(t);
   auto names = tdf.GetColumnNames();
   EXPECT_STREQ("a", names[0].c_str());
   EXPECT_STREQ("a.a", names[1].c_str());
   EXPECT_STREQ("b", names[2].c_str());
   EXPECT_STREQ("b.b", names[3].c_str());
   EXPECT_EQ(4U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromOrdering)
{
   TTree t("t", "t");
   int a, b;
   t.Branch("zzz", &a);
   t.Branch("aaa", &b);
   RDataFrame tdf(t);
   auto names = tdf.GetColumnNames();
   EXPECT_STREQ("zzz", names[0].c_str());
   EXPECT_STREQ("zzz.zzz", names[1].c_str());
   EXPECT_STREQ("aaa", names[2].c_str());
   EXPECT_STREQ("aaa.aaa", names[3].c_str());
   EXPECT_EQ(4U, names.size());
}

TEST(RDataFrameInterface, GetColumnNamesFromSource)
{
   std::unique_ptr<RDataSource> tds(new RTrivialDS(1));
   RDataFrame tdf(std::move(tds));
   auto names = tdf.Define("b", []() { return 1; }).GetColumnNames();
   EXPECT_STREQ("b", names[0].c_str());
   EXPECT_STREQ("col0", names[1].c_str());
   EXPECT_EQ(2U, names.size());
}

TEST(RDataFrameInterface, DefaultColumns)
{
   RDataFrame tdf(8);
   ULong64_t i(0ULL);
   auto checkSlotAndEntries = [&i](unsigned int slot, ULong64_t entry) {
      EXPECT_EQ(entry, i);
      EXPECT_EQ(slot, 0U);
      i++;
   };
   tdf.Foreach(checkSlotAndEntries, {"tdfslot_", "tdfentry_"});
}

TEST(RDataFrameInterface, JitDefaultColumns)
{
   RDataFrame tdf(8);
   auto f = tdf.Filter("tdfslot_ + tdfentry_ == 3");
   auto maxEntry = f.Max("tdfentry_");
   auto minEntry = f.Min("tdfentry_");
   EXPECT_EQ(*maxEntry, *minEntry);
}

TEST(RDataFrameInterface, InvalidDefine)
{
   RDataFrame df(1);
   try {
      df.Define("1", [] { return true; });
   } catch (const std::runtime_error &e) {
      EXPECT_STREQ("Cannot define column \"1\": not a valid C++ variable name.", e.what());
   }
   try {
      df.Define("a-b", "true");
   } catch (const std::runtime_error &e) {
      EXPECT_STREQ("Cannot define column \"a-b\": not a valid C++ variable name.", e.what());
   }
}
<|endoftext|>


<commit_before>#include "command.h"
Command::Command() {
	//nothing?
}
/*Command::Command(string n) {
	commandName = n;
}
Command::Command(string n, vector<string> a) {
	commandName = n;

	args.resize(a.size());
	for(int i = 0; i < a.size(); i++) {
		args.at(i) = a.at(i);
	}
}
Command::Command(const Command &c) {
	commandName = c.getName();
}*/
Command::Command(vector <string> &v) {
	/*for(int i = 0; i < v.size(); i++) {
		cout << v.at(i) << " ";
		args.push_back(v.at(i));
	}*/
	args = v;
}

bool Command::exec() {
	if(args.at(0) == "exit") {
		exit(0);
	}

	/*char* evp[] = {const_cast<char*>( commandName.c_str() ), (char*) 0 };
        execvp( const_cast<char*>( commandName.c_str() ) , evp);*/

	cout << "Executing: " << args.at(0) << endl;
	// insert exec code here!
	vector<char*> temp;
	for(int i = 0; i <args.size(); i++) {
		temp.push_back(const_cast<char*>(args.at(i).c_str()));
	}
	temp.push_back(NULL);
	char** argArray = &temp[0];

	pid_t pID = fork();
	if(pID == 0) { //child
		cout << "Child Process here calling EXECVP" << endl;

		//execvp usage requires a const_cast<char*> of a cstr for arg1
		//and a char* array with the const_cast<char*> cstr and following arguments

		//this will call execvp on our command
		execvp(argArray[0], argArray);
	}
	else if(pID < 0) {
		cout << "Fork failure" << endl;
		exit(1);
	}
	else {	//parent
		//waitPID(); << Need help implemeting this to wait for child to finish
		cout << "Parent does nothing here" << endl;
	}

	//assuming it executed correctly
	data = true;
	return true;
}
void Command::rearg(vector <string> &v) {
	args.clear();
	for(int i = 0; i < v.size(); i++) {
		args.push_back(v.at(i));
	}
}

void Command::print() {
	//cout << "Command Name: " << commandName << endl;
	cout << "Vector of Arguments: " << endl;
	for (int i = 0; i < args.size(); i++) {
		cout << args.at(i) << " ";
	}
	cout << endl;
}

<commit_msg>fixed child process not terminating bug<commit_after>#include "command.h"
#include <sys/wait.h>

Command::Command() {
	//nothing?
}
/*Command::Command(string n) {
	commandName = n;
}
Command::Command(string n, vector<string> a) {
	commandName = n;

	args.resize(a.size());
	for(int i = 0; i < a.size(); i++) {
		args.at(i) = a.at(i);
	}
}
Command::Command(const Command &c) {
	commandName = c.getName();
}*/
Command::Command(vector <string> &v) {
	/*for(int i = 0; i < v.size(); i++) {
		cout << v.at(i) << " ";
		args.push_back(v.at(i));
	}*/
	args = v;
}

bool Command::exec() {
	if(args.at(0) == "exit") {
		exit(0);
	}

	/*char* evp[] = {const_cast<char*>( commandName.c_str() ), (char*) 0 };
        execvp( const_cast<char*>( commandName.c_str() ) , evp);*/

	cout << "Executing: " << args.at(0) << endl;
	// insert exec code here!
	vector<char*> temp;
	for(int i = 0; i <args.size(); i++) {
		temp.push_back(const_cast<char*>(args.at(i).c_str()));
	}
	temp.push_back(NULL);
	char** argArray = &temp[0];

	pid_t pID = fork();
	if(pID == 0) { //child
		cout << "Child Process here calling EXECVP" << endl;

		//execvp usage requires a const_cast<char*> of a cstr for arg1
		//and a char* array with the const_cast<char*> cstr and following arguments

		//this will call execvp on our command
		execvp(argArray[0], argArray);
	}
	else if(pID < 0) {
		cout << "Fork failure" << endl;
		exit(1);
	}
	else {	//parent
		int status;
		wait(&status);
		if(status == -1)
		{
			cout << "There was an error with wait()!! ";
			exit(1);
		}
		cout << endl;

		cout << "Parent does nothing here" << endl;
	}

	//assuming it executed correctly
	data = true;
	return true;
}
void Command::rearg(vector <string> &v) {
	args.clear();
	for(int i = 0; i < v.size(); i++) {
		args.push_back(v.at(i));
	}
}

void Command::print() {
	//cout << "Command Name: " << commandName << endl;
	cout << "Vector of Arguments: " << endl;
	for (int i = 0; i < args.size(); i++) {
		cout << args.at(i) << " ";
	}
	cout << endl;
}

<|endoftext|>


<commit_before>#include "RConfigure.h"
#include "ROOT/RRawFile.hxx"
#include "ROOT/RMakeUnique.hxx"

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>

#include "gtest/gtest.h"

using RRawFile = ROOT::Internal::RRawFile;

namespace {

/**
 * An RAII wrapper around an open temporary file on disk. It cleans up the guarded file when the wrapper object
 * goes out of scope.
 */
class FileRaii {
private:
   std::string fPath;
public:
   FileRaii(const std::string &path, const std::string &content) : fPath(path)
   {
      std::ofstream ostrm(path, std::ios::binary | std::ios::out | std::ios::trunc);
      ostrm << content;
   }
   FileRaii(const FileRaii&) = delete;
   FileRaii& operator=(const FileRaii&) = delete;
   ~FileRaii() {
      std::remove(fPath.c_str());
   }
};

/**
 * A minimal RRawFile implementation that serves data from a string. It keeps a counter of the number of read calls
 * to help veryfing the buffer logic in the base class.
 */
class RRawFileMock : public RRawFile {
public:
   std::string fContent;
   unsigned fNumReadAt;

   RRawFileMock(const std::string &content, RRawFile::ROptions options)
     : RRawFile("", options), fContent(content), fNumReadAt(0) { }

   std::unique_ptr<RRawFile> Clone() const final {
      return std::make_unique<RRawFileMock>(fContent, fOptions);
   }

   void OpenImpl() final
   {
   }

   size_t ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset) final
   {
      fNumReadAt++;
      if (offset > fContent.length())
         return 0;

      auto slice = fContent.substr(offset, nbytes);
      memcpy(buffer, slice.data(), slice.length());
      return slice.length();
   }

   std::uint64_t GetSizeImpl() final { return fContent.size(); }

   int GetFeatures() const final { return kFeatureHasSize; }
};

} // anonymous namespace

TEST(RRawFile, Empty)
{
   FileRaii emptyGuard("testEmpty", "");
   auto f = RRawFile::Create("testEmpty");
   EXPECT_TRUE(f->GetFeatures() & RRawFile::kFeatureHasSize);
   EXPECT_EQ(0u, f->GetSize());
   EXPECT_EQ(0u, f->Read(nullptr, 0));
   EXPECT_EQ(0u, f->ReadAt(nullptr, 0, 1));
   std::string line;
   EXPECT_FALSE(f->Readln(line));
}

TEST(RRawFile, Basic)
{
   FileRaii basicGuard("testBasic", "foo\nbar");
   auto f = RRawFile::Create("testBasic");
   EXPECT_EQ(7u, f->GetSize());
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("foo", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("bar", line.c_str());
   EXPECT_FALSE(f->Readln(line));
   auto clone = f->Clone();
   /// file pointer is reset by clone
   EXPECT_TRUE(clone->Readln(line));
   EXPECT_STREQ("foo", line.c_str());

   auto f2 = RRawFile::Create("NoSuchFile");
   EXPECT_THROW(f2->Readln(line), std::runtime_error);

   auto f3 = RRawFile::Create("FiLE://testBasic");
   EXPECT_EQ(7u, f3->GetSize());

   EXPECT_THROW(RRawFile::Create("://testBasic"), std::runtime_error);
   EXPECT_THROW(RRawFile::Create("Communicator://Kirk"), std::runtime_error);
}

TEST(RRawFile, Remote)
{
#ifdef R__HAS_DAVIX
   auto f = RRawFile::Create("http://root.cern.ch/files/davix.test");
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("Hello, World", line.c_str());
#else
   EXPECT_THROW(RRawFile::Create("http://root.cern.ch/files/davix.test"), std::runtime_error);
#endif
}

TEST(RRawFile, Readln)
{
   FileRaii linebreakGuard("testLinebreak", "foo\r\none\nline\r\n\r\n");
   auto f = RRawFile::Create("testLinebreak");
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("foo", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("one\nline", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_TRUE(line.empty());
   EXPECT_FALSE(f->Readln(line));
}

TEST(RRawFile, ReadV)
{
   FileRaii readvGuard("test_rawfile_readv", "Hello, World");
   auto f = RRawFile::Create("test_rawfile_readv");

   char buffer[2];
   buffer[0] = buffer[1] = 0;
   RRawFile::RIOVec iovec[2];
   iovec[0].fBuffer = &buffer[0];
   iovec[0].fOffset = 0;
   iovec[0].fSize = 1;
   iovec[1].fBuffer = &buffer[1];
   iovec[1].fOffset = 11;
   iovec[1].fSize = 2;
   f->ReadV(iovec, 2);

   EXPECT_EQ(1U, iovec[0].fOutBytes);
   EXPECT_EQ(1U, iovec[1].fOutBytes);
   EXPECT_EQ('H', buffer[0]);
   EXPECT_EQ('d', buffer[1]);
}

TEST(RRawFile, SplitUrl)
{
   EXPECT_STREQ("C:\\Data\\events.root", RRawFile::GetLocation("C:\\Data\\events.root").c_str());
   EXPECT_STREQ("///many/slashes", RRawFile::GetLocation("///many/slashes").c_str());
   EXPECT_STREQ("/many/slashes", RRawFile::GetLocation(":///many/slashes").c_str());
   EXPECT_STREQ("file", RRawFile::GetTransport("/foo").c_str());
   EXPECT_STREQ("http", RRawFile::GetTransport("http://").c_str());
   EXPECT_STREQ("", RRawFile::GetLocation("http://").c_str());
   EXPECT_STREQ("http", RRawFile::GetTransport("http://file:///bar").c_str());
}

TEST(RRawFile, ReadDirect)
{
   FileRaii directGuard("testDirect", "abc");
   char buffer;
   RRawFile::ROptions options;
   options.fBlockSize = 0;
   auto f = RRawFile::Create("testDirect");
   EXPECT_EQ(0u, f->Read(&buffer, 0));
   EXPECT_EQ(1u, f->Read(&buffer, 1));
   EXPECT_EQ('a', buffer);
   EXPECT_EQ(1u, f->ReadAt(&buffer, 1, 2));
   EXPECT_EQ('c', buffer);

}

TEST(RRawFile, ReadBuffered)
{
   char buffer[8];
   RRawFile::ROptions options;
   options.fBlockSize = 2;
   std::unique_ptr<RRawFileMock> f(new RRawFileMock("abcdef", options));

   buffer[3] = '\0';
   EXPECT_EQ(3u, f->ReadAt(buffer, 3, 1));
   EXPECT_STREQ("bcd", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;

   buffer[2] = '\0';
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2));
   EXPECT_STREQ("cd", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0));
   EXPECT_STREQ("ab", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2));
   EXPECT_STREQ("cd", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1));
   EXPECT_STREQ("bc", buffer);
   EXPECT_EQ(2u, f->fNumReadAt); f->fNumReadAt = 0;

   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0));
   EXPECT_STREQ("ab", buffer);
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1));
   EXPECT_STREQ("bb", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1));
   EXPECT_STREQ("bc", buffer);
   EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 3));
   EXPECT_STREQ("de", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 2));
   EXPECT_STREQ("ce", buffer);
   EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1));
   EXPECT_STREQ("be", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;
}

TEST(RRawFile, Mmap)
{
   std::uint64_t mapdOffset;
   std::unique_ptr<RRawFileMock> m(new RRawFileMock("", RRawFile::ROptions()));
   EXPECT_FALSE(m->GetFeatures() & RRawFile::kFeatureHasMmap);
   EXPECT_THROW(m->Map(1, 0, mapdOffset), std::runtime_error);
   EXPECT_THROW(m->Unmap(this, 1), std::runtime_error);

   void *region;
   FileRaii basicGuard("test_rawfile_mmap", "foo");
   auto f = RRawFile::Create("test_rawfile_mmap");
   if (!(f->GetFeatures() & RRawFile::kFeatureHasMmap))
      return;
   region = f->Map(2, 1, mapdOffset);
   auto innerOffset = 1 - mapdOffset;
   ASSERT_NE(region, nullptr);
   EXPECT_EQ("oo", std::string(reinterpret_cast<char *>(region) + innerOffset, 2));
   auto mapdLength = 2 + innerOffset;
   f->Unmap(region, mapdLength);
}
<commit_msg>[io] make RRawFile test pass for the unimplemented io_uring ReadV<commit_after>#include "RConfigure.h"
#include "ROOT/RRawFile.hxx"
#include "ROOT/RMakeUnique.hxx"

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>

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

using RRawFile = ROOT::Internal::RRawFile;

namespace {

/**
 * An RAII wrapper around an open temporary file on disk. It cleans up the guarded file when the wrapper object
 * goes out of scope.
 */
class FileRaii {
private:
   std::string fPath;
public:
   FileRaii(const std::string &path, const std::string &content) : fPath(path)
   {
      std::ofstream ostrm(path, std::ios::binary | std::ios::out | std::ios::trunc);
      ostrm << content;
   }
   FileRaii(const FileRaii&) = delete;
   FileRaii& operator=(const FileRaii&) = delete;
   ~FileRaii() {
      std::remove(fPath.c_str());
   }
};

/**
 * A minimal RRawFile implementation that serves data from a string. It keeps a counter of the number of read calls
 * to help veryfing the buffer logic in the base class.
 */
class RRawFileMock : public RRawFile {
public:
   std::string fContent;
   unsigned fNumReadAt;

   RRawFileMock(const std::string &content, RRawFile::ROptions options)
     : RRawFile("", options), fContent(content), fNumReadAt(0) { }

   std::unique_ptr<RRawFile> Clone() const final {
      return std::make_unique<RRawFileMock>(fContent, fOptions);
   }

   void OpenImpl() final
   {
   }

   size_t ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset) final
   {
      fNumReadAt++;
      if (offset > fContent.length())
         return 0;

      auto slice = fContent.substr(offset, nbytes);
      memcpy(buffer, slice.data(), slice.length());
      return slice.length();
   }

   std::uint64_t GetSizeImpl() final { return fContent.size(); }

   int GetFeatures() const final { return kFeatureHasSize; }
};

} // anonymous namespace

TEST(RRawFile, Empty)
{
   FileRaii emptyGuard("testEmpty", "");
   auto f = RRawFile::Create("testEmpty");
   EXPECT_TRUE(f->GetFeatures() & RRawFile::kFeatureHasSize);
   EXPECT_EQ(0u, f->GetSize());
   EXPECT_EQ(0u, f->Read(nullptr, 0));
   EXPECT_EQ(0u, f->ReadAt(nullptr, 0, 1));
   std::string line;
   EXPECT_FALSE(f->Readln(line));
}

TEST(RRawFile, Basic)
{
   FileRaii basicGuard("testBasic", "foo\nbar");
   auto f = RRawFile::Create("testBasic");
   EXPECT_EQ(7u, f->GetSize());
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("foo", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("bar", line.c_str());
   EXPECT_FALSE(f->Readln(line));
   auto clone = f->Clone();
   /// file pointer is reset by clone
   EXPECT_TRUE(clone->Readln(line));
   EXPECT_STREQ("foo", line.c_str());

   auto f2 = RRawFile::Create("NoSuchFile");
   EXPECT_THROW(f2->Readln(line), std::runtime_error);

   auto f3 = RRawFile::Create("FiLE://testBasic");
   EXPECT_EQ(7u, f3->GetSize());

   EXPECT_THROW(RRawFile::Create("://testBasic"), std::runtime_error);
   EXPECT_THROW(RRawFile::Create("Communicator://Kirk"), std::runtime_error);
}

TEST(RRawFile, Remote)
{
#ifdef R__HAS_DAVIX
   auto f = RRawFile::Create("http://root.cern.ch/files/davix.test");
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("Hello, World", line.c_str());
#else
   EXPECT_THROW(RRawFile::Create("http://root.cern.ch/files/davix.test"), std::runtime_error);
#endif
}

TEST(RRawFile, Readln)
{
   FileRaii linebreakGuard("testLinebreak", "foo\r\none\nline\r\n\r\n");
   auto f = RRawFile::Create("testLinebreak");
   std::string line;
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("foo", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_STREQ("one\nline", line.c_str());
   EXPECT_TRUE(f->Readln(line));
   EXPECT_TRUE(line.empty());
   EXPECT_FALSE(f->Readln(line));
}

TEST(RRawFile, ReadV)
{
   FileRaii readvGuard("test_rawfile_readv", "Hello, World");
   auto f = RRawFile::Create("test_rawfile_readv");

   char buffer[2];
   buffer[0] = buffer[1] = 0;
   RRawFile::RIOVec iovec[2];
   iovec[0].fBuffer = &buffer[0];
   iovec[0].fOffset = 0;
   iovec[0].fSize = 1;
   iovec[1].fBuffer = &buffer[1];
   iovec[1].fOffset = 11;
   iovec[1].fSize = 2;
#ifdef R__HAS_URING
   try {
      f->ReadV(iovec, 2);
      FAIL() << "ReadV unimplemented for io_uring backend, should throw";
   } catch (const std::runtime_error& err) {
      EXPECT_THAT(err.what(), testing::HasSubstr("io_uring ReadV unimplemented!"));
   }
#else
   f->ReadV(iovec, 2);
   EXPECT_EQ(1U, iovec[0].fOutBytes);
   EXPECT_EQ(1U, iovec[1].fOutBytes);
   EXPECT_EQ('H', buffer[0]);
   EXPECT_EQ('d', buffer[1]);
#endif
}

TEST(RRawFile, SplitUrl)
{
   EXPECT_STREQ("C:\\Data\\events.root", RRawFile::GetLocation("C:\\Data\\events.root").c_str());
   EXPECT_STREQ("///many/slashes", RRawFile::GetLocation("///many/slashes").c_str());
   EXPECT_STREQ("/many/slashes", RRawFile::GetLocation(":///many/slashes").c_str());
   EXPECT_STREQ("file", RRawFile::GetTransport("/foo").c_str());
   EXPECT_STREQ("http", RRawFile::GetTransport("http://").c_str());
   EXPECT_STREQ("", RRawFile::GetLocation("http://").c_str());
   EXPECT_STREQ("http", RRawFile::GetTransport("http://file:///bar").c_str());
}

TEST(RRawFile, ReadDirect)
{
   FileRaii directGuard("testDirect", "abc");
   char buffer;
   RRawFile::ROptions options;
   options.fBlockSize = 0;
   auto f = RRawFile::Create("testDirect");
   EXPECT_EQ(0u, f->Read(&buffer, 0));
   EXPECT_EQ(1u, f->Read(&buffer, 1));
   EXPECT_EQ('a', buffer);
   EXPECT_EQ(1u, f->ReadAt(&buffer, 1, 2));
   EXPECT_EQ('c', buffer);

}

TEST(RRawFile, ReadBuffered)
{
   char buffer[8];
   RRawFile::ROptions options;
   options.fBlockSize = 2;
   std::unique_ptr<RRawFileMock> f(new RRawFileMock("abcdef", options));

   buffer[3] = '\0';
   EXPECT_EQ(3u, f->ReadAt(buffer, 3, 1));
   EXPECT_STREQ("bcd", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;

   buffer[2] = '\0';
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2));
   EXPECT_STREQ("cd", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0));
   EXPECT_STREQ("ab", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2));
   EXPECT_STREQ("cd", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1));
   EXPECT_STREQ("bc", buffer);
   EXPECT_EQ(2u, f->fNumReadAt); f->fNumReadAt = 0;

   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0));
   EXPECT_STREQ("ab", buffer);
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1));
   EXPECT_STREQ("bb", buffer);
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1));
   EXPECT_STREQ("bc", buffer);
   EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(2u, f->ReadAt(buffer, 2, 3));
   EXPECT_STREQ("de", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 2));
   EXPECT_STREQ("ce", buffer);
   EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0;
   EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1));
   EXPECT_STREQ("be", buffer);
   EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0;
}

TEST(RRawFile, Mmap)
{
   std::uint64_t mapdOffset;
   std::unique_ptr<RRawFileMock> m(new RRawFileMock("", RRawFile::ROptions()));
   EXPECT_FALSE(m->GetFeatures() & RRawFile::kFeatureHasMmap);
   EXPECT_THROW(m->Map(1, 0, mapdOffset), std::runtime_error);
   EXPECT_THROW(m->Unmap(this, 1), std::runtime_error);

   void *region;
   FileRaii basicGuard("test_rawfile_mmap", "foo");
   auto f = RRawFile::Create("test_rawfile_mmap");
   if (!(f->GetFeatures() & RRawFile::kFeatureHasMmap))
      return;
   region = f->Map(2, 1, mapdOffset);
   auto innerOffset = 1 - mapdOffset;
   ASSERT_NE(region, nullptr);
   EXPECT_EQ("oo", std::string(reinterpret_cast<char *>(region) + innerOffset, 2));
   auto mapdLength = 2 + innerOffset;
   f->Unmap(region, mapdLength);
}
<|endoftext|>


<commit_before>#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime>
#include <assert.h>
#define pi 3.14159
#define mod 1000000007
using namespace std;
int gcd(int a, int b)
{
	if(b == 0)
	{
		return a;
	}
	else
	{
		return gcd(b , a%b);
	}
}
int main()
{
	int a,b,n,token=0,flag=0;
	scanf("%d%d%d",&a,&b,&n);
	while(1)
	{
		if(token == 0)
		{
			flag = gcd(a,n);
			n = n - flag;
			token = 1;
		}
		else
		{
			flag = gcd(b,n);
			n = n - flag;
			token = 0;
		}
		if(n <= 0)
		{
			break;
		}
	}
	if(token == 0)
	{
		printf("1");
	}
	else
	{
		printf("0");
	}
	return 0;
}

// function gcd(a, b)
//     if b = 0
//        return a;
//     else
//        return gcd(b, a mod b);
<commit_msg>Delete Epic.Game.cpp<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
// Other crap
#include <SADXModLoader.h>
#include <limits.h>
#include "minmax.h"

// This namespace
#include "input.h"
#include "rumble.h"
#include "DreamPad.h"

// TODO: mouse buttons
// TODO: fix alt+f4

struct KeyboardStick : NJS_POINT2I
{
	Uint32 directions;

	void update()
	{
		auto horizontal = directions & (Buttons_Left | Buttons_Right);

		if (horizontal == Buttons_Left)
		{
			x = -SHRT_MAX;
		}
		else if (horizontal == Buttons_Right)
		{
			x = SHRT_MAX;
		}
		else
		{
			x = 0;
		}

		auto vertical = directions & (Buttons_Up | Buttons_Down);

		if (vertical == Buttons_Up)
		{
			y = -SHRT_MAX;
		}
		else if (vertical == Buttons_Down)
		{
			y = SHRT_MAX;
		}
		else
		{
			y = 0;
		}

	}
};

struct AnalogThing
{
	Angle	angle;
	float	magnitude;
};

DataArray(AnalogThing, NormalizedAnalogs, 0x03B0E7A0, 8);
DataPointer(int, MouseMode, 0x03B0EAE0);
DataPointer(int, CursorY, 0x03B0E990);
DataPointer(int, CursorX, 0x03B0E994);
DataPointer(int, CursorMagnitude, 0x03B0E998);
DataPointer(int, CursorCos, 0x03B0E99C);
DataPointer(int, CursorSin, 0x03B0E9A0);

static bool mouse_update = false;
static NJS_POINT2I cursor = {};
static KeyboardStick sticks[2] = {};
static uint32 add_buttons = 0;

inline void set_button(Uint32& i, Uint32 value, bool key_down)
{
	if (key_down)
	{
		i |= value;
	}
	else
	{
		i &= ~value;
	}
}

static void UpdateKeyboardButtons(Uint32 key, bool down)
{
	switch (key)
	{
		default:
			break;

		case UINT_MAX:
			set_button(add_buttons, key, down);
			break;

		case 'X':
		case VK_SPACE:
			set_button(add_buttons, Buttons_A, down);
			break;
		case 'Z':
			set_button(add_buttons, Buttons_B, down);
			break;
		case 'A':
			set_button(add_buttons, Buttons_X, down);
			break;
		case 'S':
			set_button(add_buttons, Buttons_Y, down);
			break;
		case 'Q':
			set_button(add_buttons, Buttons_L, down);
			break;
		case 'W':
			set_button(add_buttons, Buttons_R, down);
			break;
		case VK_RETURN:
			set_button(add_buttons, Buttons_Start, down);
			break;
		case 'D':
			set_button(add_buttons, Buttons_Z, down);
			break;
		case 'C':
			set_button(add_buttons, Buttons_C, down);
			break;
		case 'E':
			set_button(add_buttons, Buttons_D, down);
			break;

			// D-Pad
		case VK_NUMPAD8:
			set_button(add_buttons, Buttons_Up, down);
			break;
		case VK_NUMPAD5:
			set_button(add_buttons, Buttons_Down, down);
			break;
		case VK_NUMPAD4:
			set_button(add_buttons, Buttons_Left, down);
			break;
		case VK_NUMPAD6:
			set_button(add_buttons, Buttons_Right, down);
			break;

			// Left stick
		case VK_UP:
			set_button(sticks[0].directions, Buttons_Up, down);
			break;
		case VK_DOWN:
			set_button(sticks[0].directions, Buttons_Down, down);
			break;
		case VK_LEFT:
			set_button(sticks[0].directions, Buttons_Left, down);
			break;
		case VK_RIGHT:
			set_button(sticks[0].directions, Buttons_Right, down);
			break;

			// Right stick
		case 'I':
			set_button(sticks[1].directions, Buttons_Up, down);
			break;
		case 'K':
			set_button(sticks[1].directions, Buttons_Down, down);
			break;
		case 'J':
			set_button(sticks[1].directions, Buttons_Left, down);
			break;
		case 'L':
			set_button(sticks[1].directions, Buttons_Right, down);
			break;
	}
}

static void UpdateCursor(Sint32 xrel, Sint32 yrel)
{
	if (!mouse_update)
	{
		return;
	}

	CursorX = clamp(CursorX + xrel, -200, 200);
	CursorY = clamp(CursorY + yrel, -200, 200);

	auto& x = CursorX;
	auto& y = CursorY;

	auto m = x * x + y * y;

	if (m <= 625)
	{
		CursorMagnitude = 0;
		return;
	}

	CursorMagnitude = m / 361;

	if (CursorMagnitude >= 1)
	{
		if (CursorMagnitude > 120)
		{
			CursorMagnitude = 127;
		}
	}
	else
	{
		CursorMagnitude = 1;
	}

	njPushMatrix((NJS_MATRIX*)0x0389D650);

	auto r = (Angle)(atan2((double)x, (double)y) * 65536.0 * 0.1591549762031479);

	if (r)
	{
		njRotateZ(nullptr, r);
	}

	NJS_VECTOR v = { 0.0f, (float)CursorMagnitude * 1.2f, 0.0f };
	njCalcVector(nullptr, &v, &v);

	CursorCos = (int)v.x;
	CursorSin = (int)v.y;

	auto& p = cursor;
	p.x = (Sint16)clamp((int)(-v.x / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX);
	p.y = (Sint16)clamp((int)(v.y / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX);

	njPopMatrix(1);
}

static void ResetCursor()
{
	CursorMagnitude = 0;
	CursorCos       = 0;
	CursorSin       = 0;
	CursorX         = 0;
	CursorY         = 0;
	cursor          = {};
	mouse_update    = false;
}

static void UpdateMouseButtons(Uint32 button, bool down)
{
	switch (button)
	{
		case VK_LBUTTON:
			if (!down && !MouseMode)
			{
				ResetCursor();
			}
			mouse_update = down;
			break;

		case VK_MBUTTON:
		case VK_RBUTTON:
			break;

		default:
			break;
	}
}

DataPointer(HWND, hWnd, 0x3D0FD30);
WNDPROC lpPrevWndFunc = nullptr;

namespace input
{
	ControllerData RawInput[GAMEPAD_COUNT];
	bool _ControllerEnabled[GAMEPAD_COUNT];
	bool debug = false;

	LRESULT __stdcall PollKeyboardMouse(HWND handle, UINT Msg, WPARAM wParam, LPARAM lParam)
	{
		switch (Msg)
		{
			case WM_KEYDOWN:
			case WM_KEYUP:
				if (wParam <= VK_XBUTTON2)
				{
					UpdateMouseButtons(wParam, Msg == WM_KEYDOWN);
				}
				else
				{
					UpdateKeyboardButtons(wParam, Msg == WM_KEYDOWN);
				}
				break;

			case WM_MOUSEMOVE:
				break;

			case WM_MOUSEWHEEL:
				break;

			default:
				break;
		}

		return CallWindowProc(lpPrevWndFunc, handle, Msg, wParam, lParam);
	}

	void HookWndProc()
	{
		if (lpPrevWndFunc == nullptr)
		{
			lpPrevWndFunc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)PollKeyboardMouse);
		}
	}

	void PollControllers()
	{
		HookWndProc();

		SDL_Event event;
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				default:
					break;

				case SDL_CONTROLLERDEVICEADDED:
				{
					int which = event.cdevice.which;
					for (uint i = 0; i < GAMEPAD_COUNT; i++)
					{
						// Checking for both in cases like the DualShock 4 and DS4Windows where the controller might be
						// "connected" twice with the same ID. DreamPad::Open automatically closes if already open.
						if (!DreamPad::Controllers[i].Connected() || DreamPad::Controllers[i].ControllerID() == which)
						{
							DreamPad::Controllers[i].Open(which);
							break;
						}
					}
					break;
				}

				case SDL_CONTROLLERDEVICEREMOVED:
				{
					int which = event.cdevice.which;
					for (uint i = 0; i < GAMEPAD_COUNT; i++)
					{
						if (DreamPad::Controllers[i].ControllerID() == which)
						{
							DreamPad::Controllers[i].Close();
							break;
						}
					}
					break;
				}
#if 0
				case SDL_MOUSEMOTION:
				{
					UpdateCursor(event.motion.xrel, event.motion.yrel);
					break;
				}
#endif
			}
		}

		sticks[0].update();
		sticks[1].update();

		if (sticks[0].x || sticks[0].y)
		{
			ResetCursor();
		}
		else
		{
			(NJS_POINT2I)sticks[0] = cursor;
		}

		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			DreamPad& dpad = DreamPad::Controllers[i];

			auto buttons = !i ? add_buttons : 0;
			NJS_POINT2I* ls = !i ? &sticks[0] : nullptr;
			NJS_POINT2I* rs = !i ? &sticks[1] : nullptr;

			dpad.Poll(buttons, ls, rs);
			dpad.Copy(RawInput[i]);

			// Compatibility for mods who use ControllersRaw directly.
			// This will only copy the first four controllers.
			if (i < ControllersRaw_Length)
			{
				ControllersRaw[i] = RawInput[i];
			}

#ifdef EXTENDED_BUTTONS
			if (debug && RawInput[i].HeldButtons & Buttons_C)
			{
				ControllerData* pad = &RawInput[i];
				Motor m = DreamPad::Controllers[i].GetActiveMotor();

				DisplayDebugStringFormatted(NJM_LOCATION(0, 8 + (3 * i)), "P%d  B: %08X LT/RT: %03d/%03d V: %d%d", (i + 1),
					pad->HeldButtons, pad->LTriggerPressure, pad->RTriggerPressure, (m & Motor::Large), (m & Motor::Small) >> 1);
				DisplayDebugStringFormatted(NJM_LOCATION(4, 9 + (3 * i)), "LS: % 4d/% 4d RS: % 4d/% 4d",
					pad->LeftStickX, pad->LeftStickY, pad->RightStickX, pad->RightStickY);

				if (pad->HeldButtons & Buttons_Z)
				{
					int pressed = pad->PressedButtons;
					if (pressed & Buttons_Up)
					{
						dpad.settings.rumbleFactor += 0.125f;
					}
					else if (pressed & Buttons_Down)
					{
						dpad.settings.rumbleFactor -= 0.125f;
					}
					else if (pressed & Buttons_Left)
					{
						rumble::RumbleA(i, 0);
					}
					else if (pressed & Buttons_Right)
					{
						rumble::RumbleB(i, 7, 59, 6);
					}

					DisplayDebugStringFormatted(NJM_LOCATION(4, 10 + (3 * i)), "Rumble factor (U/D): %f (L/R to test)", dpad.settings.rumbleFactor);
				}
			}
#endif
		}
	}

	static void FixAnalogs()
	{
		if (!ControlEnabled)
		{
			return;
		}

		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			if (!_ControllerEnabled[i])
			{
				continue;
			}

			const DreamPad& dreamPad = DreamPad::Controllers[i];

			if (dreamPad.Connected())
			{
				const ControllerData& pad = dreamPad.DreamcastData();
				// SADX's internal deadzone is 12 of 127. It doesn't set the relative forward direction
				// unless this is exceeded in WriteAnalogs(), so the analog shouldn't be set otherwise.
				if (abs(pad.LeftStickX) > 12 || abs(pad.LeftStickY) > 12)
				{
					NormalizedAnalogs[i].magnitude = dreamPad.NormalizedL();
				}
			}
		}
	}

	void __declspec(naked) WriteAnalogs_Hook()
	{
		__asm
		{
			call FixAnalogs
			ret
		}
	}

	static void RedirectRawControllers()
	{
		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			ControllerPointers[i] = &RawInput[i];
		}
	}

	void __declspec(naked) RedirectRawControllers_Hook()
	{
		__asm
		{
			call RedirectRawControllers
			ret
		}
	}

	void EnableController_hook(Uint8 index)
	{
		// default behavior
		if (index > 1)
		{
			_ControllerEnabled[0] = true;
			_ControllerEnabled[1] = true;
		}

		if (index > GAMEPAD_COUNT)
		{
			for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++)
			{
				EnableController_hook(i);
			}
		}
		else
		{
			_ControllerEnabled[index] = true;
		}
	}

	void DisableController_hook(Uint8 index)
	{
		// default behavior
		if (index > 1)
		{
			_ControllerEnabled[0] = false;
			_ControllerEnabled[1] = false;
		}

		if (index > GAMEPAD_COUNT)
		{
			for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++)
			{
				DisableController_hook(i);
			}
		}
		else
		{
			_ControllerEnabled[index] = false;
		}
	}
}
<commit_msg>oops I forgot the mouse<commit_after>#include "stdafx.h"
// Other crap
#include <SADXModLoader.h>
#include <limits.h>
#include "minmax.h"

// This namespace
#include "input.h"
#include "rumble.h"
#include "DreamPad.h"

// TODO: mouse buttons
// TODO: fix alt+f4

struct KeyboardStick : NJS_POINT2I
{
	Uint32 directions;

	void update()
	{
		auto horizontal = directions & (Buttons_Left | Buttons_Right);

		if (horizontal == Buttons_Left)
		{
			x = -SHRT_MAX;
		}
		else if (horizontal == Buttons_Right)
		{
			x = SHRT_MAX;
		}
		else
		{
			x = 0;
		}

		auto vertical = directions & (Buttons_Up | Buttons_Down);

		if (vertical == Buttons_Up)
		{
			y = -SHRT_MAX;
		}
		else if (vertical == Buttons_Down)
		{
			y = SHRT_MAX;
		}
		else
		{
			y = 0;
		}

	}
};

struct AnalogThing
{
	Angle	angle;
	float	magnitude;
};

DataArray(AnalogThing, NormalizedAnalogs, 0x03B0E7A0, 8);
DataPointer(int, MouseMode, 0x03B0EAE0);
DataPointer(int, CursorY, 0x03B0E990);
DataPointer(int, CursorX, 0x03B0E994);
DataPointer(int, CursorMagnitude, 0x03B0E998);
DataPointer(int, CursorCos, 0x03B0E99C);
DataPointer(int, CursorSin, 0x03B0E9A0);

static bool mouse_update = false;
static NJS_POINT2I cursor = {};
static KeyboardStick sticks[2] = {};
static uint32 add_buttons = 0;

inline void set_button(Uint32& i, Uint32 value, bool key_down)
{
	if (key_down)
	{
		i |= value;
	}
	else
	{
		i &= ~value;
	}
}

static void UpdateKeyboardButtons(Uint32 key, bool down)
{
	switch (key)
	{
		default:
			break;

		case UINT_MAX:
			set_button(add_buttons, key, down);
			break;

		case 'X':
		case VK_SPACE:
			set_button(add_buttons, Buttons_A, down);
			break;
		case 'Z':
			set_button(add_buttons, Buttons_B, down);
			break;
		case 'A':
			set_button(add_buttons, Buttons_X, down);
			break;
		case 'S':
			set_button(add_buttons, Buttons_Y, down);
			break;
		case 'Q':
			set_button(add_buttons, Buttons_L, down);
			break;
		case 'W':
			set_button(add_buttons, Buttons_R, down);
			break;
		case VK_RETURN:
			set_button(add_buttons, Buttons_Start, down);
			break;
		case 'D':
			set_button(add_buttons, Buttons_Z, down);
			break;
		case 'C':
			set_button(add_buttons, Buttons_C, down);
			break;
		case 'E':
			set_button(add_buttons, Buttons_D, down);
			break;

			// D-Pad
		case VK_NUMPAD8:
			set_button(add_buttons, Buttons_Up, down);
			break;
		case VK_NUMPAD5:
			set_button(add_buttons, Buttons_Down, down);
			break;
		case VK_NUMPAD4:
			set_button(add_buttons, Buttons_Left, down);
			break;
		case VK_NUMPAD6:
			set_button(add_buttons, Buttons_Right, down);
			break;

			// Left stick
		case VK_UP:
			set_button(sticks[0].directions, Buttons_Up, down);
			break;
		case VK_DOWN:
			set_button(sticks[0].directions, Buttons_Down, down);
			break;
		case VK_LEFT:
			set_button(sticks[0].directions, Buttons_Left, down);
			break;
		case VK_RIGHT:
			set_button(sticks[0].directions, Buttons_Right, down);
			break;

			// Right stick
		case 'I':
			set_button(sticks[1].directions, Buttons_Up, down);
			break;
		case 'K':
			set_button(sticks[1].directions, Buttons_Down, down);
			break;
		case 'J':
			set_button(sticks[1].directions, Buttons_Left, down);
			break;
		case 'L':
			set_button(sticks[1].directions, Buttons_Right, down);
			break;
	}
}

static void UpdateCursor(Sint32 xrel, Sint32 yrel)
{
	if (!mouse_update)
	{
		return;
	}

	CursorX = clamp(CursorX + xrel, -200, 200);
	CursorY = clamp(CursorY + yrel, -200, 200);

	auto& x = CursorX;
	auto& y = CursorY;

	auto m = x * x + y * y;

	if (m <= 625)
	{
		CursorMagnitude = 0;
		return;
	}

	CursorMagnitude = m / 361;

	if (CursorMagnitude >= 1)
	{
		if (CursorMagnitude > 120)
		{
			CursorMagnitude = 127;
		}
	}
	else
	{
		CursorMagnitude = 1;
	}

	njPushMatrix((NJS_MATRIX*)0x0389D650);

	auto r = (Angle)(atan2((double)x, (double)y) * 65536.0 * 0.1591549762031479);

	if (r)
	{
		njRotateZ(nullptr, r);
	}

	NJS_VECTOR v = { 0.0f, (float)CursorMagnitude * 1.2f, 0.0f };
	njCalcVector(nullptr, &v, &v);

	CursorCos = (int)v.x;
	CursorSin = (int)v.y;

	auto& p = cursor;
	p.x = (Sint16)clamp((int)(-v.x / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX);
	p.y = (Sint16)clamp((int)(v.y / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX);

	njPopMatrix(1);
}

static void ResetCursor()
{
	CursorMagnitude = 0;
	CursorCos       = 0;
	CursorSin       = 0;
	CursorX         = 0;
	CursorY         = 0;
	cursor          = {};
	mouse_update    = false;
}

static void UpdateMouseButtons(Uint32 button, bool down)
{
	switch (button)
	{
		case VK_LBUTTON:
			if (!down && !MouseMode)
			{
				ResetCursor();
			}
			mouse_update = down;
			break;

		case VK_MBUTTON:
		case VK_RBUTTON:
			break;

		default:
			break;
	}
}

DataPointer(HWND, hWnd, 0x3D0FD30);
static WNDPROC lpPrevWndFunc = nullptr;

static Sint16 mouse_x = 0;
static Sint16 mouse_y = 0;

namespace input
{
	ControllerData RawInput[GAMEPAD_COUNT];
	bool _ControllerEnabled[GAMEPAD_COUNT];
	bool debug = false;

	LRESULT __stdcall PollKeyboardMouse(HWND handle, UINT Msg, WPARAM wParam, LPARAM lParam)
	{
		switch (Msg)
		{
			case WM_LBUTTONDOWN:
			case WM_LBUTTONUP:
				UpdateMouseButtons(VK_LBUTTON, Msg == WM_LBUTTONDOWN);
				break;
			case WM_RBUTTONDOWN:
			case WM_RBUTTONUP:
				UpdateMouseButtons(VK_RBUTTON, Msg == WM_RBUTTONDOWN);
				break;
			case WM_MBUTTONDOWN:
			case WM_MBUTTONUP:
				UpdateMouseButtons(VK_MBUTTON, Msg == WM_MBUTTONDOWN);
				break;

			case WM_SYSKEYUP:
			case WM_SYSKEYDOWN:
			case WM_KEYDOWN:
			case WM_KEYUP:
				UpdateKeyboardButtons(wParam, Msg == WM_KEYDOWN || Msg == WM_SYSKEYDOWN);
				break;

			case WM_MOUSEMOVE:
			{
				auto x = (short)(lParam & 0xFFFF);
				auto y = (short)(lParam >> 16);

				UpdateCursor(x - mouse_x, y - mouse_y);

				mouse_x = x;
				mouse_y = y;
				break;
			}

			case WM_MOUSEWHEEL:
				break;

			default:
				break;
		}

		return CallWindowProc(lpPrevWndFunc, handle, Msg, wParam, lParam);
	}

	void HookWndProc()
	{
		if (lpPrevWndFunc == nullptr)
		{
			lpPrevWndFunc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)PollKeyboardMouse);
		}
	}

	void PollControllers()
	{
		HookWndProc();

		SDL_Event event;
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				default:
					break;

				case SDL_CONTROLLERDEVICEADDED:
				{
					int which = event.cdevice.which;
					for (uint i = 0; i < GAMEPAD_COUNT; i++)
					{
						// Checking for both in cases like the DualShock 4 and DS4Windows where the controller might be
						// "connected" twice with the same ID. DreamPad::Open automatically closes if already open.
						if (!DreamPad::Controllers[i].Connected() || DreamPad::Controllers[i].ControllerID() == which)
						{
							DreamPad::Controllers[i].Open(which);
							break;
						}
					}
					break;
				}

				case SDL_CONTROLLERDEVICEREMOVED:
				{
					int which = event.cdevice.which;
					for (uint i = 0; i < GAMEPAD_COUNT; i++)
					{
						if (DreamPad::Controllers[i].ControllerID() == which)
						{
							DreamPad::Controllers[i].Close();
							break;
						}
					}
					break;
				}
			}
		}

		sticks[0].update();
		sticks[1].update();

		if (sticks[0].x || sticks[0].y)
		{
			ResetCursor();
		}
		else
		{
			*(NJS_POINT2I*)&sticks[0] = cursor;
		}

		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			DreamPad& dpad = DreamPad::Controllers[i];

			auto buttons = !i ? add_buttons : 0;
			NJS_POINT2I* ls = !i ? &sticks[0] : nullptr;
			NJS_POINT2I* rs = !i ? &sticks[1] : nullptr;

			dpad.Poll(buttons, ls, rs);
			dpad.Copy(RawInput[i]);

			// Compatibility for mods who use ControllersRaw directly.
			// This will only copy the first four controllers.
			if (i < ControllersRaw_Length)
			{
				ControllersRaw[i] = RawInput[i];
			}

#ifdef EXTENDED_BUTTONS
			if (debug && RawInput[i].HeldButtons & Buttons_C)
			{
				ControllerData* pad = &RawInput[i];
				Motor m = DreamPad::Controllers[i].GetActiveMotor();

				DisplayDebugStringFormatted(NJM_LOCATION(0, 8 + (3 * i)), "P%d  B: %08X LT/RT: %03d/%03d V: %d%d", (i + 1),
					pad->HeldButtons, pad->LTriggerPressure, pad->RTriggerPressure, (m & Motor::Large), (m & Motor::Small) >> 1);
				DisplayDebugStringFormatted(NJM_LOCATION(4, 9 + (3 * i)), "LS: % 4d/% 4d RS: % 4d/% 4d",
					pad->LeftStickX, pad->LeftStickY, pad->RightStickX, pad->RightStickY);

				if (pad->HeldButtons & Buttons_Z)
				{
					int pressed = pad->PressedButtons;
					if (pressed & Buttons_Up)
					{
						dpad.settings.rumbleFactor += 0.125f;
					}
					else if (pressed & Buttons_Down)
					{
						dpad.settings.rumbleFactor -= 0.125f;
					}
					else if (pressed & Buttons_Left)
					{
						rumble::RumbleA(i, 0);
					}
					else if (pressed & Buttons_Right)
					{
						rumble::RumbleB(i, 7, 59, 6);
					}

					DisplayDebugStringFormatted(NJM_LOCATION(4, 10 + (3 * i)), "Rumble factor (U/D): %f (L/R to test)", dpad.settings.rumbleFactor);
				}
			}
#endif
		}
	}

	static void FixAnalogs()
	{
		if (!ControlEnabled)
		{
			return;
		}

		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			if (!_ControllerEnabled[i])
			{
				continue;
			}

			const DreamPad& dreamPad = DreamPad::Controllers[i];

			if (dreamPad.Connected())
			{
				const ControllerData& pad = dreamPad.DreamcastData();
				// SADX's internal deadzone is 12 of 127. It doesn't set the relative forward direction
				// unless this is exceeded in WriteAnalogs(), so the analog shouldn't be set otherwise.
				if (abs(pad.LeftStickX) > 12 || abs(pad.LeftStickY) > 12)
				{
					NormalizedAnalogs[i].magnitude = dreamPad.NormalizedL();
				}
			}
		}
	}

	void __declspec(naked) WriteAnalogs_Hook()
	{
		__asm
		{
			call FixAnalogs
			ret
		}
	}

	static void RedirectRawControllers()
	{
		for (uint i = 0; i < GAMEPAD_COUNT; i++)
		{
			ControllerPointers[i] = &RawInput[i];
		}
	}

	void __declspec(naked) RedirectRawControllers_Hook()
	{
		__asm
		{
			call RedirectRawControllers
			ret
		}
	}

	void EnableController_hook(Uint8 index)
	{
		// default behavior
		if (index > 1)
		{
			_ControllerEnabled[0] = true;
			_ControllerEnabled[1] = true;
		}

		if (index > GAMEPAD_COUNT)
		{
			for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++)
			{
				EnableController_hook(i);
			}
		}
		else
		{
			_ControllerEnabled[index] = true;
		}
	}

	void DisableController_hook(Uint8 index)
	{
		// default behavior
		if (index > 1)
		{
			_ControllerEnabled[0] = false;
			_ControllerEnabled[1] = false;
		}

		if (index > GAMEPAD_COUNT)
		{
			for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++)
			{
				DisableController_hook(i);
			}
		}
		else
		{
			_ControllerEnabled[index] = false;
		}
	}
}
<|endoftext|>


<commit_before>
#include <assert.h>
#include <thread>

#include "LinkedList.hpp"

void test0() {
	LinkedList<int> l;
	l._checkSanity();

	auto item = l.push_back();
	item->value = 42;
	item = NULL;
	l._checkSanity();
	assert(l.size() == 1);

	auto ret = l.pop_front();
	assert(ret);
	assert(ret->value == 42);
	ret = NULL;

	assert(l.empty());
	assert(l.size() == 0);
	l._checkSanity();
}

void test1() {
	LinkedList<int> l;
	l._checkSanity();

	for(int i = 0; i < 100; ++i) {
		auto item = l.push_back();
		l._checkSanity();
		item->value = i;
	}

	for(int i = 0; i < 100; ++i) {
		auto ret = l.pop_front();
		l._checkSanity();
		assert(ret);
		assert(ret->value == i);
	}

	assert(l.empty());
}

void test2() {
	LinkedList<int> l;
	l._checkSanity();

	auto producer = [&l](){
		for(int i = 0; i < 100; ++i) {
			LinkedList<int>::ItemPtr item(new LinkedList<int>::Item);
			item->value = i;
			l.push_back(item);
		}
	};

	auto consumer = [&l](){
		for(int i = 0; i < 100; ++i) {
			while(l.empty()); // wait for entry
			auto ret = l.pop_front();
			assert(ret);
			assert(ret->value == i);
		}
	};

	for(int i = 0; i < 1000; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(l.empty());
		l._checkSanity();
	}
}

int main() {
	test0();
	test1();
	test2();
}
<commit_msg>more testing<commit_after>
#include <assert.h>
#include <thread>

#include "LinkedList.hpp"

void test0() {
	LinkedList<int> l;
	assert(l.empty());
	l._checkSanity();

	auto item = l.push_back();
	item->value = 42;
	item = NULL;
	l._checkSanity();
	assert(!l.empty());
	assert(l.size() == 1);

	auto ret = l.pop_front();
	assert(ret);
	assert(ret->value == 42);
	ret = NULL;

	assert(l.empty());
	assert(l.size() == 0);
	l._checkSanity();
}

void test1() {
	LinkedList<int> l;
	l._checkSanity();

	for(int i = 0; i < 100; ++i) {
		auto item = l.push_back();
		l._checkSanity();
		item->value = i;
	}

	assert(!l.empty());
	assert(l.size() == 100);

	for(int i = 0; i < 100; ++i) {
		auto ret = l.pop_front();
		l._checkSanity();
		assert(ret);
		assert(ret->value == i);
	}

	assert(l.empty());
}

void test2() {
	LinkedList<int> l;
	l._checkSanity();

	auto producer = [&l](){
		for(int i = 0; i < 100; ++i) {
			LinkedList<int>::ItemPtr item(new LinkedList<int>::Item);
			item->value = i;
			l.push_back(item);
		}
	};

	auto consumer = [&l](){
		for(int i = 0; i < 100; ++i) {
			while(l.empty()); // wait for entry
			auto ret = l.pop_front();
			assert(ret);
			assert(ret->value == i);
		}
	};

	for(int i = 0; i < 1000; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(l.empty());
		l._checkSanity();
	}
}

int main() {
	test0();
	test1();
	test2();
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  if (browser_view->IsBrowserTypePopup() ||
      browser_view->IsBrowserTypePanel()) {
    // TODO(anicolao): implement popups for touch
    NOTIMPLEMENTED();
    return NULL;
  } else {
    return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser
<commit_msg>Use the non-touch popup frame instead of NULL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  if (browser_view->IsBrowserTypePopup() ||
      browser_view->IsBrowserTypePanel()) {
    // TODO(anicolao): implement popups for touch
    NOTIMPLEMENTED();
    return new PopupNonClientFrameView(frame);
  } else {
    return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include <thread>

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false;
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false;
#endif

//Flag to disable the creation of temporary in expressions
#ifdef ETL_NO_TEMPORARY
constexpr const bool create_temporary = false;
#else
constexpr const bool create_temporary = true;
#endif

#ifdef ETL_PARALLEL
constexpr const bool parallel = true;
#else
constexpr const bool parallel = false;
#endif

#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads = std::thread::hardware_concurrency();
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

struct is_mkl_enabled : std::true_type {};
struct has_fast_fft : std::true_type {};

#else

struct is_mkl_enabled : std::false_type {};
struct has_fast_fft : std::false_type {};

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
struct is_cblas_enabled : std::true_type {};
#else
struct is_cblas_enabled : std::false_type {};
#endif

#ifdef ETL_CUBLAS_MODE
struct is_cublas_enabled : std::true_type {};
#else
struct is_cublas_enabled : std::false_type {};
#endif

#ifdef ETL_CUFFT_MODE
struct is_cufft_enabled : std::true_type {};
#else
struct is_cufft_enabled : std::false_type {};
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false;
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false;
#endif

//Flag to enable unrolling of vectorized loops
#ifdef ETL_UNROLL_VECT
constexpr const bool unroll_vectorized_loops = true;
#else
constexpr const bool unroll_vectorized_loops     = false;
#endif

//Flag to enable unrolling of non-vectorized loops
#ifdef ETL_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = true;
#else
constexpr const bool unroll_normal_loops         = false;
#endif

enum class vector_mode_t {
    NONE,
    SSE3,
    AVX
};

#ifdef __AVX__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode        = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE;
#endif

} //end of namespace etl
<commit_msg>Disable parallel if only one thread is enabled<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include <thread>

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false;
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false;
#endif

//Flag to disable the creation of temporary in expressions
#ifdef ETL_NO_TEMPORARY
constexpr const bool create_temporary = false;
#else
constexpr const bool create_temporary = true;
#endif

#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads = std::thread::hardware_concurrency();
#endif

#ifdef ETL_PARALLEL
const bool parallel = threads > 1;
#else
constexpr const bool parallel = false;
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

struct is_mkl_enabled : std::true_type {};
struct has_fast_fft : std::true_type {};

#else

struct is_mkl_enabled : std::false_type {};
struct has_fast_fft : std::false_type {};

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
struct is_cblas_enabled : std::true_type {};
#else
struct is_cblas_enabled : std::false_type {};
#endif

#ifdef ETL_CUBLAS_MODE
struct is_cublas_enabled : std::true_type {};
#else
struct is_cublas_enabled : std::false_type {};
#endif

#ifdef ETL_CUFFT_MODE
struct is_cufft_enabled : std::true_type {};
#else
struct is_cufft_enabled : std::false_type {};
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false;
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false;
#endif

//Flag to enable unrolling of vectorized loops
#ifdef ETL_UNROLL_VECT
constexpr const bool unroll_vectorized_loops = true;
#else
constexpr const bool unroll_vectorized_loops     = false;
#endif

//Flag to enable unrolling of non-vectorized loops
#ifdef ETL_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = true;
#else
constexpr const bool unroll_normal_loops         = false;
#endif

enum class vector_mode_t {
    NONE,
    SSE3,
    AVX
};

#ifdef __AVX__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode        = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE;
#endif

} //end of namespace etl
<|endoftext|>


<commit_before>/* Rescorer.C
*
* Copyright (C) 2011 Marcel Schumann
*
* This program free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/

// ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------

#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/DOCKING/COMMON/dockingAlgorithm.h>
#include <BALL/DOCKING/COMMON/structurePreparer.h>
#include <BALL/SCORING/FUNCTIONS/gridedMM.h>
#include <BALL/SCORING/FUNCTIONS/MMScoring.h>
#include <BALL/SCORING/FUNCTIONS/PBScoring.h>
#include <BALL/SCORING/FUNCTIONS/gridedPLP.h>
#include <BALL/SCORING/FUNCTIONS/PLPScoring.h>
#include <BALL/SCORING/FUNCTIONS/rescoring3D.h>
#include <BALL/SCORING/FUNCTIONS/rescoring4D.h>
#include <BALL/SCORING/FUNCTIONS/rescoring1D.h>
#include <BALL/SCORING/COMMON/rescorer.h>
#include "version.h"

using namespace BALL;

int main(int argc, char* argv[])
{
	CommandlineParser par("SimpleRescorer", "rescore docking results", VERSION, String(__DATE__), "Rescoring");
	par.registerParameter("rec", "receptor pdb-file", INFILE, true);
	par.registerParameter("rl", "reference-ligand", INFILE, true);
	par.registerParameter(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME, "configuration file", INFILE);
	par.registerParameter("i", "compounds to be rescored", INFILE, true);
	par.registerParameter("o", "rescored compounds", OUTFILE, true);
	par.registerParameter("write_ini", "write ini-file w/ default parameters (and don't do anything else)", OUTFILE);
	par.registerParameter("function", "scoring function: 'MM', 'PLP' or 'PB'", STRING);
	par.registerFlag("rm", "remove input file when finished");

	String man = "This tool rescores docking output poses.\nA scoring function is used to evaluate the binding-free-energy of each compound. This is similar to the scoring done during docking; details depend on the config-file (if one is specified).\n\nAs input we need:\n\
    * a file containing a protonated protein in pdb-format\n\
    * a file containing a reference ligand. This reference ligand should be located in the binding pocket. Supported formats are mol2, sdf or drf (DockResultFile, xml-based).\n\
    * a file containing the compounds that are to be rescored. Supported formats are mol2, sdf or drf (DockResultFile, xml-based). Those compound should have been docked into the specified protein.\n\nOutput of this tool is a file in the same format as the input ligand file containing all compounds with scores obtained by rescoring in form of a property 're-score'.";
	par.setToolManual(man);
	list<String> slist;
	slist.push_back("MM");
	slist.push_back("PLP");
	slist.push_back("PB");
	par.setParameterRestrictions("function",slist);
	par.setSupportedFormats("rec","pdb");
	par.setSupportedFormats("rl",MolFileFactory::getSupportedFormats());
	par.setSupportedFormats(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME,"ini");
	par.setSupportedFormats("i",MolFileFactory::getSupportedFormats());
	par.setSupportedFormats("o","mol2,sdf,drf");
	par.setSupportedFormats("write_ini","ini");
	par.setOutputFormatSource("o","i");
	Options default_options;
	ScoringFunction::getDefaultOptions(default_options);
	par.registerAdvancedParameters(default_options);
	par.setSupportedFormats("filename","ini");
	par.parse(argc, argv);

	int status = Rescorer::runRescoring(par, true, false);

	if (status == 0 && par.has("rm"))
	{
		File::remove(par.get("i"));
	}
	return status;

}
<commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/DOCKING/COMMON/dockingAlgorithm.h>
#include <BALL/DOCKING/COMMON/structurePreparer.h>
#include <BALL/SCORING/FUNCTIONS/gridedMM.h>
#include <BALL/SCORING/FUNCTIONS/MMScoring.h>
#include <BALL/SCORING/FUNCTIONS/PBScoring.h>
#include <BALL/SCORING/FUNCTIONS/gridedPLP.h>
#include <BALL/SCORING/FUNCTIONS/PLPScoring.h>
#include <BALL/SCORING/FUNCTIONS/rescoring3D.h>
#include <BALL/SCORING/FUNCTIONS/rescoring4D.h>
#include <BALL/SCORING/FUNCTIONS/rescoring1D.h>
#include <BALL/SCORING/COMMON/rescorer.h>
#include "version.h"

using namespace BALL;

int main(int argc, char* argv[])
{
	CommandlineParser par("SimpleRescorer", "rescore docking results", VERSION, String(__DATE__), "Rescoring");
	par.registerParameter("rec", "receptor pdb-file", INFILE, true);
	par.registerParameter("rl", "reference-ligand", INFILE, true);
	par.registerParameter(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME, "configuration file", INFILE);
	par.registerParameter("i", "compounds to be rescored", INFILE, true);
	par.registerParameter("o", "rescored compounds", OUTFILE, true);
	par.registerParameter("write_ini", "write ini-file w/ default parameters (and don't do anything else)", OUTFILE);
	par.registerParameter("function", "scoring function: 'MM', 'PLP' or 'PB'", STRING);
	par.registerFlag("rm", "remove input file when finished");

	String man = "This tool rescores docking output poses.\nA scoring function is used to evaluate the binding-free-energy of each compound. This is similar to the scoring done during docking; details depend on the config-file (if one is specified).\n\nAs input we need:\n\
    * a file containing a protonated protein in pdb-format\n\
    * a file containing a reference ligand. This reference ligand should be located in the binding pocket. Supported formats are mol2, sdf or drf (DockResultFile, xml-based).\n\
    * a file containing the compounds that are to be rescored. Supported formats are mol2, sdf or drf (DockResultFile, xml-based). Those compound should have been docked into the specified protein.\n\nOutput of this tool is a file in the same format as the input ligand file containing all compounds with scores obtained by rescoring in form of a property 're-score'.";
	par.setToolManual(man);
	list<String> slist;
	slist.push_back("MM");
	slist.push_back("PLP");
	slist.push_back("PB");
	par.setParameterRestrictions("function",slist);
	par.setSupportedFormats("rec","pdb");
	par.setSupportedFormats("rl",MolFileFactory::getSupportedFormats());
	par.setSupportedFormats(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME,"ini");
	par.setSupportedFormats("i",MolFileFactory::getSupportedFormats());
	par.setSupportedFormats("o","mol2,sdf,drf");
	par.setSupportedFormats("write_ini","ini");
	par.setOutputFormatSource("o","i");
	Options default_options;
	ScoringFunction::getDefaultOptions(default_options);
	par.registerAdvancedParameters(default_options);
	par.setSupportedFormats("filename","ini");
	par.parse(argc, argv);

	int status = Rescorer::runRescoring(par, true, false);

	if (status == 0 && par.has("rm"))
	{
		File::remove(par.get("i"));
	}
	return status;

}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////
//							   //
//	Class to analyze ZDC data			   //
//							   //
/////////////////////////////////////////////////////////////

#include <TList.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TFile.h>
#include <TString.h>

#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDInputHandler.h"
#include "AliESDZDC.h"
#include "AliMultiplicity.h"
#include "AliAODHandler.h"
#include "AliAODEvent.h"
#include "AliAODVertex.h"
#include "AliAODMCHeader.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliAODMCParticle.h"
#include "AliAnalysisTaskSE.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliPhysicsSelectionTask.h"
#include "AliPhysicsSelection.h"
#include "AliBackgroundSelection.h"
#include "AliTriggerAnalysis.h"
#include "AliCentrality.h"
#include "AliAnalysisTaskZDCpp.h"

ClassImp(AliAnalysisTaskZDCpp)

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp():
  AliAnalysisTaskSE(),
    fDebug(0),
    fIsMCInput(kFALSE),
    fOutput(0x0),
    fhTDCZNSum(0x0),
    fhTDCZNDiff(0x0),
    fhZNCSpectrum(0x0),
    fhZNASpectrum(0x0),
    fhZPCSpectrum(0x0),
    fhZPASpectrum(0x0),
    fhZEM1Spectrum(0x0),
    fhZEM2Spectrum(0x0),
    fhZNCpmc(0x0),
    fhZNApmc(0x0),
    fhZPCpmc(0x0),
    fhZPApmc(0x0),
    fhZNCCentroid(0x0),
    fhZNACentroid(0x0),
    fDebunch(0x0),
    fhTDCZNC(0x0),
    fhTDCZNA(0x0)
{
   // Default constructor
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const char *name):
  AliAnalysisTaskSE(name),
    fDebug(0),
    fIsMCInput(kFALSE),
    fOutput(0x0),
    fhTDCZNSum(0x0),
    fhTDCZNDiff(0x0),
    fhZNCSpectrum(0x0),
    fhZNASpectrum(0x0),
    fhZPCSpectrum(0x0),
    fhZPASpectrum(0x0),
    fhZEM1Spectrum(0x0),
    fhZEM2Spectrum(0x0),
    fhZNCpmc(0x0),
    fhZNApmc(0x0),
    fhZPCpmc(0x0),
    fhZPApmc(0x0),
    fhZNCCentroid(0x0),
    fhZNACentroid(0x0),
    fDebunch(0x0) ,
    fhTDCZNC(0x0),
    fhTDCZNA(0x0)
{
  // Output slot #1 writes into a TList container
  DefineOutput(1, TList::Class());

}

//________________________________________________________________________
AliAnalysisTaskZDCpp& AliAnalysisTaskZDCpp::operator=(const AliAnalysisTaskZDCpp& c)
{
  //
  // Assignment operator
  //
  if (this!=&c) {
    AliAnalysisTaskSE::operator=(c);
  }
  return *this;
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const AliAnalysisTaskZDCpp& ana):
  AliAnalysisTaskSE(ana),
  fDebug(ana.fDebug),
  fIsMCInput(ana.fIsMCInput),
  fOutput(ana.fOutput),
  fhTDCZNSum(ana.fhTDCZNSum),
  fhTDCZNDiff(ana.fhTDCZNDiff),
  fhZNCSpectrum(ana.fhZNCSpectrum),
  fhZNASpectrum(ana.fhZNASpectrum),
  fhZPCSpectrum(ana.fhZPCSpectrum),
  fhZPASpectrum(ana.fhZPASpectrum),
  fhZEM1Spectrum(ana.fhZEM1Spectrum),
  fhZEM2Spectrum(ana.fhZEM2Spectrum),
  fhZNCpmc(ana.fhZNCpmc),
  fhZNApmc(ana.fhZNApmc),
  fhZPCpmc(ana.fhZPCpmc),
  fhZPApmc(ana.fhZPApmc),
  fhZNCCentroid(ana.fhZNCCentroid),
  fhZNACentroid(ana.fhZNACentroid),
  fDebunch(ana.fDebunch),
  fhTDCZNC(ana.fhTDCZNC),
  fhTDCZNA(ana.fhTDCZNA)
{
  //
  // Copy Constructor
  //
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::~AliAnalysisTaskZDCpp()
{
  // Destructor
  if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){
    delete fOutput; fOutput=0;
  }

}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::UserCreateOutputObjects()
{
  // Create the output containers

  fOutput = new TList;
  fOutput->SetOwner();
  //fOutput->SetName("output");

  fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,30.);
  fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNSum);

  fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.);
  fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNDiff);

  fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 2000.);
  fOutput->Add(fhZNCSpectrum);
  fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 2000.) ;
  fOutput->Add(fhZNASpectrum);
  fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 140,0., 1400.) ;
  fOutput->Add(fhZPCSpectrum);
  fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 140,0., 1400.) ;
  fOutput->Add(fhZPASpectrum);
  fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 200,0., 2500.);
  fOutput->Add(fhZEM1Spectrum);
  fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 200,0., 2500.);
  fOutput->Add(fhZEM2Spectrum);

  fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 2000.);
  fOutput->Add(fhZNCpmc);
  fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 2000.);
  fOutput->Add(fhZNApmc);
  fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",140, 0., 1400.);
  fOutput->Add(fhZPCpmc);
  fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",140, 0., 1400.);
  fOutput->Add(fhZPApmc);

  fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5);
  fOutput->Add(fhZNCCentroid);
  fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5);
  fOutput->Add(fhZNACentroid);

  fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,30);
  fOutput->Add(fDebunch);

  fhTDCZNC = new TH1F("fhTDCZNC","TDC_{ZNC}",60,-30.,30.);
  fhTDCZNC->GetXaxis()->SetTitle("TDC_{ZNC} (ns)");
  fOutput->Add(fhTDCZNC);

  fhTDCZNA = new TH1F("fhTDCZNA","TDC_{ZNA}",60,-30.,30.);
  fhTDCZNA->GetXaxis()->SetTitle("TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNA);

  PostData(1, fOutput);
}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::UserExec(Option_t */*option*/)
{
  // Execute analysis for current event:
  if(fDebug>1) printf(" **** AliAnalysisTaskZDCpp::UserExec() \n");

  if (!InputEvent()) {
    Printf("ERROR: InputEvent not available");
    return;
  }

  AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent());
  if(!esd) return;
  // Select PHYSICS events (type=7, for data)
  //if(!fIsMCInput && esd->GetEventType()!=7) return;

  // ********* MC INFO *********************************
  if(fIsMCInput){

    AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
    if (!eventHandler) {
      Printf("ERROR: Could not retrieve MC event handler");
      return;
    }

    AliMCEvent* mcEvent = eventHandler->MCEvent();
    if (!mcEvent) {
      Printf("ERROR: Could not retrieve MC event");
      return;
   }

  }
  // ****************************************************

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();

  AliESDZDC *esdZDC = esd->GetESDZDC();

  if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){

    fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy());
    fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy());
    fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy());
    fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy());
    fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.);
    fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.);

    const Double_t * towZNC = esdZDC->GetZN1TowerEnergy();
    const Double_t * towZPC = esdZDC->GetZP1TowerEnergy();
    const Double_t * towZNA = esdZDC->GetZN2TowerEnergy();
    const Double_t * towZPA = esdZDC->GetZP2TowerEnergy();
    //
    fhZNCpmc->Fill(towZNC[0]);
    fhZNApmc->Fill(towZNA[0]);
    fhZPCpmc->Fill(towZPC[0]);
    fhZPApmc->Fill(towZPA[0]);

    Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.};
    esdZDC->GetZNCentroidInpp(xyZNC, xyZNA);

    fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]);
    fhZNACentroid->Fill(xyZNA[0], xyZNA[1]);

    const Double_t * towZNCLG = esdZDC->GetZN1TowerEnergyLR();
    const Double_t * towZNALG = esdZDC->GetZN2TowerEnergyLR();
    Double_t znclg=0., znalg=0.;
    for(Int_t iq=0; iq<5; iq++){
       znclg += towZNCLG[iq];
       znalg += towZNALG[iq];
    }
  }

  Float_t tdcC=999., tdcA=999;
  Float_t tdcSum=999., tdcDiff=999;
  for(int i=0; i<4; i++){
    if(esdZDC->GetZDCTDCData(esdZDC->GetZNCTDCChannel() ,i) != 0.){
      tdcC = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i);
      fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i));
      if(esdZDC->GetZDCTDCData(esdZDC->GetZNATDCChannel(),i) != 0.){
        tdcA = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i);
        fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i));
        tdcSum = tdcC+tdcA;
        tdcDiff = tdcC-tdcA;
      }
    }
    if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum);
    if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff);
    if(tdcSum!=999. && tdcDiff!=999.)  fDebunch->Fill(tdcDiff, tdcSum);
  }

  PostData(1, fOutput);

}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::Terminate(Option_t */*option*/)
{
  // Terminate analysis
  //
}
<commit_msg>Removing unused variables<commit_after>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////
//							   //
//	Class to analyze ZDC data			   //
//							   //
/////////////////////////////////////////////////////////////

#include <TList.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TFile.h>
#include <TString.h>

#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDInputHandler.h"
#include "AliESDZDC.h"
#include "AliMultiplicity.h"
#include "AliAODHandler.h"
#include "AliAODEvent.h"
#include "AliAODVertex.h"
#include "AliAODMCHeader.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliAODMCParticle.h"
#include "AliAnalysisTaskSE.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliPhysicsSelectionTask.h"
#include "AliPhysicsSelection.h"
#include "AliBackgroundSelection.h"
#include "AliTriggerAnalysis.h"
#include "AliCentrality.h"
#include "AliAnalysisTaskZDCpp.h"

ClassImp(AliAnalysisTaskZDCpp)

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp():
  AliAnalysisTaskSE(),
    fDebug(0),
    fIsMCInput(kFALSE),
    fOutput(0x0),
    fhTDCZNSum(0x0),
    fhTDCZNDiff(0x0),
    fhZNCSpectrum(0x0),
    fhZNASpectrum(0x0),
    fhZPCSpectrum(0x0),
    fhZPASpectrum(0x0),
    fhZEM1Spectrum(0x0),
    fhZEM2Spectrum(0x0),
    fhZNCpmc(0x0),
    fhZNApmc(0x0),
    fhZPCpmc(0x0),
    fhZPApmc(0x0),
    fhZNCCentroid(0x0),
    fhZNACentroid(0x0),
    fDebunch(0x0),
    fhTDCZNC(0x0),
    fhTDCZNA(0x0)
{
   // Default constructor
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const char *name):
  AliAnalysisTaskSE(name),
    fDebug(0),
    fIsMCInput(kFALSE),
    fOutput(0x0),
    fhTDCZNSum(0x0),
    fhTDCZNDiff(0x0),
    fhZNCSpectrum(0x0),
    fhZNASpectrum(0x0),
    fhZPCSpectrum(0x0),
    fhZPASpectrum(0x0),
    fhZEM1Spectrum(0x0),
    fhZEM2Spectrum(0x0),
    fhZNCpmc(0x0),
    fhZNApmc(0x0),
    fhZPCpmc(0x0),
    fhZPApmc(0x0),
    fhZNCCentroid(0x0),
    fhZNACentroid(0x0),
    fDebunch(0x0) ,
    fhTDCZNC(0x0),
    fhTDCZNA(0x0)
{
  // Output slot #1 writes into a TList container
  DefineOutput(1, TList::Class());

}

//________________________________________________________________________
AliAnalysisTaskZDCpp& AliAnalysisTaskZDCpp::operator=(const AliAnalysisTaskZDCpp& c)
{
  //
  // Assignment operator
  //
  if (this!=&c) {
    AliAnalysisTaskSE::operator=(c);
  }
  return *this;
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const AliAnalysisTaskZDCpp& ana):
  AliAnalysisTaskSE(ana),
  fDebug(ana.fDebug),
  fIsMCInput(ana.fIsMCInput),
  fOutput(ana.fOutput),
  fhTDCZNSum(ana.fhTDCZNSum),
  fhTDCZNDiff(ana.fhTDCZNDiff),
  fhZNCSpectrum(ana.fhZNCSpectrum),
  fhZNASpectrum(ana.fhZNASpectrum),
  fhZPCSpectrum(ana.fhZPCSpectrum),
  fhZPASpectrum(ana.fhZPASpectrum),
  fhZEM1Spectrum(ana.fhZEM1Spectrum),
  fhZEM2Spectrum(ana.fhZEM2Spectrum),
  fhZNCpmc(ana.fhZNCpmc),
  fhZNApmc(ana.fhZNApmc),
  fhZPCpmc(ana.fhZPCpmc),
  fhZPApmc(ana.fhZPApmc),
  fhZNCCentroid(ana.fhZNCCentroid),
  fhZNACentroid(ana.fhZNACentroid),
  fDebunch(ana.fDebunch),
  fhTDCZNC(ana.fhTDCZNC),
  fhTDCZNA(ana.fhTDCZNA)
{
  //
  // Copy Constructor
  //
}

//________________________________________________________________________
AliAnalysisTaskZDCpp::~AliAnalysisTaskZDCpp()
{
  // Destructor
  if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){
    delete fOutput; fOutput=0;
  }

}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::UserCreateOutputObjects()
{
  // Create the output containers

  fOutput = new TList;
  fOutput->SetOwner();
  //fOutput->SetName("output");

  fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,30.);
  fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNSum);

  fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.);
  fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNDiff);

  fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 2000.);
  fOutput->Add(fhZNCSpectrum);
  fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 2000.) ;
  fOutput->Add(fhZNASpectrum);
  fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 140,0., 1400.) ;
  fOutput->Add(fhZPCSpectrum);
  fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 140,0., 1400.) ;
  fOutput->Add(fhZPASpectrum);
  fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 200,0., 2500.);
  fOutput->Add(fhZEM1Spectrum);
  fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 200,0., 2500.);
  fOutput->Add(fhZEM2Spectrum);

  fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 2000.);
  fOutput->Add(fhZNCpmc);
  fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 2000.);
  fOutput->Add(fhZNApmc);
  fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",140, 0., 1400.);
  fOutput->Add(fhZPCpmc);
  fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",140, 0., 1400.);
  fOutput->Add(fhZPApmc);

  fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5);
  fOutput->Add(fhZNCCentroid);
  fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5);
  fOutput->Add(fhZNACentroid);

  fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,30);
  fOutput->Add(fDebunch);

  fhTDCZNC = new TH1F("fhTDCZNC","TDC_{ZNC}",60,-30.,30.);
  fhTDCZNC->GetXaxis()->SetTitle("TDC_{ZNC} (ns)");
  fOutput->Add(fhTDCZNC);

  fhTDCZNA = new TH1F("fhTDCZNA","TDC_{ZNA}",60,-30.,30.);
  fhTDCZNA->GetXaxis()->SetTitle("TDC_{ZNA} (ns)");
  fOutput->Add(fhTDCZNA);

  PostData(1, fOutput);
}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::UserExec(Option_t */*option*/)
{
  // Execute analysis for current event:
  if(fDebug>1) printf(" **** AliAnalysisTaskZDCpp::UserExec() \n");

  if (!InputEvent()) {
    Printf("ERROR: InputEvent not available");
    return;
  }

  AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent());
  if(!esd) return;
  // Select PHYSICS events (type=7, for data)
  //if(!fIsMCInput && esd->GetEventType()!=7) return;

  // ********* MC INFO *********************************
  if(fIsMCInput){

    AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
    if (!eventHandler) {
      Printf("ERROR: Could not retrieve MC event handler");
      return;
    }

    AliMCEvent* mcEvent = eventHandler->MCEvent();
    if (!mcEvent) {
      Printf("ERROR: Could not retrieve MC event");
      return;
   }

  }
  // ****************************************************

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();

  AliESDZDC *esdZDC = esd->GetESDZDC();

  if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){

    fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy());
    fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy());
    fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy());
    fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy());
    fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.);
    fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.);

    const Double_t * towZNC = esdZDC->GetZN1TowerEnergy();
    const Double_t * towZPC = esdZDC->GetZP1TowerEnergy();
    const Double_t * towZNA = esdZDC->GetZN2TowerEnergy();
    const Double_t * towZPA = esdZDC->GetZP2TowerEnergy();
    //
    fhZNCpmc->Fill(towZNC[0]);
    fhZNApmc->Fill(towZNA[0]);
    fhZPCpmc->Fill(towZPC[0]);
    fhZPApmc->Fill(towZPA[0]);

    Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.};
    esdZDC->GetZNCentroidInpp(xyZNC, xyZNA);

    fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]);
    fhZNACentroid->Fill(xyZNA[0], xyZNA[1]);

  }

  Float_t tdcC=999., tdcA=999;
  Float_t tdcSum=999., tdcDiff=999;
  for(int i=0; i<4; i++){
    if(esdZDC->GetZDCTDCData(esdZDC->GetZNCTDCChannel() ,i) != 0.){
      tdcC = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i);
      fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i));
      if(esdZDC->GetZDCTDCData(esdZDC->GetZNATDCChannel(),i) != 0.){
        tdcA = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i);
        fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i));
        tdcSum = tdcC+tdcA;
        tdcDiff = tdcC-tdcA;
      }
    }
    if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum);
    if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff);
    if(tdcSum!=999. && tdcDiff!=999.)  fDebunch->Fill(tdcDiff, tdcSum);
  }

  PostData(1, fOutput);

}

//________________________________________________________________________
void AliAnalysisTaskZDCpp::Terminate(Option_t */*option*/)
{
  // Terminate analysis
  //
}
<|endoftext|>