<commit_before>#include "Trie.h"

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <unordered_map>

#include "Postgres.h"
#include "Utils.h"

using namespace std;
using namespace btree;

//
// Trie::~Trie
//
Trie::~Trie() {
  for (btree_map<word,Trie*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
    delete iter->second;
  }
}

//
// Trie::add
//
void Trie::add(const edge* elements, const uint8_t& length,
               const Graph* graph) {
  // Corner cases
  if (length == 0) { return; }  // this case shouldn't actually happen normally...
  // Register child
  const word w = elements[0].source;
  assert (w > 0);
  const btree_map<word,Trie*>::iterator childIter = children.find( w );
  Trie* child = NULL;
  if (childIter == children.end()) {
    child = new Trie();
    children[w] = child;
  } else {
    child = childIter->second;
  }
  // Register skip-gram
  if (length > 1) {
    const word grandChildW = elements[1].source;
    assert (grandChildW > 0);
    skipGrams[grandChildW].push_back(w);
  }
  // Register information about child
  if (graph == NULL || graph->containsDeletion(elements[0])) {
    child->registerEdge(elements[0]);
  }
  // Recursive call
  if (length == 1) {
    child->isLeaf = true;    // Mark this as a leaf node
    completions[w] = child;  // register a completion
  } else {
    child->add(&(elements[1]), length - 1, graph);
  }
}

inline uint8_t min(const uint8_t& a, const uint8_t b) { return a < b ? a : b; }

//
// Trie::addCompletion
//
inline void Trie::addCompletion(const Trie* child, const word& source,
                                edge* insertion, uint32_t& index) const {
  if (index < MAX_COMPLETIONS - 4) {
    // case: write directly to insertion buffer
    uint8_t numEdges = child->getEdges(&(insertion[index]));
    for (int i = 0; i < numEdges; ++i) { insertion[index + i].source = source; }
    index += numEdges;
  } else {
    // case: write to temporary buffer and copy over
    edge buffer[4];
    uint8_t bufferedEdges = child->getEdges(buffer);
    uint8_t numEdges = min( MAX_COMPLETIONS - index, bufferedEdges );
    for (int i = 0; i < numEdges; ++i) { buffer[i].source = source; }
    memcpy(&(insertion[index]), buffer, numEdges * sizeof(edge));
    index += numEdges;
  }
}

//
// Trie::contains
//
const bool Trie::contains(const tagged_word* query,
                          const uint8_t& queryLength,
                          const int16_t& mutationIndex,
                          edge* insertions) const {
  assert (queryLength > mutationIndex);
  uint32_t mutableIndex = 0;
  bool contains;
  if (mutationIndex == -1) {
    if (queryLength > 0) {
      btree_map<word,vector<word>>::const_iterator skipGramIter = skipGrams.find( query[0].word );
      if (skipGramIter != skipGrams.end()) {
        // Case: add anything that leads into the second term
        for (vector<word>::const_iterator iter = skipGramIter->second.begin(); iter != skipGramIter->second.end(); ++iter) {
          btree_map<word,Trie*>::const_iterator childIter = children.find( *iter );
          if (childIter != children.end()) {
            addCompletion(childIter->second, childIter->first, insertions, mutableIndex);
          }
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      } else {
        // Case: we're kind of shit out of luck. We're inserting into the
        //       beginning of the sentence, but with no valid skip-grams.
        //       So, let's just add some starting words and pray.
        for (btree_map<word,Trie*>::const_iterator childIter = children.begin(); childIter != children.end(); ++childIter) {
          addCompletion(childIter->second, childIter->first, insertions, mutableIndex);
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      }
    } else {
      // Case: add any single-term completions
      for (btree_map<word,Trie*>::const_iterator iter = children.begin(); iter != children.end(); ++iter) {
        if (iter->second->isLeaf) {
          addCompletion(iter->second, iter->first, insertions, mutableIndex);
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      }
    }
    contains =  containsImpl(query, queryLength, -9000, insertions, mutableIndex);  // already added completions
  } else {
    contains = containsImpl(query, queryLength, mutationIndex, insertions, mutableIndex);
  }

  // Return
  if (mutableIndex < MAX_COMPLETIONS) {
    insertions[mutableIndex].source = 0;
  }
  return contains;
}

//
// Trie::containsImpl
//
const bool Trie::containsImpl(const tagged_word* query,
                              const uint8_t& queryLength,
                              const int16_t& mutationIndex,
                              edge* insertions,
                              uint32_t& mutableIndex) const {
  assert (queryLength > mutationIndex);

  // -- Part 1: Fill in completions --
  if (mutationIndex == -1) {
    const bool tooManyChildren = (children.size() > MAX_COMPLETIONS);
    if (!tooManyChildren) {
      // sub-case: add all children
      btree_map<word,Trie*>::const_iterator iter;
      for (iter = children.begin(); iter != children.end(); ++iter) {
        addCompletion(iter->second, iter->first, insertions, mutableIndex);
        if (mutableIndex >= MAX_COMPLETIONS) { break; }
      }
    } else {
      // sub-case: too many children; only add completions
      for (btree_map<word,Trie*>::const_iterator iter = completions.begin(); iter != completions.end(); ++iter) {
        addCompletion(iter->second, iter->first, insertions, mutableIndex);
        if (mutableIndex >= MAX_COMPLETIONS) { break; }
      }
    }
  }

  // -- Part 2: Check containment --
  if (queryLength == 0) {
    // return whether the fact exists
    return isLeaf;
  } else {
    // Case: we're in the middle of the query
    btree_map<word,Trie*>::const_iterator childIter = children.find( query[0].word );
    if (childIter == children.end()) {
      // Return false
      return false;
    } else {
      // Check the child
      return childIter->second->containsImpl(&(query[1]),
                                             queryLength - 1,
                                             mutationIndex - 1,
                                             insertions,
                                             mutableIndex);
    }
  }
}

//
// ReadFactTrie
//
FactDB* ReadFactTrie(const uint64_t maxFactsToRead, const Graph* graph) {
  Trie* facts = new Trie();
  char query[127];

  // Read valid deletions
  printf("Reading registered deletions...\n");
  unordered_map<word,vector<edge>> word2senses;
  // (query)
  snprintf(query, 127, "SELECT DISTINCT (source) source, source_sense, type FROM %s WHERE source<>0 AND sink=0 ORDER BY type;", PG_TABLE_EDGE);
  PGIterator wordIter = PGIterator(query);
  uint32_t numValidInsertions = 0;
  while (wordIter.hasNext()) {
    // Get fact
    PGRow row = wordIter.next();
    // Create edge
    edge e;
    e.source       = atoi(row[0]);
    e.source_sense = atoi(row[1]);
    e.type  = atoi(row[2]);
    e.cost  = 1.0f;
    // Register edge
    word2senses[e.source].push_back(e);
    numValidInsertions += 1;
  }
  printf("  Done. %u words have sense tags\n", numValidInsertions);

  // Read facts
  printf("Reading facts...\n");
  // (query)
  if (maxFactsToRead == std::numeric_limits<uint64_t>::max()) {
    snprintf(query, 127,
             "SELECT gloss, weight FROM %s ORDER BY weight DESC;",
             PG_TABLE_FACT);
  } else {
    snprintf(query, 127,
             "SELECT gloss, weight FROM %s ORDER BY weight DESC LIMIT %lu;",
             PG_TABLE_FACT,
             maxFactsToRead);
  }
  PGIterator iter = PGIterator(query);
  uint64_t i = 0;
  edge buffer[256];
  uint8_t bufferLength;
  while (iter.hasNext()) {
    // Get fact
    PGRow row = iter.next();
    const char* gloss = row[0];
    uint32_t weight = atoi(row[1]);
    if (weight < MIN_FACT_COUNT) { break; }
    // Parse fact
    stringstream stream (&gloss[1]);
    bufferLength = 0;
    while( stream.good() ) {
      // Parse the word
      string substr;
      getline( stream, substr, ',' );
      word w = atoi(substr.c_str());
      // Register the word
      unordered_map<word,vector<edge>>::iterator iter = word2senses.find( w );
      if (iter == word2senses.end() || iter->second.size() == 0) {
        buffer[bufferLength].source       = w;
        buffer[bufferLength].source_sense = 0;
        buffer[bufferLength].type         = 0;
        buffer[bufferLength].cost         = 1.0f;
      } else {
        buffer[bufferLength] = iter->second[0];
      }
      buffer[bufferLength].sink       = 0;
      buffer[bufferLength].sink_sense = 0;
      if (bufferLength >= MAX_FACT_LENGTH) { break; }
      bufferLength += 1;
    }
    // Add fact
    // Add 'canonical' version
    facts->add(buffer, bufferLength, graph);
    // Add word sense variants
    for (uint32_t k = 0; k < bufferLength; ++k) {
      unordered_map<word,vector<edge>>::iterator iter = word2senses.find( buffer[k].source );
      if (iter != word2senses.end() && iter->second.size() > 1) {
        for (uint32_t sense = 1; sense < iter->second.size(); ++sense) {
          buffer[k] = iter->second[sense];
          facts->add(buffer, bufferLength, graph);
        }
      }
    }
    // Debug
    i += 1;
    if (i % 10000000 == 0) {
      printf("  loaded %luM facts\n", i / 1000000);
    }
  }

  // Return
  printf("  done reading the fact database (%lu facts read)\n", i);
  return facts;
}
<commit_msg>Debug reading the factdb more<commit_after>#include "Trie.h"

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <unordered_map>

#include "Postgres.h"
#include "Utils.h"

using namespace std;
using namespace btree;

//
// Trie::~Trie
//
Trie::~Trie() {
  for (btree_map<word,Trie*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
    delete iter->second;
  }
}

//
// Trie::add
//
void Trie::add(const edge* elements, const uint8_t& length,
               const Graph* graph) {
  // Corner cases
  if (length == 0) { return; }  // this case shouldn't actually happen normally...
  // Register child
  const word w = elements[0].source;
  assert (w > 0);
  const btree_map<word,Trie*>::iterator childIter = children.find( w );
  Trie* child = NULL;
  if (childIter == children.end()) {
    child = new Trie();
    children[w] = child;
  } else {
    child = childIter->second;
  }
  // Register skip-gram
  if (length > 1) {
    const word grandChildW = elements[1].source;
    assert (grandChildW > 0);
    skipGrams[grandChildW].push_back(w);
  }
  // Register information about child
  if (graph == NULL || graph->containsDeletion(elements[0])) {
    child->registerEdge(elements[0]);
  }
  // Recursive call
  if (length == 1) {
    child->isLeaf = true;    // Mark this as a leaf node
    completions[w] = child;  // register a completion
  } else {
    child->add(&(elements[1]), length - 1, graph);
  }
}

inline uint8_t min(const uint8_t& a, const uint8_t b) { return a < b ? a : b; }

//
// Trie::addCompletion
//
inline void Trie::addCompletion(const Trie* child, const word& source,
                                edge* insertion, uint32_t& index) const {
  if (index < MAX_COMPLETIONS - 4) {
    // case: write directly to insertion buffer
    uint8_t numEdges = child->getEdges(&(insertion[index]));
    for (int i = 0; i < numEdges; ++i) { insertion[index + i].source = source; }
    index += numEdges;
  } else {
    // case: write to temporary buffer and copy over
    edge buffer[4];
    uint8_t bufferedEdges = child->getEdges(buffer);
    uint8_t numEdges = min( MAX_COMPLETIONS - index, bufferedEdges );
    for (int i = 0; i < numEdges; ++i) { buffer[i].source = source; }
    memcpy(&(insertion[index]), buffer, numEdges * sizeof(edge));
    index += numEdges;
  }
}

//
// Trie::contains
//
const bool Trie::contains(const tagged_word* query,
                          const uint8_t& queryLength,
                          const int16_t& mutationIndex,
                          edge* insertions) const {
  assert (queryLength > mutationIndex);
  uint32_t mutableIndex = 0;
  bool contains;
  if (mutationIndex == -1) {
    if (queryLength > 0) {
      btree_map<word,vector<word>>::const_iterator skipGramIter = skipGrams.find( query[0].word );
      if (skipGramIter != skipGrams.end()) {
        // Case: add anything that leads into the second term
        for (vector<word>::const_iterator iter = skipGramIter->second.begin(); iter != skipGramIter->second.end(); ++iter) {
          btree_map<word,Trie*>::const_iterator childIter = children.find( *iter );
          if (childIter != children.end()) {
            addCompletion(childIter->second, childIter->first, insertions, mutableIndex);
          }
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      } else {
        // Case: we're kind of shit out of luck. We're inserting into the
        //       beginning of the sentence, but with no valid skip-grams.
        //       So, let's just add some starting words and pray.
        for (btree_map<word,Trie*>::const_iterator childIter = children.begin(); childIter != children.end(); ++childIter) {
          addCompletion(childIter->second, childIter->first, insertions, mutableIndex);
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      }
    } else {
      // Case: add any single-term completions
      for (btree_map<word,Trie*>::const_iterator iter = children.begin(); iter != children.end(); ++iter) {
        if (iter->second->isLeaf) {
          addCompletion(iter->second, iter->first, insertions, mutableIndex);
          if (mutableIndex >= MAX_COMPLETIONS) { break; }
        }
      }
    }
    contains =  containsImpl(query, queryLength, -9000, insertions, mutableIndex);  // already added completions
  } else {
    contains = containsImpl(query, queryLength, mutationIndex, insertions, mutableIndex);
  }

  // Return
  if (mutableIndex < MAX_COMPLETIONS) {
    insertions[mutableIndex].source = 0;
  }
  return contains;
}

//
// Trie::containsImpl
//
const bool Trie::containsImpl(const tagged_word* query,
                              const uint8_t& queryLength,
                              const int16_t& mutationIndex,
                              edge* insertions,
                              uint32_t& mutableIndex) const {
  assert (queryLength > mutationIndex);

  // -- Part 1: Fill in completions --
  if (mutationIndex == -1) {
    const bool tooManyChildren = (children.size() > MAX_COMPLETIONS);
    if (!tooManyChildren) {
      // sub-case: add all children
      btree_map<word,Trie*>::const_iterator iter;
      for (iter = children.begin(); iter != children.end(); ++iter) {
        addCompletion(iter->second, iter->first, insertions, mutableIndex);
        if (mutableIndex >= MAX_COMPLETIONS) { break; }
      }
    } else {
      // sub-case: too many children; only add completions
      for (btree_map<word,Trie*>::const_iterator iter = completions.begin(); iter != completions.end(); ++iter) {
        addCompletion(iter->second, iter->first, insertions, mutableIndex);
        if (mutableIndex >= MAX_COMPLETIONS) { break; }
      }
    }
  }

  // -- Part 2: Check containment --
  if (queryLength == 0) {
    // return whether the fact exists
    return isLeaf;
  } else {
    // Case: we're in the middle of the query
    btree_map<word,Trie*>::const_iterator childIter = children.find( query[0].word );
    if (childIter == children.end()) {
      // Return false
      return false;
    } else {
      // Check the child
      return childIter->second->containsImpl(&(query[1]),
                                             queryLength - 1,
                                             mutationIndex - 1,
                                             insertions,
                                             mutableIndex);
    }
  }
}

//
// ReadFactTrie
//
FactDB* ReadFactTrie(const uint64_t maxFactsToRead, const Graph* graph) {
  Trie* facts = new Trie();
  char query[127];

  // Read valid deletions
  printf("Reading registered deletions...\n");
  unordered_map<word,vector<edge>> word2senses;
  // (query)
  snprintf(query, 127, "SELECT DISTINCT (source) source, source_sense, type FROM %s WHERE source<>0 AND sink=0 ORDER BY type;", PG_TABLE_EDGE);
  PGIterator wordIter = PGIterator(query);
  uint32_t numValidInsertions = 0;
  while (wordIter.hasNext()) {
    // Get fact
    PGRow row = wordIter.next();
    // Create edge
    edge e;
    e.source       = atoi(row[0]);
    e.source_sense = atoi(row[1]);
    e.type  = atoi(row[2]);
    e.cost  = 1.0f;
    // Register edge
    word2senses[e.source].push_back(e);
    numValidInsertions += 1;
  }
  printf("  Done. %u words have sense tags\n", numValidInsertions);

  // Read facts
  printf("Reading facts...\n");
  // (query)
  if (maxFactsToRead == std::numeric_limits<uint64_t>::max()) {
    snprintf(query, 127,
             "SELECT gloss, weight FROM %s ORDER BY weight DESC;",
             PG_TABLE_FACT);
  } else {
    snprintf(query, 127,
             "SELECT gloss, weight FROM %s ORDER BY weight DESC LIMIT %lu;",
             PG_TABLE_FACT,
             maxFactsToRead);
  }
  PGIterator iter = PGIterator(query);
  uint64_t i = 0;
  edge buffer[256];
  uint8_t bufferLength;
  while (iter.hasNext()) {
    // Get fact
    PGRow row = iter.next();
    const char* gloss = row[0];
    uint32_t weight = atoi(row[1]);
    if (weight < MIN_FACT_COUNT) { break; }
    // Parse fact
    stringstream stream (&gloss[1]);
    bufferLength = 0;
    while( stream.good() ) {
      // Parse the word
      string substr;
      getline( stream, substr, ',' );
      word w = atoi(substr.c_str());
      // Register the word
      unordered_map<word,vector<edge>>::iterator iter = word2senses.find( w );
      if (iter == word2senses.end() || iter->second.size() == 0) {
        buffer[bufferLength].source       = w;
        buffer[bufferLength].source_sense = 0;
        buffer[bufferLength].type         = 0;
        buffer[bufferLength].cost         = 1.0f;
      } else {
        buffer[bufferLength] = iter->second[0];
      }
      buffer[bufferLength].sink       = 0;
      buffer[bufferLength].sink_sense = 0;
      if (bufferLength >= MAX_FACT_LENGTH) { break; }
      bufferLength += 1;
    }
    // Add fact
    // Add 'canonical' version
    facts->add(buffer, bufferLength, graph);
    // Add word sense variants
    for (uint32_t k = 0; k < bufferLength; ++k) {
      unordered_map<word,vector<edge>>::iterator iter = word2senses.find( buffer[k].source );
      if (iter != word2senses.end() && iter->second.size() > 1) {
        for (uint32_t sense = 1; sense < iter->second.size(); ++sense) {
          buffer[k] = iter->second[sense];
          facts->add(buffer, bufferLength, graph);
        }
      }
    }
    // Debug
    i += 1;
    if (i % 1000 == 0) {
      printf("  loaded %lu facts\n", i);
    }
  }

  // Return
  printf("  done reading the fact database (%lu facts read)\n", i);
  return facts;
}
<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{

	}
}

	return 0;
}

<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
		}

	}
}

	return 0;
}

<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
		}
	}
	return 0;
}

<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
			pAction->SetupSkillBulletPosition(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('9'))
	{

	}
	return 0;
}

<|endoftext|>


<commit_before>#include "ReposLog.hpp"

#include "LogCache.hpp"
#include "src/svnqt/info_entry.hpp"
#include "src/svnqt/svnqttypes.hpp"
#include "src/svnqt/client.hpp"
#include "src/svnqt/context_listener.hpp"
#include "src/svnqt/cache/DatabaseException.hpp"

#include <qsqldatabase.h>
#include <qsqlcursor.h>

/*!
    \fn svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&)
 */
svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&aRepository)
    :m_Client(aClient),m_Database(0),m_ReposRoot(aRepository),m_latestHead(svn::Revision::UNDEFINED)
{
    if (!aRepository.isEmpty()) {
        m_Database = LogCache::self()->reposDb(aRepository);
    }
}

/*!
    \fn svn::cache::ReposLog::latestHeadRev()
 */
svn::Revision svn::cache::ReposLog::latestHeadRev()
{
    if (!m_Client||m_ReposRoot.isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return svn::Revision::UNDEFINED;
        }
    }
    /// no catch - exception has go trough...
    svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;
    if (e.count()<1||e[0].reposRoot().isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    return e[0].revision();
}

/*!
    \fn svn::cache::ReposLog::latestCachedRev()
 */
svn::Revision svn::cache::ReposLog::latestCachedRev()
{
    if (m_ReposRoot.isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return svn::Revision::UNDEFINED;
        }
    }
    QString q("select revision from 'logentries' order by revision DESC limit 1");
    QSqlQuery _q(QString::null, m_Database);
    if (!_q.exec(q)) {
        qDebug(_q.lastError().text());
        return svn::Revision::UNDEFINED;
    }
    int _r;
    if (_q.isActive() && _q.next()) {

        qDebug("Sel result: "+_q.value(0).toString());
        _r = _q.value(0).toInt();
    } else {
        qDebug(_q.lastError().text());
        return svn::Revision::UNDEFINED;
    }
    return _r;
}

bool svn::cache::ReposLog::checkFill(svn::Revision&start,svn::Revision&end)
{
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return false;
        }
    }
    ContextP cp = m_Client->getContext();
    long long icount=0;

    svn::Revision _latest=latestCachedRev();
    qDebug("Latest cached rev: %i",_latest.revnum());

    start=date2numberRev(start);
    end=date2numberRev(end);

    // both should now one of START, HEAD or NUMBER
    if (start==svn::Revision::HEAD || (end==svn::Revision::NUMBER && start==svn::Revision::NUMBER && start.revnum()>end.revnum())) {
        svn::Revision tmp = start;
        start = end;
        end = tmp;
    }
    qDebug("End: "+end.toString());
    svn::Revision _rstart=_latest.revnum()+1;
    svn::Revision _rend = end;
    if (_rend==svn::Revision::UNDEFINED) {
        _rend=svn::Revision::HEAD;
    }
    // no catch - exception should go outside.
    if (_rstart==0){
        _rstart = 1;
    }
    qDebug("Getting log %s -> %s",_rstart.toString().latin1(),_rend.toString().latin1());
    if (_rend==svn::Revision::HEAD) {
        _rend=latestHeadRev();
    }
    QSqlCursor cur("changeditems",true,m_Database);
    QSqlCursor bcur("logentries",true,m_Database);

    if (_rend==svn::Revision::HEAD||_rend.revnum()>_latest.revnum()) {
        LogEntriesMap _internal;
        qDebug("Retrieving from network.");
        if (!m_Client->log(m_ReposRoot,_rstart,_rend,_internal,svn::Revision::UNDEFINED,true,false)) {
            return false;
        }
        LogEntriesMap::ConstIterator it=_internal.begin();

        for (;it!=_internal.end();++it) {
            insertLogEntry((*it),bcur,cur);
            if (cp && cp->getListener()) {
                //cp->getListener()->contextProgress(++icount,_internal.size());
                if (cp->getListener()->contextCancel()) {
                    throw svn::ClientException(QString("Could not retrieve values: User cancel."));
                }
            }
        }
    }
    return true;
}

bool svn::cache::ReposLog::fillCache(const svn::Revision&_end)
{
    svn::Revision end = _end;
    svn::Revision start = latestCachedRev().revnum()+1;
    return checkFill(start,end);
}

/*!
    \fn svn::cache::ReposLog::simpleLog(const svn::Revision&start,const svn::Revision&end,LogEntriesMap&target)
 */
bool svn::cache::ReposLog::simpleLog(LogEntriesMap&target,const svn::Revision&_start,const svn::Revision&_end)
{
    if (!m_Client||m_ReposRoot.isEmpty()) {
        return false;
    }
    target.clear();
    ContextP cp = m_Client->getContext();

    svn::Revision end = _end;
    svn::Revision start = _start;
    if (!checkFill(start,end)) {
        return false;
    }

    QSqlCursor cur("changeditems",true,m_Database);
    QSqlCursor bcur("logentries",true,m_Database);

    qDebug("End: "+end.toString());
    if (end==svn::Revision::HEAD) {
        end = latestCachedRev();
    }
    if (start==svn::Revision::HEAD) {
        start=latestCachedRev();
    }

    QString lim = QString("revision<=%1 and revision>=%2").arg(end.revnum()).arg(start.revnum());
    qDebug(lim);
    if (!bcur.select(lim)) {
        qDebug(bcur.lastError().text());
        throw svn::ClientException(QString("Could not retrieve values: ")+bcur.lastError().text());
        return false;
    }
    while(bcur.next()) {
        Q_LLONG revision= bcur.value("revision").toLongLong();
        lim=QString("revision=%1").arg(revision);
        if (!cur.select(lim)) {
            qDebug(cur.lastError().text());
            throw svn::ClientException(QString("Could not retrieve values: ")+cur.lastError().text());
            return false;
        }
        target[revision].revision=revision;
        target[revision].author=bcur.value("author").toString();
        target[revision].date=bcur.value("date").toLongLong();
        target[revision].message=bcur.value("message").toString();
        while(cur.next()) {
            char c = cur.value("action").toInt();
            LogChangePathEntry lcp;
            lcp.action=cur.value("action").toString()[0];
            lcp.copyFromPath=cur.value("copyfrom").toString().latin1();
            lcp.path= cur.value("changeditem").toString();
            lcp.copyFromRevision=cur.value("copyfromrev").toLongLong();
            target[revision].changedPaths.push_back(lcp);
        }
        if (cp && cp->getListener()) {
            //cp->getListener()->contextProgress(++icount,bcur.size());
            if (cp->getListener()->contextCancel()) {
                throw svn::ClientException(QString("Could not retrieve values: User cancel."));
            }
        }
    }
    return false;
}

/*!
    \fn svn::cache::ReposLog::date2numberRev(const svn::Revision&)
 */
svn::Revision svn::cache::ReposLog::date2numberRev(const svn::Revision&aRev)
{
    if (aRev!=svn::Revision::DATE) {
        return aRev;
    }
    if (!m_Database) {
        return svn::Revision::UNDEFINED;
    }
    QSqlCursor bcur("logentries",true,m_Database);
    QSqlIndex order = bcur.index("revision");
    order.setDescending(0,true);
    /// @todo as I understood - the resulting revision should always the last one BEFORE this date...
    //QString q=QString("date>='%1'").arg(value);
    //qDebug(q);
    bcur.select(order);
    if (bcur.lastError().type()!=QSqlError::None) {
        qDebug(bcur.lastError().text());
    }
    bool must_remote=true;
    if (bcur.next()) {
        if (bcur.value("date").toLongLong()>=aRev.date()) {
            must_remote=false;
        }
    }
    if (must_remote) {
        svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,aRev,aRev));;
        if (e.count()<1||e[0].reposRoot().isEmpty()) {
            return aRev;
        }
        return e[0].revision();
    }
    QString q=QString("date<'%1'").arg(aRev.date());
    bcur.select(q,order);
    qDebug("Search for date: " +q);
    if (bcur.lastError().type()!=QSqlError::None) {
        qDebug(bcur.lastError().text());
    }
    if (bcur.next()) {
        return bcur.value( "revision" ).toInt();
    }
    // not found...
    svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;
    if (e.count()<1||e[0].reposRoot().isEmpty()) {
        return aRev;
    }
    return e[0].revision();
}

/*!
    \fn svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&)
 */
bool svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&aEntry,QSqlCursor&lCur,QSqlCursor&cCur)
{
    QSqlRecord *buffer;
    m_Database->transaction();

#if QT_VERSION < 0x040000
    Q_LLONG j = aEntry.revision;
#else
    qlonglong j = aEntry.revision;
#endif
    buffer=lCur.primeInsert();
    buffer->setValue("revision",j);
    buffer->setValue("date",aEntry.date);
    buffer->setValue("author",aEntry.author);
    buffer->setValue("message",aEntry.message);
    lCur.insert();
    if (lCur.lastError().type()!=QSqlError::None) {
        m_Database->rollback();
        qDebug(QString("Could not insert values: ")+lCur.lastError().text());
    }
    svn::LogChangePathEntries::ConstIterator cpit = aEntry.changedPaths.begin();
    for (;cpit!=aEntry.changedPaths.end();++cpit){
        buffer = cCur.primeInsert();
        buffer->setValue("revision",j);
        buffer->setValue("changeditem",(*cpit).path);
        buffer->setValue("action",QString(QChar((*cpit).action)));
        buffer->setValue("copyfrom",(*cpit).copyFromPath);
        buffer->setValue("copyfromrev",Q_LLONG((*cpit).copyFromRevision));
        cCur.insert();
        if (cCur.lastError().type()!=QSqlError::None) {
            m_Database->rollback();
            qDebug(QString("Could not insert values: ")+cCur.lastError().text());
            //throw DatabaseException(QString("Could not insert values: ")+cCur.lastError().text());
        }
    }
    m_Database->commit();
    return true;
}
<commit_msg> * catch svn::Exception not svn::ClientException  * don't try retrieve logs for cache if last cached revision is same as head revision<commit_after>#include "ReposLog.hpp"

#include "LogCache.hpp"
#include "src/svnqt/info_entry.hpp"
#include "src/svnqt/svnqttypes.hpp"
#include "src/svnqt/client.hpp"
#include "src/svnqt/context_listener.hpp"
#include "src/svnqt/cache/DatabaseException.hpp"

#include <qsqldatabase.h>
#include <qsqlcursor.h>

/*!
    \fn svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&)
 */
svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&aRepository)
    :m_Client(aClient),m_Database(0),m_ReposRoot(aRepository),m_latestHead(svn::Revision::UNDEFINED)
{
    if (!aRepository.isEmpty()) {
        m_Database = LogCache::self()->reposDb(aRepository);
    }
}

/*!
    \fn svn::cache::ReposLog::latestHeadRev()
 */
svn::Revision svn::cache::ReposLog::latestHeadRev()
{
    if (!m_Client||m_ReposRoot.isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return svn::Revision::UNDEFINED;
        }
    }
    /// no catch - exception has go trough...
    svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;
    if (e.count()<1||e[0].reposRoot().isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    return e[0].revision();
}

/*!
    \fn svn::cache::ReposLog::latestCachedRev()
 */
svn::Revision svn::cache::ReposLog::latestCachedRev()
{
    if (m_ReposRoot.isEmpty()) {
        return svn::Revision::UNDEFINED;
    }
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return svn::Revision::UNDEFINED;
        }
    }
    QString q("select revision from 'logentries' order by revision DESC limit 1");
    QSqlQuery _q(QString::null, m_Database);
    if (!_q.exec(q)) {
        qDebug(_q.lastError().text());
        return svn::Revision::UNDEFINED;
    }
    int _r;
    if (_q.isActive() && _q.next()) {

        qDebug("Sel result: "+_q.value(0).toString());
        _r = _q.value(0).toInt();
    } else {
        qDebug(_q.lastError().text());
        return svn::Revision::UNDEFINED;
    }
    return _r;
}

bool svn::cache::ReposLog::checkFill(svn::Revision&start,svn::Revision&end)
{
    if (!m_Database) {
        m_Database = LogCache::self()->reposDb(m_ReposRoot);
        if (!m_Database) {
            return false;
        }
    }
    ContextP cp = m_Client->getContext();
    long long icount=0;

    svn::Revision _latest=latestCachedRev();
    qDebug("Latest cached rev: %i",_latest.revnum());
    if (_latest.revnum()>=latestHeadRev().revnum()) {
        return true;
    }

    start=date2numberRev(start);
    end=date2numberRev(end);

    // both should now one of START, HEAD or NUMBER
    if (start==svn::Revision::HEAD || (end==svn::Revision::NUMBER && start==svn::Revision::NUMBER && start.revnum()>end.revnum())) {
        svn::Revision tmp = start;
        start = end;
        end = tmp;
    }
    qDebug("End: "+end.toString());
    svn::Revision _rstart=_latest.revnum()+1;
    svn::Revision _rend = end;
    if (_rend==svn::Revision::UNDEFINED) {
        _rend=svn::Revision::HEAD;
    }
    // no catch - exception should go outside.
    if (_rstart==0){
        _rstart = 1;
    }
    qDebug("Getting log %s -> %s",_rstart.toString().latin1(),_rend.toString().latin1());
    if (_rend==svn::Revision::HEAD) {
        _rend=latestHeadRev();
    }
    QSqlCursor cur("changeditems",true,m_Database);
    QSqlCursor bcur("logentries",true,m_Database);

    if (_rend==svn::Revision::HEAD||_rend.revnum()>_latest.revnum()) {
        LogEntriesMap _internal;
        qDebug("Retrieving from network.");
        if (!m_Client->log(m_ReposRoot,_rstart,_rend,_internal,svn::Revision::UNDEFINED,true,false)) {
            return false;
        }
        LogEntriesMap::ConstIterator it=_internal.begin();

        for (;it!=_internal.end();++it) {
            insertLogEntry((*it),bcur,cur);
            if (cp && cp->getListener()) {
                //cp->getListener()->contextProgress(++icount,_internal.size());
                if (cp->getListener()->contextCancel()) {
                    throw DatabaseException(QString("Could not retrieve values: User cancel."));
                }
            }
        }
    }
    return true;
}

bool svn::cache::ReposLog::fillCache(const svn::Revision&_end)
{
    svn::Revision end = _end;
    svn::Revision start = latestCachedRev().revnum()+1;
    return checkFill(start,end);
}

/*!
    \fn svn::cache::ReposLog::simpleLog(const svn::Revision&start,const svn::Revision&end,LogEntriesMap&target)
 */
bool svn::cache::ReposLog::simpleLog(LogEntriesMap&target,const svn::Revision&_start,const svn::Revision&_end)
{
    if (!m_Client||m_ReposRoot.isEmpty()) {
        return false;
    }
    target.clear();
    ContextP cp = m_Client->getContext();

    svn::Revision end = _end;
    svn::Revision start = _start;
    if (!checkFill(start,end)) {
        return false;
    }

    QSqlCursor cur("changeditems",true,m_Database);
    QSqlCursor bcur("logentries",true,m_Database);

    qDebug("End: "+end.toString());
    if (end==svn::Revision::HEAD) {
        end = latestCachedRev();
    }
    if (start==svn::Revision::HEAD) {
        start=latestCachedRev();
    }

    QString lim = QString("revision<=%1 and revision>=%2").arg(end.revnum()).arg(start.revnum());
    qDebug(lim);
    if (!bcur.select(lim)) {
        qDebug(bcur.lastError().text());
        throw svn::ClientException(QString("Could not retrieve values: ")+bcur.lastError().text());
        return false;
    }
    while(bcur.next()) {
        Q_LLONG revision= bcur.value("revision").toLongLong();
        lim=QString("revision=%1").arg(revision);
        if (!cur.select(lim)) {
            qDebug(cur.lastError().text());
            throw svn::ClientException(QString("Could not retrieve values: ")+cur.lastError().text());
            return false;
        }
        target[revision].revision=revision;
        target[revision].author=bcur.value("author").toString();
        target[revision].date=bcur.value("date").toLongLong();
        target[revision].message=bcur.value("message").toString();
        while(cur.next()) {
            char c = cur.value("action").toInt();
            LogChangePathEntry lcp;
            lcp.action=cur.value("action").toString()[0];
            lcp.copyFromPath=cur.value("copyfrom").toString().latin1();
            lcp.path= cur.value("changeditem").toString();
            lcp.copyFromRevision=cur.value("copyfromrev").toLongLong();
            target[revision].changedPaths.push_back(lcp);
        }
        if (cp && cp->getListener()) {
            //cp->getListener()->contextProgress(++icount,bcur.size());
            if (cp->getListener()->contextCancel()) {
                throw svn::ClientException(QString("Could not retrieve values: User cancel."));
            }
        }
    }
    return false;
}

/*!
    \fn svn::cache::ReposLog::date2numberRev(const svn::Revision&)
 */
svn::Revision svn::cache::ReposLog::date2numberRev(const svn::Revision&aRev)
{
    if (aRev!=svn::Revision::DATE) {
        return aRev;
    }
    if (!m_Database) {
        return svn::Revision::UNDEFINED;
    }
    QSqlCursor bcur("logentries",true,m_Database);
    QSqlIndex order = bcur.index("revision");
    order.setDescending(0,true);
    /// @todo as I understood - the resulting revision should always the last one BEFORE this date...
    //QString q=QString("date>='%1'").arg(value);
    //qDebug(q);
    bcur.select(order);
    if (bcur.lastError().type()!=QSqlError::None) {
        qDebug(bcur.lastError().text());
    }
    bool must_remote=true;
    if (bcur.next()) {
        if (bcur.value("date").toLongLong()>=aRev.date()) {
            must_remote=false;
        }
    }
    if (must_remote) {
        svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,aRev,aRev));;
        if (e.count()<1||e[0].reposRoot().isEmpty()) {
            return aRev;
        }
        return e[0].revision();
    }
    QString q=QString("date<'%1'").arg(aRev.date());
    bcur.select(q,order);
    qDebug("Search for date: " +q);
    if (bcur.lastError().type()!=QSqlError::None) {
        qDebug(bcur.lastError().text());
    }
    if (bcur.next()) {
        return bcur.value( "revision" ).toInt();
    }
    // not found...
    svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;
    if (e.count()<1||e[0].reposRoot().isEmpty()) {
        return aRev;
    }
    return e[0].revision();
}

/*!
    \fn svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&)
 */
bool svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&aEntry,QSqlCursor&lCur,QSqlCursor&cCur)
{
    QSqlRecord *buffer;
    m_Database->transaction();

#if QT_VERSION < 0x040000
    Q_LLONG j = aEntry.revision;
#else
    qlonglong j = aEntry.revision;
#endif
    buffer=lCur.primeInsert();
    buffer->setValue("revision",j);
    buffer->setValue("date",aEntry.date);
    buffer->setValue("author",aEntry.author);
    buffer->setValue("message",aEntry.message);
    lCur.insert();
    if (lCur.lastError().type()!=QSqlError::None) {
        m_Database->rollback();
        qDebug(QString("Could not insert values: ")+lCur.lastError().text());
    }
    svn::LogChangePathEntries::ConstIterator cpit = aEntry.changedPaths.begin();
    for (;cpit!=aEntry.changedPaths.end();++cpit){
        buffer = cCur.primeInsert();
        buffer->setValue("revision",j);
        buffer->setValue("changeditem",(*cpit).path);
        buffer->setValue("action",QString(QChar((*cpit).action)));
        buffer->setValue("copyfrom",(*cpit).copyFromPath);
        buffer->setValue("copyfromrev",Q_LLONG((*cpit).copyFromRevision));
        cCur.insert();
        if (cCur.lastError().type()!=QSqlError::None) {
            m_Database->rollback();
            qDebug(QString("Could not insert values: ")+cCur.lastError().text());
            throw DatabaseException(QString("Could not insert values: ")+cCur.lastError().text());
        }
    }
    m_Database->commit();
    return true;
}
<|endoftext|>


<commit_before>#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>

#include <absl/strings/str_cat.h>
#include <gflags/gflags.h>

DEFINE_int32(
    c,
    4,
    "threshold under which candidates are output. set to -1 to output all.");
DEFINE_bool(i, false, "add inverted tags");
DEFINE_int32(m, 0, "min number of set/cleared samples each");
DEFINE_int32(M, 0, "min number of set/cleared samples total");
DEFINE_string(o, "", "set output file");
DEFINE_string(k, "", "set output mask file");

using std::map;
using std::string;
using std::tuple;
using std::vector;

int num_bits = 0, num_tags = 0;
map<string, int> bit_ids, tag_ids;
vector<string> bit_ids_r, tag_ids_r;

#if 0
struct bool_vec
{
	vector<bool> data;

	bool_vec(int n = 0, bool initval = false) : data(n, initval)
	{
	}

	void set(int n)
	{
		if (int(data.size()) <= n)
			data.resize(n+1);
		data[n] = true;
	}

	bool get(int n)
	{
		return data.at(n);
	}

	void resize(int n)
	{
		data.resize(n);
	}

	int count()
	{
		return std::accumulate(data.begin(), data.end(), 0);
	}

	void apply_and(const bool_vec &other)
	{
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] = data[i] && other.data[i];
	}

	void apply_andc(const bool_vec &other)
	{
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] = data[i] && !other.data[i];
	}
};
#else
struct bool_vec {
	vector<uint64_t> data;

	bool_vec(int n = 0, bool initval = false)
	    : data((n + 63) / 64, initval ? ~uint64_t(0) : uint64_t(0)) {
		for (int i = data.size() * 64 - 1; i >= n; i--)
			data[n / 64] &= ~(uint64_t(1) << (n % 64));
	}

	void set(int n) {
		if (int(data.size() * 64) <= n)
			data.resize((n + 64) / 64);
		data[n / 64] |= uint64_t(1) << (n % 64);
	}

	bool get(int n) { return (data[n / 64] >> (n % 64)) & 1; }

	void resize(int n) { data.resize((n + 63) / 64); }

	int count() {
		int sum = 0;
		for (int i = 0; i < 64 * int(data.size()); i++)
			if (get(i))
				sum++;
		return sum;
	}

	void apply_and(const bool_vec& other) {
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] &= other.data[i];
	}

	void apply_andc(const bool_vec& other) {
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] &= ~other.data[i];
	}
};
#endif

// segname -> bits, tags_on, tags_off
typedef tuple<bool_vec, bool_vec, bool_vec> segdata_t;
map<string, segdata_t> segdata;

map<string, int> segnamecnt;

static inline bool_vec& segdata_bits(segdata_t& sd) {
	return std::get<0>(sd);
}
static inline bool_vec& segdata_tags1(segdata_t& sd) {
	return std::get<1>(sd);
}
static inline bool_vec& segdata_tags0(segdata_t& sd) {
	return std::get<2>(sd);
}

void read_input(std::istream& f, std::string filename) {
	string token;
	segdata_t* segptr = nullptr;

	while (f >> token) {
		if (token == "seg") {
			f >> token;
			token = filename + ":" + token;
			while (segdata.count(token)) {
				int idx = 1;
				if (segnamecnt.count(token))
					idx = segnamecnt.at(token);
				segnamecnt[token] = idx + 1;
				char buffer[64];
				snprintf(buffer, 64, "-%d", idx);
				token += buffer;
			}
			segptr = &segdata[token];
			continue;
		}

		if (token == "bit") {
			assert(segptr != nullptr);

			f >> token;
			if (bit_ids.count(token) == 0) {
				bit_ids[token] = num_bits++;
				bit_ids_r.push_back(token);
			}

			int bit_idx = bit_ids.at(token);
			auto& bits = segdata_bits(*segptr);

			bits.set(bit_idx);
			continue;
		}

		if (token == "tag") {
			assert(segptr != nullptr);

			f >> token;
			if (tag_ids.count(token) == 0) {
				tag_ids[token] = num_tags++;
				tag_ids_r.push_back(token);
			}

			int tag_idx = tag_ids.at(token);

			f >> token;
			assert(token == "0" || token == "1");

			auto& tags = token == "1" ? segdata_tags1(*segptr)
			                          : segdata_tags0(*segptr);

			tags.set(tag_idx);

			if (FLAGS_i) {
				auto& inv_tags = token == "1"
				                     ? segdata_tags0(*segptr)
				                     : segdata_tags1(*segptr);

				token = tag_ids_r.at(tag_idx) + "__INV";

				if (tag_ids.count(token) == 0) {
					tag_ids[token] = num_tags++;
					tag_ids_r.push_back(token);
				}

				int inv_tag_idx = tag_ids.at(token);
				inv_tags.set(inv_tag_idx);
			}

			continue;
		}

		abort();
	}

	// printf("Number of segments: %d\n", int(segdata.size()));
	// printf("Number of bits: %d\n", num_bits);
	// printf("Number of tags: %d\n", num_tags);

	for (auto& segdat : segdata) {
		segdata_bits(segdat.second).resize(num_bits);
		segdata_tags1(segdat.second).resize(num_tags);
		segdata_tags0(segdat.second).resize(num_tags);
	}
}

int main(int argc, char** argv) {
	gflags::SetUsageMessage(
	    absl::StrCat("Usage: ", argv[0], " [options] file.."));
	gflags::ParseCommandLineFlags(&argc, &argv, true);

	if (argc > 1) {
		for (int optind = 1; optind < argc; optind++) {
			printf("Reading %s.\n", argv[optind]);
			std::ifstream f;
			f.open(argv[optind]);
			assert(!f.fail());
			read_input(f, argv[optind]);
		}
	} else {
		printf("Reading from stding.\n");
		read_input(std::cin, "stdin");
	}

	printf("#of segments: %d\n", int(segdata.size()));
	printf("#of bits: %d\n", num_bits);
	printf("#of tags: %d\n", num_tags);

	FILE* f = stdout;

	if (!FLAGS_o.empty()) {
		f = fopen(FLAGS_o.c_str(), "w");
		assert(f != nullptr);
	}

	int cnt_const0 = 0;
	int cnt_const1 = 0;
	int cnt_candidates = 0;
	int min_candidates = num_bits;
	int max_candidates = 0;
	float avg_candidates = 0;

	std::vector<std::string> out_lines;

	for (int tag_idx = 0; tag_idx < num_tags; tag_idx++) {
		bool_vec mask(num_bits, true);
		int count1 = 0, count0 = 0;

		for (auto& segdat : segdata) {
			auto& sd = segdat.second;
			bool tag1 = segdata_tags1(sd).get(tag_idx);
			bool tag0 = segdata_tags0(sd).get(tag_idx);

			assert(!tag1 || !tag0);

			if (tag1) {
				count1++;
				mask.apply_and(segdata_bits(sd));
				continue;
			}

			if (tag0) {
				count0++;
				mask.apply_andc(segdata_bits(sd));
				continue;
			}
		}

		assert(count1 || count0);

		std::string out_line = tag_ids_r.at(tag_idx);

		if (count1 < FLAGS_m) {
			char buffer[64];
			snprintf(buffer, 64, " <m1 %d>", count1);
			out_line += buffer;
		}

		if (count0 < FLAGS_m) {
			char buffer[64];
			snprintf(buffer, 64, " <m0 %d>", count0);
			out_line += buffer;
		}

		if (count1 + count0 < FLAGS_M) {
			char buffer[64];
			snprintf(buffer, 64, " <M %d %d>", count1, count0);
			out_line += buffer;
		}

		if (!count1) {
			out_lines.push_back(out_line + " <const0>");
			cnt_const0 += 1;
			continue;
		}

		if (!count0) {
			out_line += " <const1>";
			cnt_const1 += 1;
		}

		int num_candidates = mask.count();

		if (count0) {
			min_candidates =
			    std::min(min_candidates, num_candidates);
			max_candidates =
			    std::max(max_candidates, num_candidates);
			avg_candidates += num_candidates;
			cnt_candidates += 1;
		}

		if (FLAGS_c < 0 ||
		    (0 < num_candidates && num_candidates <= FLAGS_c)) {
			std::vector<std::string> out_tags;
			for (int bit_idx = 0; bit_idx < num_bits; bit_idx++)
				if (mask.get(bit_idx))
					out_tags.push_back(
					    bit_ids_r.at(bit_idx));
			std::sort(out_tags.begin(), out_tags.end());
			for (auto& tag : out_tags)
				out_line += " " + tag;
		} else {
			char buffer[64];
			snprintf(buffer, 64, " <%d candidates>",
			         num_candidates);
			out_line += buffer;
		}

		out_lines.push_back(out_line);
	}

	std::sort(out_lines.begin(), out_lines.end());

	for (auto& line : out_lines)
		fprintf(f, "%s\n", line.c_str());

	if (cnt_candidates)
		avg_candidates /= cnt_candidates;

	printf("#of const0 tags: %d\n", cnt_const0);
	printf("#of const1 tags: %d\n", cnt_const1);

	if (cnt_candidates) {
		printf("min #of candidates: %d\n", min_candidates);
		printf("max #of candidates: %d\n", max_candidates);
		printf("avg #of candidates: %.3f\n", avg_candidates);
	}

	if (!FLAGS_k.empty()) {
		f = fopen(FLAGS_k.c_str(), "w");
		assert(f != nullptr);
		std::sort(bit_ids_r.begin(), bit_ids_r.end());
		for (auto bit : bit_ids_r)
			fprintf(f, "bit %s\n", bit.c_str());
	}

	return 0;
}
<commit_msg>segmatch: added warning for missing files<commit_after>#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>

#include <absl/strings/str_cat.h>
#include <gflags/gflags.h>

DEFINE_int32(
    c,
    4,
    "threshold under which candidates are output. set to -1 to output all.");
DEFINE_bool(i, false, "add inverted tags");
DEFINE_int32(m, 0, "min number of set/cleared samples each");
DEFINE_int32(M, 0, "min number of set/cleared samples total");
DEFINE_string(o, "", "set output file");
DEFINE_string(k, "", "set output mask file");

using std::map;
using std::string;
using std::tuple;
using std::vector;

int num_bits = 0, num_tags = 0;
map<string, int> bit_ids, tag_ids;
vector<string> bit_ids_r, tag_ids_r;

#if 0
struct bool_vec
{
	vector<bool> data;

	bool_vec(int n = 0, bool initval = false) : data(n, initval)
	{
	}

	void set(int n)
	{
		if (int(data.size()) <= n)
			data.resize(n+1);
		data[n] = true;
	}

	bool get(int n)
	{
		return data.at(n);
	}

	void resize(int n)
	{
		data.resize(n);
	}

	int count()
	{
		return std::accumulate(data.begin(), data.end(), 0);
	}

	void apply_and(const bool_vec &other)
	{
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] = data[i] && other.data[i];
	}

	void apply_andc(const bool_vec &other)
	{
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] = data[i] && !other.data[i];
	}
};
#else
struct bool_vec {
	vector<uint64_t> data;

	bool_vec(int n = 0, bool initval = false)
	    : data((n + 63) / 64, initval ? ~uint64_t(0) : uint64_t(0)) {
		for (int i = data.size() * 64 - 1; i >= n; i--)
			data[n / 64] &= ~(uint64_t(1) << (n % 64));
	}

	void set(int n) {
		if (int(data.size() * 64) <= n)
			data.resize((n + 64) / 64);
		data[n / 64] |= uint64_t(1) << (n % 64);
	}

	bool get(int n) { return (data[n / 64] >> (n % 64)) & 1; }

	void resize(int n) { data.resize((n + 63) / 64); }

	int count() {
		int sum = 0;
		for (int i = 0; i < 64 * int(data.size()); i++)
			if (get(i))
				sum++;
		return sum;
	}

	void apply_and(const bool_vec& other) {
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] &= other.data[i];
	}

	void apply_andc(const bool_vec& other) {
		assert(data.size() == other.data.size());
		for (int i = 0; i < int(data.size()); i++)
			data[i] &= ~other.data[i];
	}
};
#endif

// segname -> bits, tags_on, tags_off
typedef tuple<bool_vec, bool_vec, bool_vec> segdata_t;
map<string, segdata_t> segdata;

map<string, int> segnamecnt;

static inline bool_vec& segdata_bits(segdata_t& sd) {
	return std::get<0>(sd);
}
static inline bool_vec& segdata_tags1(segdata_t& sd) {
	return std::get<1>(sd);
}
static inline bool_vec& segdata_tags0(segdata_t& sd) {
	return std::get<2>(sd);
}

void read_input(std::istream& f, std::string filename) {
	string token;
	segdata_t* segptr = nullptr;

	while (f >> token) {
		if (token == "seg") {
			f >> token;
			token = filename + ":" + token;
			while (segdata.count(token)) {
				int idx = 1;
				if (segnamecnt.count(token))
					idx = segnamecnt.at(token);
				segnamecnt[token] = idx + 1;
				char buffer[64];
				snprintf(buffer, 64, "-%d", idx);
				token += buffer;
			}
			segptr = &segdata[token];
			continue;
		}

		if (token == "bit") {
			assert(segptr != nullptr);

			f >> token;
			if (bit_ids.count(token) == 0) {
				bit_ids[token] = num_bits++;
				bit_ids_r.push_back(token);
			}

			int bit_idx = bit_ids.at(token);
			auto& bits = segdata_bits(*segptr);

			bits.set(bit_idx);
			continue;
		}

		if (token == "tag") {
			assert(segptr != nullptr);

			f >> token;
			if (tag_ids.count(token) == 0) {
				tag_ids[token] = num_tags++;
				tag_ids_r.push_back(token);
			}

			int tag_idx = tag_ids.at(token);

			f >> token;
			assert(token == "0" || token == "1");

			auto& tags = token == "1" ? segdata_tags1(*segptr)
			                          : segdata_tags0(*segptr);

			tags.set(tag_idx);

			if (FLAGS_i) {
				auto& inv_tags = token == "1"
				                     ? segdata_tags0(*segptr)
				                     : segdata_tags1(*segptr);

				token = tag_ids_r.at(tag_idx) + "__INV";

				if (tag_ids.count(token) == 0) {
					tag_ids[token] = num_tags++;
					tag_ids_r.push_back(token);
				}

				int inv_tag_idx = tag_ids.at(token);
				inv_tags.set(inv_tag_idx);
			}

			continue;
		}

		abort();
	}

	// printf("Number of segments: %d\n", int(segdata.size()));
	// printf("Number of bits: %d\n", num_bits);
	// printf("Number of tags: %d\n", num_tags);

	for (auto& segdat : segdata) {
		segdata_bits(segdat.second).resize(num_bits);
		segdata_tags1(segdat.second).resize(num_tags);
		segdata_tags0(segdat.second).resize(num_tags);
	}
}

int main(int argc, char** argv) {
	gflags::SetUsageMessage(
	    absl::StrCat("Usage: ", argv[0], " [options] file.."));
	gflags::ParseCommandLineFlags(&argc, &argv, true);

	if (argc > 1) {
		for (int optind = 1; optind < argc; optind++) {
			printf("Reading %s.\n", argv[optind]);
			std::ifstream f;
			f.open(argv[optind]);

			// Check if input file exists.
			if (!f.good()) {
				printf("WARNING: Input file does not exist!\n");
			}

			assert(!f.fail());
			read_input(f, argv[optind]);
		}
	} else {
		printf("Reading from stding.\n");
		read_input(std::cin, "stdin");
	}

	printf("#of segments: %d\n", int(segdata.size()));
	printf("#of bits: %d\n", num_bits);
	printf("#of tags: %d\n", num_tags);

	FILE* f = stdout;

	if (!FLAGS_o.empty()) {
		f = fopen(FLAGS_o.c_str(), "w");
		assert(f != nullptr);
	}

	int cnt_const0 = 0;
	int cnt_const1 = 0;
	int cnt_candidates = 0;
	int min_candidates = num_bits;
	int max_candidates = 0;
	float avg_candidates = 0;

	std::vector<std::string> out_lines;

	for (int tag_idx = 0; tag_idx < num_tags; tag_idx++) {
		bool_vec mask(num_bits, true);
		int count1 = 0, count0 = 0;

		for (auto& segdat : segdata) {
			auto& sd = segdat.second;
			bool tag1 = segdata_tags1(sd).get(tag_idx);
			bool tag0 = segdata_tags0(sd).get(tag_idx);

			assert(!tag1 || !tag0);

			if (tag1) {
				count1++;
				mask.apply_and(segdata_bits(sd));
				continue;
			}

			if (tag0) {
				count0++;
				mask.apply_andc(segdata_bits(sd));
				continue;
			}
		}

		assert(count1 || count0);

		std::string out_line = tag_ids_r.at(tag_idx);

		if (count1 < FLAGS_m) {
			char buffer[64];
			snprintf(buffer, 64, " <m1 %d>", count1);
			out_line += buffer;
		}

		if (count0 < FLAGS_m) {
			char buffer[64];
			snprintf(buffer, 64, " <m0 %d>", count0);
			out_line += buffer;
		}

		if (count1 + count0 < FLAGS_M) {
			char buffer[64];
			snprintf(buffer, 64, " <M %d %d>", count1, count0);
			out_line += buffer;
		}

		if (!count1) {
			out_lines.push_back(out_line + " <const0>");
			cnt_const0 += 1;
			continue;
		}

		if (!count0) {
			out_line += " <const1>";
			cnt_const1 += 1;
		}

		int num_candidates = mask.count();

		if (count0) {
			min_candidates =
			    std::min(min_candidates, num_candidates);
			max_candidates =
			    std::max(max_candidates, num_candidates);
			avg_candidates += num_candidates;
			cnt_candidates += 1;
		}

		if (FLAGS_c < 0 ||
		    (0 < num_candidates && num_candidates <= FLAGS_c)) {
			std::vector<std::string> out_tags;
			for (int bit_idx = 0; bit_idx < num_bits; bit_idx++)
				if (mask.get(bit_idx))
					out_tags.push_back(
					    bit_ids_r.at(bit_idx));
			std::sort(out_tags.begin(), out_tags.end());
			for (auto& tag : out_tags)
				out_line += " " + tag;
		} else {
			char buffer[64];
			snprintf(buffer, 64, " <%d candidates>",
			         num_candidates);
			out_line += buffer;
		}

		out_lines.push_back(out_line);
	}

	std::sort(out_lines.begin(), out_lines.end());

	for (auto& line : out_lines)
		fprintf(f, "%s\n", line.c_str());

	if (cnt_candidates)
		avg_candidates /= cnt_candidates;

	printf("#of const0 tags: %d\n", cnt_const0);
	printf("#of const1 tags: %d\n", cnt_const1);

	if (cnt_candidates) {
		printf("min #of candidates: %d\n", min_candidates);
		printf("max #of candidates: %d\n", max_candidates);
		printf("avg #of candidates: %.3f\n", avg_candidates);
	}

	if (!FLAGS_k.empty()) {
		f = fopen(FLAGS_k.c_str(), "w");
		assert(f != nullptr);
		std::sort(bit_ids_r.begin(), bit_ids_r.end());
		for (auto bit : bit_ids_r)
			fprintf(f, "bit %s\n", bit.c_str());
	}

	return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                               libparaver-api                              *
 *                       Paraver Main Computing Library                      *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

#include "semanticderivedfunctions.h"
#include "kwindow.h"

using namespace std;

string DerivedAdd::name = "add";
TSemanticValue DerivedAdd::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];

  return tmp;
}

string DerivedProduct::name = "product";
TSemanticValue DerivedProduct::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] * myInfo->values[ 1 ];

  return tmp;
}

string DerivedSubstract::name = "substract";
TSemanticValue DerivedSubstract::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] - myInfo->values[ 1 ];

  return tmp;
}

string DerivedDivide::name = "divide";
TSemanticValue DerivedDivide::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0.0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  if( myInfo->values[ 1 ] == 0 )
    return 0.0;

  tmp = myInfo->values[ 0 ] / myInfo->values[ 1 ];

  return tmp;
}

string DerivedMaximum::name = "maximum";
TSemanticValue DerivedMaximum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string DerivedMinimum::name = "minimum";
TSemanticValue DerivedMinimum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] < myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string DerivedDifferent::name = "different";
TSemanticValue DerivedDifferent::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] != myInfo->values[ 1 ] ?
        1 :
        0;

  return tmp;
}

string ControlDerivedClearBy::name = "controlled: clear by";
TSemanticValue ControlDerivedClearBy::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if( myInfo->values[ 1 ] < prevValue[ tmpOrder ] )
  {
    tmp = 0;
    state[ tmpOrder ] = myInfo->values[ 0 ];
    prevValue[ tmpOrder ] = myInfo->values[ 1 ];
    prevResult[ tmpOrder ] = tmp;
  }
  else
  {
    if( state[ tmpOrder ] != myInfo->values[ 0 ] )
    {
      tmp = myInfo->values[ 0 ];
      state[ tmpOrder ] = myInfo->values[ 0 ];
      prevValue[ tmpOrder ] = myInfo->values[ 1 ];
      prevResult[ tmpOrder ] = tmp;
    }
    else
      tmp = prevResult[ tmpOrder ];

    prevValue[ tmpOrder ] = myInfo->values[ 1 ];
  }

  return tmp;
}

void ControlDerivedClearBy::init( KWindow *whichWindow )
{
  TObjectOrder size = 0;

  prevValue.clear();
  state.clear();
  prevResult.clear();

  if( whichWindow->getLevel() >= SYSTEM )
    size = whichWindow->getTrace()->totalCPUs();
  else
    size = whichWindow->getTrace()->totalThreads();

  prevValue.reserve( size );
  state.reserve( size );
  prevResult.reserve( size );
  for( TObjectOrder i = 0; i < size; i++ )
  {
    prevValue.push_back( 0 );
    state.push_back( 0 );
    prevResult.push_back( 0 );
  }
}

string ControlDerivedMaximum::name = "controlled: maximum";
TSemanticValue ControlDerivedMaximum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string ControlDerivedAdd::name = "controlled: add";
TSemanticValue ControlDerivedAdd::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];

  return tmp;
}
<commit_msg>BUG FIXED: controlled clear by aware of bursts with same value<commit_after>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                               libparaver-api                              *
 *                       Paraver Main Computing Library                      *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

#include "semanticderivedfunctions.h"
#include "kwindow.h"

using namespace std;

string DerivedAdd::name = "add";
TSemanticValue DerivedAdd::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];

  return tmp;
}

string DerivedProduct::name = "product";
TSemanticValue DerivedProduct::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] * myInfo->values[ 1 ];

  return tmp;
}

string DerivedSubstract::name = "substract";
TSemanticValue DerivedSubstract::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] - myInfo->values[ 1 ];

  return tmp;
}

string DerivedDivide::name = "divide";
TSemanticValue DerivedDivide::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0.0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  if( myInfo->values[ 1 ] == 0 )
    return 0.0;

  tmp = myInfo->values[ 0 ] / myInfo->values[ 1 ];

  return tmp;
}

string DerivedMaximum::name = "maximum";
TSemanticValue DerivedMaximum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string DerivedMinimum::name = "minimum";
TSemanticValue DerivedMinimum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] < myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string DerivedDifferent::name = "different";
TSemanticValue DerivedDifferent::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] != myInfo->values[ 1 ] ?
        1 :
        0;

  return tmp;
}

string ControlDerivedClearBy::name = "controlled: clear by";
TSemanticValue ControlDerivedClearBy::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if( myInfo->values[ 1 ] < prevValue[ tmpOrder ] )
  {
    tmp = 0;
    state[ tmpOrder ] = myInfo->values[ 0 ];
    prevValue[ tmpOrder ] = myInfo->values[ 1 ];
    prevResult[ tmpOrder ] = tmp;
  }
  else
  {
    tmp = myInfo->values[ 0 ];
    state[ tmpOrder ] = myInfo->values[ 0 ];
    prevValue[ tmpOrder ] = myInfo->values[ 1 ];
    prevResult[ tmpOrder ] = tmp;
  }

  return tmp;
}

void ControlDerivedClearBy::init( KWindow *whichWindow )
{
  TObjectOrder size = 0;

  prevValue.clear();
  state.clear();
  prevResult.clear();

  if( whichWindow->getLevel() >= SYSTEM )
    size = whichWindow->getTrace()->totalCPUs();
  else
    size = whichWindow->getTrace()->totalThreads();

  prevValue.reserve( size );
  state.reserve( size );
  prevResult.reserve( size );
  for( TObjectOrder i = 0; i < size; i++ )
  {
    prevValue.push_back( 0 );
    state.push_back( 0 );
    prevResult.push_back( 0 );
  }
}

string ControlDerivedMaximum::name = "controlled: maximum";
TSemanticValue ControlDerivedMaximum::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?
        myInfo->values[ 0 ] :
        myInfo->values[ 1 ];

  return tmp;
}

string ControlDerivedAdd::name = "controlled: add";
TSemanticValue ControlDerivedAdd::execute( const SemanticInfo *info )
{
  TSemanticValue tmp = 0;
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];

  return tmp;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"

using namespace std;

int main()
{

    cout << "Testes de Dominios" << endl;

    TUNome testeNome;

    switch(testeNome.run()){
        case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
                                break;
        case TUNome::FALHA  : cout << "Nome - FALHA" << endl;
                                break;
    }

    TUTelefone testeTelefone;

    switch(testeTelefone.run()){
        case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
                                break;
        case TUTelefone::FALHA  : cout << "Telefone - FALHA" << endl;
                                break;
    }

    TUTitulo testeTitulo;

    switch(testeTitulo.run()){
        case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
                                break;
        case TUTitulo::FALHA  : cout << "Titulo - FALHA" << endl;
                                break;
    }

    TUCodigo testeCodigo;

    switch(testeCodigo.run()){
        case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
                                break;
        case TUCodigo::FALHA  : cout << "Codigo - FALHA" << endl;
                                break;
    }

    TUGeneroLiterario testeGeneroLiterario;

    switch(testeGeneroLiterario.run()){
        case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
                                break;
        case TUGeneroLiterario::FALHA  : cout << "Genero Literario - FALHA" << endl;
                                break;
    }

        TUApelido testeApelido;

    switch(testeApelido.run()){
        case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
                                break;
        case TUApelido::FALHA  : cout << "Apelido - FALHA" << endl;
                                break;
    }

    TUSenha testeSenha;

    switch(testeSenha.run()){
        case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
                                break;
        case TUSenha::FALHA  : cout << "Senha - FALHA" << endl;
                                break;
    }

    TUData testeData;

    switch(testeData.run()){
        case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
                                break;
        case TUData::FALHA  : cout << "Data - FALHA" << endl;
                                break;
    }

    TUTexto testeTexto;

    switch(testeTexto.run()){
        case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
                                break;
        case TUTexto::FALHA  : cout << "Texto - FALHA" << endl;
                                break;
    }
    cout << endl;
    cout << "Testes de Entidades" << endl;

    TUUsuario testeUsuario;

    switch(testeUsuario.run()){
        case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
                                break;
        case TUUsuario::FALHA  : cout << "Usuario - FALHA" << endl;
                                break;
    }

    TUResenha testeResenha;

    switch(testeResenha.run()){
        case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
                                break;
        case TUResenha::FALHA  : cout << "Resenha - FALHA" << endl;
                                break;
    }

    TULivro testeLivro;

    switch(testeLivro.run()){
        case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
                                break;
        case TULivro::FALHA  : cout << "Livro - FALHA" << endl;
                                break;
    }
    return 0;
}
<commit_msg>add author<commit_after>#include <iostream>

#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"

/** @author Acio Fernandes Galiza Magalhes - 15/0115121
*   @author Diego Brian Coelho Leite - 14/0136371
*/

using namespace std;

int main()
{

    cout << "Testes de Dominios" << endl;

    TUNome testeNome;

    switch(testeNome.run()){
        case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
                                break;
        case TUNome::FALHA  : cout << "Nome - FALHA" << endl;
                                break;
    }

    TUTelefone testeTelefone;

    switch(testeTelefone.run()){
        case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
                                break;
        case TUTelefone::FALHA  : cout << "Telefone - FALHA" << endl;
                                break;
    }

    TUTitulo testeTitulo;

    switch(testeTitulo.run()){
        case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
                                break;
        case TUTitulo::FALHA  : cout << "Titulo - FALHA" << endl;
                                break;
    }

    TUCodigo testeCodigo;

    switch(testeCodigo.run()){
        case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
                                break;
        case TUCodigo::FALHA  : cout << "Codigo - FALHA" << endl;
                                break;
    }

    TUGeneroLiterario testeGeneroLiterario;

    switch(testeGeneroLiterario.run()){
        case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
                                break;
        case TUGeneroLiterario::FALHA  : cout << "Genero Literario - FALHA" << endl;
                                break;
    }

        TUApelido testeApelido;

    switch(testeApelido.run()){
        case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
                                break;
        case TUApelido::FALHA  : cout << "Apelido - FALHA" << endl;
                                break;
    }

    TUSenha testeSenha;

    switch(testeSenha.run()){
        case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
                                break;
        case TUSenha::FALHA  : cout << "Senha - FALHA" << endl;
                                break;
    }

    TUData testeData;

    switch(testeData.run()){
        case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
                                break;
        case TUData::FALHA  : cout << "Data - FALHA" << endl;
                                break;
    }

    TUTexto testeTexto;

    switch(testeTexto.run()){
        case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
                                break;
        case TUTexto::FALHA  : cout << "Texto - FALHA" << endl;
                                break;
    }
    cout << endl;
    cout << "Testes de Entidades" << endl;

    TUUsuario testeUsuario;

    switch(testeUsuario.run()){
        case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
                                break;
        case TUUsuario::FALHA  : cout << "Usuario - FALHA" << endl;
                                break;
    }

    TUResenha testeResenha;

    switch(testeResenha.run()){
        case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
                                break;
        case TUResenha::FALHA  : cout << "Resenha - FALHA" << endl;
                                break;
    }

    TULivro testeLivro;

    switch(testeLivro.run()){
        case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
                                break;
        case TULivro::FALHA  : cout << "Livro - FALHA" << endl;
                                break;
    }
    return 0;
}
<|endoftext|>