<commit_before>#include "Tron.h"
#include <algorithm>
#include <set>
std::ofstream debug;

//Note: I define Standard Directional Order (which I'll call standard order) to be: NORTH, EAST, SOUTH, WEST.

//Little useful function for debugging, as it will tell us what direction, in words, an integer corresponds to.
inline std::string stringFromDirection(int dir) {
	return dir == 0 ? "NORTH" : dir == 1 ? "EAST" : dir == 2 ? "SOUTH" : dir == 3 ? "WEST" : "NONSENSE";
}

/*This function finds out which squares Bot3 to location are empty.
It returns in the standard order of NORTH, EAST, SOUTH, and WEST as booleans which are true if the square is empty.
Note that this function DOES create dynamic memory. Make sure to delete it when you're done.*/
inline bool * emptyAjacentSquares(const std::vector< std::vector<int> > & map, const std::pair<int, int> & location) {
	bool * empty = new bool[4];
	empty[NORTH] = location.second != 15 && map[location.second + 1][location.first] == EMPTY;
	empty[EAST] = location.first != 15 && map[location.second][location.first + 1] == EMPTY;
	empty[SOUTH] = location.second != 0 && map[location.second - 1][location.first] == EMPTY;
	empty[WEST] = location.first != 0 && map[location.second][location.first - 1] == EMPTY;
	return empty;
}

//This is something to return if the square we want to return doesn't exist, and correspondingly something to compare against.
#define BAD_LOCATION std::pair<int, int>{ -1, -1 }

//This will give us the square we'd get to if we tried to move in direction dir from location.
inline std::pair<int, int> getLocation(const std::pair<int, int> & location, int dir) {
	if(dir == NORTH) return location.second == 15 ? BAD_LOCATION : std::pair<int, int>{ location.first, location.second + 1 };
	if(dir == EAST) return location.first == 15 ? BAD_LOCATION : std::pair<int, int>{ location.first + 1, location.second };
	if(dir == SOUTH) return location.second == 0 ? BAD_LOCATION : std::pair<int, int>{ location.first, location.second - 1 };
	if(dir == WEST) return location.first == 0 ? BAD_LOCATION : std::pair<int, int>{ location.first - 1, location.second };
	throw std::runtime_error("No such direction exists.");
}

int main() {
	//Seed rand with the time.
	srand(time(NULL));

	//Initialize bot with respect to the Tron Environment.
	init();

	//We'll want to keep track of the turn number to make debugging easier.
	int turnNumber = 0;

	//Execute loop forever (or until game ends)
	while(true) {
		//Update turn number:
		turnNumber++;

		//Gets the newest map. Every int will have a value of EMPTY, ME, OPPONENT, TAKEN_BY_ME, or TAKEN_BY_OPPONENT.
		std::vector< std::vector<int> > m = getMap();

		//Let's figure out where we are:
		std::pair<int, int> myLocation;
		for(int y = 0; y < 16; y++)  {
			for(int x = 0; x < 16; x++) {
				if(m[y][x] == ME) {
					myLocation = { x, y };
				}
			}
		}

		//Let's find out which directions are safe to go in:
		bool * safe = emptyAjacentSquares(m, myLocation);

		//Let's look at the counts of empty squares around the possible squares to go to:
		int dirEmptyCount[4];
		for(int a = 0; a < 4; a++) if(safe[a]) {
			//Get the location we would be in if we went in a certain direction (specified by a).
			std::pair<int, int> possibleSquare = getLocation(myLocation, a);
			//Make sure that square exists:
			if(possibleSquare != BAD_LOCATION) {
				//Find the squares around that square:
				bool * around = emptyAjacentSquares(m, possibleSquare);
				//Count the number of empty squares around that square and set it in our array:
				dirEmptyCount[a] = std::count(around, around + 4, true);
				//Cleanup:
				delete[] around;
			}
		}
		else dirEmptyCount[a] = 5; //Irrelevant, but we must ensure it's as large as possible because we don't want to go there.

		dbg::logln("-----------------------------------------------------\nDebug for turn #" + std::to_string(turnNumber) + ':');
		for(int a = 0; a < 4; a++) dbg::logln("Direction " + std::to_string(a) + " is " + (safe[a] ? "safe " : "not safe ") + "and has " + std::to_string(dirEmptyCount[a]) + " Bot3 empty squares.");

		//We'll go in the direction that has the most walls Bot3 to it and is free to go to. If there's a tie we use standard order.
		sendMove(std::min_element(dirEmptyCount, dirEmptyCount + 4) - dirEmptyCount);

		delete[] safe; //Cleanup
	}
}<commit_msg>Update TronBot.cpp<commit_after>#include "Tron.h"
#include <algorithm>
#include <set>
std::ofstream debug;

//Note: I define Standard Directional Order (which I'll call standard order) to be: NORTH, EAST, SOUTH, WEST.

//Little useful function for debugging, as it will tell us what direction, in words, an integer corresponds to.
inline std::string stringFromDirection(int dir) {
	return dir == 0 ? "NORTH" : dir == 1 ? "EAST" : dir == 2 ? "SOUTH" : dir == 3 ? "WEST" : "NONSENSE";
}

/*This function finds out which squares Bot3 to location are empty.
It returns in the standard order of NORTH, EAST, SOUTH, and WEST as booleans which are true if the square is empty.
Note that this function DOES create dynamic memory. Make sure to delete it when you're done.*/
inline bool * emptyAdjacentSquares(const std::vector< std::vector<int> > & map, const std::pair<int, int> & location) {
	bool * empty = new bool[4];
	empty[NORTH] = location.second != 15 && map[location.second + 1][location.first] == EMPTY;
	empty[EAST] = location.first != 15 && map[location.second][location.first + 1] == EMPTY;
	empty[SOUTH] = location.second != 0 && map[location.second - 1][location.first] == EMPTY;
	empty[WEST] = location.first != 0 && map[location.second][location.first - 1] == EMPTY;
	return empty;
}

//This is something to return if the square we want to return doesn't exist, and correspondingly something to compare against.
#define BAD_LOCATION std::pair<int, int>{ -1, -1 }

//This will give us the square we'd get to if we tried to move in direction dir from location.
inline std::pair<int, int> getLocation(const std::pair<int, int> & location, int dir) {
	if(dir == NORTH) return location.second == 15 ? BAD_LOCATION : std::pair<int, int>{ location.first, location.second + 1 };
	if(dir == EAST) return location.first == 15 ? BAD_LOCATION : std::pair<int, int>{ location.first + 1, location.second };
	if(dir == SOUTH) return location.second == 0 ? BAD_LOCATION : std::pair<int, int>{ location.first, location.second - 1 };
	if(dir == WEST) return location.first == 0 ? BAD_LOCATION : std::pair<int, int>{ location.first - 1, location.second };
	throw std::runtime_error("No such direction exists.");
}

int main() {
	//Seed rand with the time.
	srand(time(NULL));

	//Initialize bot with respect to the Tron Environment.
	init();

	//We'll want to keep track of the turn number to make debugging easier.
	int turnNumber = 0;

	//Execute loop forever (or until game ends)
	while(true) {
		//Update turn number:
		turnNumber++;

		//Gets the newest map. Every int will have a value of EMPTY, ME, OPPONENT, TAKEN_BY_ME, or TAKEN_BY_OPPONENT.
		std::vector< std::vector<int> > m = getMap();

		//Let's figure out where we are:
		std::pair<int, int> myLocation;
		for(int y = 0; y < 16; y++)  {
			for(int x = 0; x < 16; x++) {
				if(m[y][x] == ME) {
					myLocation = { x, y };
				}
			}
		}

		//Let's find out which directions are safe to go in:
		bool * safe = emptyAdjacentSquares(m, myLocation);

		//Let's look at the counts of empty squares around the possible squares to go to:
		int dirEmptyCount[4];
		for(int a = 0; a < 4; a++) if(safe[a]) {
			//Get the location we would be in if we went in a certain direction (specified by a).
			std::pair<int, int> possibleSquare = getLocation(myLocation, a);
			//Make sure that square exists:
			if(possibleSquare != BAD_LOCATION) {
				//Find the squares around that square:
				bool * around = emptyAdjacentSquares(m, possibleSquare);
				//Count the number of empty squares around that square and set it in our array:
				dirEmptyCount[a] = std::count(around, around + 4, true);
				//Cleanup:
				delete[] around;
			}
		}
		else dirEmptyCount[a] = 5; //Irrelevant, but we must ensure it's as large as possible because we don't want to go there.

		dbg::logln("-----------------------------------------------------\nDebug for turn #" + std::to_string(turnNumber) + ':');
		for(int a = 0; a < 4; a++) dbg::logln("Direction " + std::to_string(a) + " is " + (safe[a] ? "safe " : "not safe ") + "and has " + std::to_string(dirEmptyCount[a]) + " Bot3 empty squares.");

		//We'll go in the direction that has the most walls Bot3 to it and is free to go to. If there's a tie we use standard order.
		sendMove(std::min_element(dirEmptyCount, dirEmptyCount + 4) - dirEmptyCount);

		delete[] safe; //Cleanup
	}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "MRLineEditor.h"

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

#include "BasicsC/strings.h"

#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif

#ifdef TRI_ENABLE_MRUBY
extern "C" {
#include "mruby.h"
#include "compile.h"
}
#endif

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class MRLineEditor
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief word break characters
////////////////////////////////////////////////////////////////////////////////

#if 0
static char WordBreakCharacters[] = {
    ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
    '<', '>', '=', ';', '|', '&', '{', '}', '(', ')',
    '\0'
};
#endif

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief completion generator
////////////////////////////////////////////////////////////////////////////////

static char* CompletionGenerator (char const* text, int state) {
  return 0;

#if 0
  static size_t currentIndex;
  static vector<string> result;
  char* prefix;

  // compute the possible completion
  if (state == 0) {
    if (! v8::Context::InContext()) {
      return 0;
    }

    // locate global object or sub-object
    v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global();
    string path;

    if (*text != '\0') {
      TRI_vector_string_t splitted = TRI_SplitString(text, '.');

      if (1 < splitted._length) {
        for (size_t i = 0;  i < splitted._length - 1;  ++i) {
          v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]);

          if (! current->Has(name)) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          v8::Handle<v8::Value> val = current->Get(name);

          if (! val->IsObject()) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          current = val->ToObject();
          path = path + splitted._buffer[i] + ".";
        }

        prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
      }
      else {
        prefix = TRI_DuplicateString(text);
      }

      TRI_DestroyVectorString(&splitted);
    }
    else {
      prefix = TRI_DuplicateString(text);
    }

    // compute all possible completions
    v8::Handle<v8::Array> properties;
    v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS");

    if (current->HasOwnProperty(cpl)) {
      v8::Handle<v8::Value> funcVal = current->Get(cpl);

      if (funcVal->IsFunction()) {
        v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
        v8::Handle<v8::Value> args;
        v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);

        if (cpls->IsArray()) {
          properties = v8::Handle<v8::Array>::Cast(cpls);
        }
      }
    }
    else {
      properties = current->GetPropertyNames();
    }

    // locate
    if (! properties.IsEmpty()) {
      size_t n = properties->Length();

      for (size_t i = 0;  i < n;  ++i) {
        v8::Handle<v8::Value> v = properties->Get(i);

        v8::String::Utf8Value str(v);
        char const* s = *str;

        if (s != 0 && *s) {
          string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
          string name = path + s + suffix;

          if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
            result.push_back(name);
          }
        }
      }
    }

    currentIndex = 0;

    TRI_FreeString(prefix);
  }

  if (currentIndex < result.size()) {
    return TRI_DuplicateString(result[currentIndex++].c_str());
  }
  else {
    result.clear();
    return 0;
  }
#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief attempted completion
////////////////////////////////////////////////////////////////////////////////

#if 0
static char** AttemptedCompletion (char const* text, int start, int end) {
  char** result;

  result = completion_matches(text, CompletionGenerator);
  rl_attempted_completion_over = true;

  if (result != 0 && result[0] != 0 && result[1] == 0) {
    size_t n = strlen(result[0]);

    if (result[0][n-1] == ')') {
      result[0][n-1] = '\0';

#if RL_READLINE_VERSION >= 0x0500
      rl_completion_suppress_append = 1;
#endif
    }
  }

  return result;
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////

MRLineEditor::MRLineEditor (MR_state_t* mrs, string const& history)
  : LineEditor(history), _current(), _mrs(mrs) {
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor open
////////////////////////////////////////////////////////////////////////////////

bool MRLineEditor::open (const bool autoComplete) {
  return LineEditor::open(autoComplete);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 protected methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief check if line is complete
////////////////////////////////////////////////////////////////////////////////

bool MRLineEditor::isComplete (string const& source, size_t lineno, size_t column) {

#ifdef TRI_ENABLE_MRUBY
  char const* msg = "syntax error, unexpected $end";
  char* text = TRI_DuplicateString(source.c_str());

  struct mrb_parser_state* p = mrb_parse_nstring_ext(&_mrs->_mrb, text, source.size());
  TRI_FreeString(TRI_CORE_MEM_ZONE, text);

  // out of memory?
  if (p == 0) {
    return true;
  }

  // no error or strange error
  if (p->tree != 0) {
    return true;
  }

  // check for end-of-line
  if (0 < p->nerr) {
    if (TRI_EqualString2(p->error_buffer[0].message, msg, strlen(msg))) {
      return false;
    }
  }
#endif

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>comment out unused func<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "MRLineEditor.h"

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

#include "BasicsC/strings.h"

#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif

#ifdef TRI_ENABLE_MRUBY
extern "C" {
#include "mruby.h"
#include "compile.h"
}
#endif

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class MRLineEditor
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief word break characters
////////////////////////////////////////////////////////////////////////////////

#if 0
static char WordBreakCharacters[] = {
    ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
    '<', '>', '=', ';', '|', '&', '{', '}', '(', ')',
    '\0'
};
#endif

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief completion generator
////////////////////////////////////////////////////////////////////////////////

#if 0
static char* CompletionGenerator (char const* text, int state) {
  static size_t currentIndex;
  static vector<string> result;
  char* prefix;

  // compute the possible completion
  if (state == 0) {
    if (! v8::Context::InContext()) {
      return 0;
    }

    // locate global object or sub-object
    v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global();
    string path;

    if (*text != '\0') {
      TRI_vector_string_t splitted = TRI_SplitString(text, '.');

      if (1 < splitted._length) {
        for (size_t i = 0;  i < splitted._length - 1;  ++i) {
          v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]);

          if (! current->Has(name)) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          v8::Handle<v8::Value> val = current->Get(name);

          if (! val->IsObject()) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          current = val->ToObject();
          path = path + splitted._buffer[i] + ".";
        }

        prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
      }
      else {
        prefix = TRI_DuplicateString(text);
      }

      TRI_DestroyVectorString(&splitted);
    }
    else {
      prefix = TRI_DuplicateString(text);
    }

    // compute all possible completions
    v8::Handle<v8::Array> properties;
    v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS");

    if (current->HasOwnProperty(cpl)) {
      v8::Handle<v8::Value> funcVal = current->Get(cpl);

      if (funcVal->IsFunction()) {
        v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
        v8::Handle<v8::Value> args;
        v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);

        if (cpls->IsArray()) {
          properties = v8::Handle<v8::Array>::Cast(cpls);
        }
      }
    }
    else {
      properties = current->GetPropertyNames();
    }

    // locate
    if (! properties.IsEmpty()) {
      size_t n = properties->Length();

      for (size_t i = 0;  i < n;  ++i) {
        v8::Handle<v8::Value> v = properties->Get(i);

        v8::String::Utf8Value str(v);
        char const* s = *str;

        if (s != 0 && *s) {
          string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
          string name = path + s + suffix;

          if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
            result.push_back(name);
          }
        }
      }
    }

    currentIndex = 0;

    TRI_FreeString(prefix);
  }

  if (currentIndex < result.size()) {
    return TRI_DuplicateString(result[currentIndex++].c_str());
  }
  else {
    result.clear();
    return 0;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// @brief attempted completion
////////////////////////////////////////////////////////////////////////////////

#if 0
static char** AttemptedCompletion (char const* text, int start, int end) {
  char** result;

  result = completion_matches(text, CompletionGenerator);
  rl_attempted_completion_over = true;

  if (result != 0 && result[0] != 0 && result[1] == 0) {
    size_t n = strlen(result[0]);

    if (result[0][n-1] == ')') {
      result[0][n-1] = '\0';

#if RL_READLINE_VERSION >= 0x0500
      rl_completion_suppress_append = 1;
#endif
    }
  }

  return result;
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////

MRLineEditor::MRLineEditor (MR_state_t* mrs, string const& history)
  : LineEditor(history), _current(), _mrs(mrs) {
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRLineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor open
////////////////////////////////////////////////////////////////////////////////

bool MRLineEditor::open (const bool autoComplete) {
  return LineEditor::open(autoComplete);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 protected methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief check if line is complete
////////////////////////////////////////////////////////////////////////////////

bool MRLineEditor::isComplete (string const& source, size_t lineno, size_t column) {

#ifdef TRI_ENABLE_MRUBY
  char const* msg = "syntax error, unexpected $end";
  char* text = TRI_DuplicateString(source.c_str());

  struct mrb_parser_state* p = mrb_parse_nstring_ext(&_mrs->_mrb, text, source.size());
  TRI_FreeString(TRI_CORE_MEM_ZONE, text);

  // out of memory?
  if (p == 0) {
    return true;
  }

  // no error or strange error
  if (p->tree != 0) {
    return true;
  }

  // check for end-of-line
  if (0 < p->nerr) {
    if (TRI_EqualString2(p->error_buffer[0].message, msg, strlen(msg))) {
      return false;
    }
  }
#endif

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/DIALOGS/setCamera.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/stage.h>

#include <qpushbutton.h>
#include <qlineedit.h>

namespace BALL
{
	namespace VIEW
	{

SetCamera::SetCamera( QWidget* parent,  const char* name, bool modal, WFlags fl )
    : SetCameraData( parent, name, modal, fl )
{
	const Camera& camera = ((Scene*) parent)->getStage()->getCamera();

	String text(String(camera.getViewPoint().x) + "|" +
							String(camera.getViewPoint().y) + "|" +
							String(camera.getViewPoint().z));
	view_edit->setText(text.c_str());

	text = String(camera.getLookAtPosition().x) + "|" +
				 String(camera.getLookAtPosition().y) + "|" +
				 String(camera.getLookAtPosition().z);

	look_edit->setText(text.c_str());
}

SetCamera::~SetCamera()
{
 // no need to delete child widgets, Qt does it all for us
}

void SetCamera::okPressed()
{
	MainControl *main_control = MainControl::getMainControl(parentWidget());

	hide();
	vector<String> strings1, strings2;
	String(view_edit->text().ascii()).split(strings1, "|");
	String(look_edit->text().ascii()).split(strings2, "|");

	if (strings1.size() != 3 ||
			strings2.size() != 3)
	{
		main_control->setStatusbarText("Invalid Values!");
		return;
	}

	for (Index i = 0; i<3; i++)
	{
		if (!strings1[i].isFloat() ||
				!strings2[i].isFloat())
		{
			main_control->setStatusbarText("Invalid Values!");
			return;
		}
	}

	Camera& camera = ((Scene*) parentWidget())->getStage()->getCamera();
	camera.setViewPoint(Vector3(strings1[0].toFloat(), strings1[1].toFloat(), strings1[2].toFloat()));
	camera.setLookAtPosition(Vector3(strings2[0].toFloat(), strings2[1].toFloat(), strings2[2].toFloat()));
}

// NAMESPACE
} }
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/DIALOGS/setCamera.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/stage.h>

#include <qpushbutton.h>
#include <qlineedit.h>

namespace BALL
{
	namespace VIEW
	{

SetCamera::SetCamera( QWidget* parent,  const char* name, bool modal, WFlags fl )
    : SetCameraData( parent, name, modal, fl )
{
	const Camera& camera = ((Scene*) parent)->getStage()->getCamera();

	String text(String(camera.getViewPoint().x) + "|" +
							String(camera.getViewPoint().y) + "|" +
							String(camera.getViewPoint().z));
	view_edit->setText(text.c_str());

	text = String(camera.getLookAtPosition().x) + "|" +
				 String(camera.getLookAtPosition().y) + "|" +
				 String(camera.getLookAtPosition().z);

	look_edit->setText(text.c_str());
}

SetCamera::~SetCamera()
{
 // no need to delete child widgets, Qt does it all for us
}

void SetCamera::okPressed()
{
	MainControl *main_control = MainControl::getMainControl(parentWidget());

	hide();
	vector<String> strings1, strings2;
	String(view_edit->text().ascii()).split(strings1, "|");
	String(look_edit->text().ascii()).split(strings2, "|");

	if (strings1.size() != 3 ||
			strings2.size() != 3)
	{
		main_control->setStatusbarText("Invalid Values!");
		return;
	}

	for (Index i = 0; i<3; i++)
	{
		if (!strings1[i].isFloat() ||
				!strings2[i].isFloat())
		{
			main_control->setStatusbarText("Invalid Values!");
			return;
		}
	}

	Vector3 vp(strings1[0].toFloat(), strings1[1].toFloat(), strings1[2].toFloat());
	Vector3 lp(strings2[0].toFloat(), strings2[1].toFloat(), strings2[2].toFloat());
	if (vp == lp)
	{
		Log.error() << "Invalid values for setCamera: viewpoint = look at" << std::endl;
		return;
	}

	Camera& camera = ((Scene*) parentWidget())->getStage()->getCamera();
	camera.setViewPoint(vp);
	camera.setLookAtPosition(lp);
}

// NAMESPACE
} }
<|endoftext|>


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

#include <async.h>
#include <sfsmisc.h>
#include <dhash_common.h>
#include <dhash_prot.h>
#include <dhashclient.h>
#include <dhblock.h>
#include <dbfe.h>
#include <crypt.h>
#include <sys/time.h>

static bigint *IDs;
static bool *done;
static void **data;
str control_socket;
static FILE *outfile;
static FILE *bwfile;
unsigned int datasize;

ptr<axprt_stream> xprt;
int fconnected = 0;
int out = 0;
int totalnum = 0;
int MAX_OPS_OUT = 1024;

int bps = 0;
int sec = 0;
timecb_t *measurer = NULL;

u_int64_t
getusec ()
{
  timeval tv;
  gettimeofday (&tv, NULL);
  return tv.tv_sec * INT64(1000000) + tv.tv_usec;
}

void
measure_bw (void)
{
  float bw = datasize * bps; // we get called every second
  bw /= 1024; // convert to K.
  sec++;
  unsigned long long usecs = (getusec ()/1000);
  fprintf (bwfile, "%llu\t%6.2f KB/s\n", usecs, bw);
  bps = 0;
  measurer = delaycb (1, wrap (&measure_bw));
}

chordID
make_block (void *data, int g)
{
  // size must be word sized
  //  assert (datasize % sizeof (long) == 0);

  char *rd = (char *)data;
  for (unsigned int i = 0; i < datasize; i++)
        rd[i] = random();
    //rd[i] = (char)('a' + g);
  rd[datasize - 1] = 0;

  return compute_hash (rd, datasize);
}

void
prepare_test_data (int num)
{
  IDs = New chordID[num];
  data = (void **)malloc(sizeof(void *)*num);
  done = (bool *)malloc (sizeof (bool) * num);
  for (int i = 0; i < num; i++) {
    data[i] = malloc(datasize);
    IDs[i] = make_block(data[i], i);
    done[i] = false;
  }
}

void
store_cb (u_int64_t start, dhash_stat status, ptr<insert_info> i)
{
  out--;

  strbuf s;
  if (status != DHASH_OK) {
    s << "store_cb: " << i->key << " " << status << "\n";
  } else {
    bps++;
    s << (i->key>>144) << " / " << (getusec () - start)/1000 << " /";
    for (size_t j = 0; j < i->path.size (); j++)
      s << " " << (i->path[j]>>144);
    s << "\n";
  }
  str buf (s);
  fprintf (outfile, "%s", buf.cstr ());
  if (outfile != stdout)
    warnx << buf;
}

int
store (dhashclient *dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    dhash->insert ((char *)data[i], datasize, wrap (store_cb, getusec ()));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck ();

  return 0;
}

void
fetch_cb (int i, struct timeval start, dhash_stat stat, ptr<dhash_block> blk, vec<chordID> path)
{
  out--;
  done[i] = true;

  if (!blk) {
    strbuf buf;
    buf << "Error: " << IDs[i] << "\n";
    fprintf (outfile, str (buf).cstr ());
  }
  else if (datasize != blk->data.len () || memcmp (data[i], blk->data.cstr (), datasize) != 0)
    fatal << "verification failed for block " << IDs[i];
  else {
    struct timeval end;
    gettimeofday(&end, NULL);
    strbuf buf;
    float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
    char estr[128];
    sprintf (estr, "%f", elapsed);

    bps++;
    buf << (IDs[i]>>144) << " " << estr;
    buf << " /";
    for (u_int i = 0; i < blk->times.size (); i++)
      buf << " " << blk->times[i];
    buf << " /";

    buf << " " << blk->hops << " " <<  blk->errors
	<< " " << blk->retries << " ";
    for (u_int i=0; i < path.size (); i++) {
      buf << (path[i]>>144) << " ";
    }

    buf << "\n";
    fprintf (outfile, str (buf).cstr ());
    if (outfile != stdout)
      warnx << buf;
  }
}

void
fetch (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    struct timeval start;
    gettimeofday (&start, NULL);

    dhash.retrieve (IDs[i], DHASH_CONTENTHASH, wrap (fetch_cb, i, start));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck();
}

void
usage (char *progname)
{
  warn << "vnode_num control_socket num_trials data_size file <f or s> nops seed [bw-file]\n";
  exit(0);
}

void
cleanup (void)
{
  for (int i = 0; i < totalnum; i++) {
    if (!done[i])
      warn << (IDs[i]>>144) << " not done " << "\n";
  }
  if (outfile) {
    fclose (outfile);
  }
  if (bwfile) {
    fclose (bwfile);
  }
  exit (1);
}

void
eofhandler ()
{
  warn << "Unexpected EOF: block too large?\n";
  cleanup ();
}

void
connected (dhashclient *dhash, int argc, char **argv)
{
  dhash->seteofcb (wrap (eofhandler));

  fconnected = 1;
  int num = atoi(argv[3]);
  totalnum = num;
  datasize = atoi(argv[4]);

  char *output = argv[5];
  if (strcmp(output, "-") == 0)
    outfile = stdout;
  else
    outfile = fopen(output, "w");

  char *bwoutput;
  if (argc > 9) {
    bwoutput = argv[9];
    if (strcmp (bwoutput, "-") == 0)
      bwfile = stdout;
    else
      bwfile = fopen (bwoutput, "w");

    fflush (bwfile);
    measurer = delaycb (1, wrap (&measure_bw));
  }

  if (!outfile) {
    printf ("could not open %s\n", output);
    exit(1);
  }

  unsigned int seed = strtoul (argv[8], NULL, 10);
  srandom (seed);
  prepare_test_data (num);

  MAX_OPS_OUT = atoi(argv[7]);

  struct timeval start;
  gettimeofday (&start, NULL);

  if (argv[6][0] == 's')
    store (dhash, num);
  else
    fetch (*dhash, num);

  struct timeval end;
  gettimeofday (&end, NULL);
  float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
  fprintf(outfile, "Total Elapsed: %f\n", elapsed);

  if (bwfile && measurer) {
    timecb_remove (measurer);
    measurer = NULL;
    measure_bw ();
    fclose (bwfile);
  }

  fclose (outfile);

  delete dhash;
}

void
tcp_connect_cb (int argc, char **argv, int fd)
{
  if (fd < 0)
    fatal << "connect failed\n";
  warnx << "... connected!\n";
  xprt = axprt_stream::alloc (fd);
  dhashclient *dhash = New dhashclient (xprt);
  connected (dhash, argc, argv);
}

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

  if (argc < 9) {
    usage (argv[0]);
    exit (1);
  }
  sigcb (SIGTERM, wrap (&cleanup));
  sigcb (SIGINT, wrap (&cleanup));

  control_socket = argv[2];
  char *cstr = (char *)control_socket.cstr ();
  if (strchr (cstr, ':')) {
    char *port = strchr (cstr, ':');
    *port = 0; //isolate host
    port++; // point at port
    char *host = cstr;
    short i_port = atoi (port);
    warn << "Connecting to " << host << ":" << i_port << " via TCP...";
    tcpconnect (host, i_port, wrap (&tcp_connect_cb, argc, argv));
    while (!fconnected) acheck ();
  } else {
    dhashclient *dhash = New dhashclient (control_socket);
    connected (dhash, argc, argv);
  }
}

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

#include <async.h>
#include <dhash_common.h>
#include <dhashclient.h>
#include <dhblock.h>
#include <sys/time.h>

static bigint *IDs;
static bool *done;
static void **data;
str control_socket;
static FILE *outfile;
static FILE *bwfile;
unsigned int datasize;

ptr<axprt_stream> xprt;
int fconnected = 0;
int out = 0;
int totalnum = 0;
int MAX_OPS_OUT = 1024;

int bps = 0;
int sec = 0;
timecb_t *measurer = NULL;

u_int64_t
getusec ()
{
  timeval tv;
  gettimeofday (&tv, NULL);
  return tv.tv_sec * INT64(1000000) + tv.tv_usec;
}

void
measure_bw (void)
{
  float bw = datasize * bps; // we get called every second
  bw /= 1024; // convert to K.
  sec++;
  unsigned long long usecs = (getusec ()/1000);
  fprintf (bwfile, "%llu\t%6.2f KB/s\n", usecs, bw);
  bps = 0;
  measurer = delaycb (1, wrap (&measure_bw));
}

chordID
make_block (void *data, int g)
{
  // size must be word sized
  //  assert (datasize % sizeof (long) == 0);

  char *rd = (char *)data;
  for (unsigned int i = 0; i < datasize; i++)
        rd[i] = random();
    //rd[i] = (char)('a' + g);
  rd[datasize - 1] = 0;

  return compute_hash (rd, datasize);
}

void
prepare_test_data (int num)
{
  IDs = New chordID[num];
  data = (void **)malloc(sizeof(void *)*num);
  done = (bool *)malloc (sizeof (bool) * num);
  for (int i = 0; i < num; i++) {
    data[i] = malloc(datasize);
    IDs[i] = make_block(data[i], i);
    done[i] = false;
  }
}

void
store_cb (u_int64_t start, dhash_stat status, ptr<insert_info> i)
{
  out--;

  strbuf s;
  if (status != DHASH_OK) {
    s << "store_cb: " << i->key << " " << status << "\n";
  } else {
    bps++;
    s << (i->key>>144) << " / " << (getusec () - start)/1000 << " /";
    for (size_t j = 0; j < i->path.size (); j++)
      s << " " << (i->path[j]>>144);
    s << "\n";
  }
  str buf (s);
  fprintf (outfile, "%s", buf.cstr ());
  if (outfile != stdout)
    warnx << buf;
}

int
store (dhashclient *dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    dhash->insert ((char *)data[i], datasize, wrap (store_cb, getusec ()));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck ();

  return 0;
}

void
fetch_cb (int i, struct timeval start, dhash_stat stat, ptr<dhash_block> blk, vec<chordID> path)
{
  out--;
  done[i] = true;

  if (!blk) {
    strbuf buf;
    buf << "Error: " << IDs[i] << "\n";
    fprintf (outfile, str (buf).cstr ());
  }
  else if (datasize != blk->data.len () || memcmp (data[i], blk->data.cstr (), datasize) != 0)
    fatal << "verification failed for block " << IDs[i];
  else {
    struct timeval end;
    gettimeofday(&end, NULL);
    strbuf buf;
    float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
    char estr[128];
    sprintf (estr, "%f", elapsed);

    bps++;
    buf << (IDs[i]>>144) << " " << estr;
    buf << " /";
    for (u_int i = 0; i < blk->times.size (); i++)
      buf << " " << blk->times[i];
    buf << " /";

    buf << " " << blk->hops << " " <<  blk->errors
	<< " " << blk->retries << " ";
    for (u_int i=0; i < path.size (); i++) {
      buf << (path[i]>>144) << " ";
    }

    buf << "\n";
    fprintf (outfile, str (buf).cstr ());
    if (outfile != stdout)
      warnx << buf;
  }
}

void
fetch (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    struct timeval start;
    gettimeofday (&start, NULL);

    dhash.retrieve (IDs[i], DHASH_CONTENTHASH, wrap (fetch_cb, i, start));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck();
}

void
usage (char *progname)
{
  warn << "vnode_num control_socket num_trials data_size file <f or s> nops seed [bw-file]\n";
  exit(0);
}

void
cleanup (void)
{
  for (int i = 0; i < totalnum; i++) {
    if (!done[i])
      warn << (IDs[i]>>144) << " not done " << "\n";
  }
  if (outfile) {
    fclose (outfile);
  }
  if (bwfile) {
    fclose (bwfile);
  }
  exit (1);
}

void
eofhandler ()
{
  warn << "Unexpected EOF: block too large?\n";
  cleanup ();
}

void
connected (dhashclient *dhash, int argc, char **argv)
{
  dhash->seteofcb (wrap (eofhandler));

  fconnected = 1;
  int num = atoi(argv[3]);
  totalnum = num;
  datasize = atoi(argv[4]);

  char *output = argv[5];
  if (strcmp(output, "-") == 0)
    outfile = stdout;
  else
    outfile = fopen(output, "w");

  char *bwoutput;
  if (argc > 9) {
    bwoutput = argv[9];
    if (strcmp (bwoutput, "-") == 0)
      bwfile = stdout;
    else
      bwfile = fopen (bwoutput, "w");

    fflush (bwfile);
    measurer = delaycb (1, wrap (&measure_bw));
  }

  if (!outfile) {
    printf ("could not open %s\n", output);
    exit(1);
  }

  unsigned int seed = strtoul (argv[8], NULL, 10);
  srandom (seed);
  prepare_test_data (num);

  MAX_OPS_OUT = atoi(argv[7]);

  struct timeval start;
  gettimeofday (&start, NULL);

  if (argv[6][0] == 's')
    store (dhash, num);
  else
    fetch (*dhash, num);

  struct timeval end;
  gettimeofday (&end, NULL);
  float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
  fprintf(outfile, "Total Elapsed: %f\n", elapsed);

  if (bwfile && measurer) {
    timecb_remove (measurer);
    measurer = NULL;
    measure_bw ();
    fclose (bwfile);
  }

  fclose (outfile);

  delete dhash;
}

void
tcp_connect_cb (int argc, char **argv, int fd)
{
  if (fd < 0)
    fatal << "connect failed\n";
  warnx << "... connected!\n";
  xprt = axprt_stream::alloc (fd);
  dhashclient *dhash = New dhashclient (xprt);
  connected (dhash, argc, argv);
}

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

  if (argc < 9) {
    usage (argv[0]);
    exit (1);
  }
  sigcb (SIGTERM, wrap (&cleanup));
  sigcb (SIGINT, wrap (&cleanup));

  control_socket = argv[2];
  char *cstr = (char *)control_socket.cstr ();
  if (strchr (cstr, ':')) {
    char *port = strchr (cstr, ':');
    *port = 0; //isolate host
    port++; // point at port
    char *host = cstr;
    short i_port = atoi (port);
    warn << "Connecting to " << host << ":" << i_port << " via TCP...";
    tcpconnect (host, i_port, wrap (&tcp_connect_cb, argc, argv));
    while (!fconnected) acheck ();
  } else {
    dhashclient *dhash = New dhashclient (control_socket);
    connected (dhash, argc, argv);
  }
}

<|endoftext|>


<commit_before>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"

#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"

int
GenerateConfigFile::operator() () {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );

	std::map< std::string, std::string > mapping;
	mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
	mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
	mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
	mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
	mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
	mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
	mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
	mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";

	// Append the annex configuration to the user config file.
	FILE * configFile = NULL;

	// Consider using createUserConfigDir() from user-config-dir.h.
	std::string userConfigName;
	MyString userConfigSource;
	param( userConfigName, "USER_CONFIG_FILE" );
	if(! userConfigName.empty()) {
		find_user_file( userConfigSource, userConfigName.c_str(), false );
		if(! userConfigSource.empty()) {
			// Create the containing directory if necessary, and only the
			// containing directory -- don't do anything stupid if the
			// user configuration directory is misconfigured.
			std::string dir, file;
			filename_split( userConfigSource.c_str(), dir, file );
			if(! IsDirectory( dir.c_str() )) {
				mkdir( dir.c_str(), 0755 );
			}

			configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
				"a", 0644 );
			if( configFile == NULL ) {
				fprintf( stderr, "Failed to open user configuration file '%s': %s (%d).  Printing configuration...\n",
					userConfigSource.c_str(), strerror( errno ), errno );
				configFile = stdout;
			}
		} else {
			fprintf( stderr, "Unable to locate your user configuration file.  Printing configuration...\n" );
			configFile = stdout;
		}
	} else {
		fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files.  Contact your system administrator.  Printing configuration...\n" );
		configFile = stdout;
	}

	char * safeRegion = NULL;
	if( region != NULL ) {
		safeRegion = strdup( region );
		assert( safeRegion != NULL );
		for( unsigned i = 0; i < strlen( region ); ++i ) {
			if( ('a' <= region[i] && region[i] <= 'z') ||
			    ('A' <= region[i] && region[i] <= 'Z') ||
			    ('0' <= region[i] && region[i] <= '9') ||
			    strchr( "_./", region[i] ) != NULL )
			{
				continue;
			} else {
				safeRegion[i] = '_';
			}
		}
	}

	fprintf( configFile, "\n" );
	if( safeRegion ) {
		fprintf( configFile, "# Generated by condor-annex -setup for region %s.\n", safeRegion );
	} else {
		fprintf( configFile, "# Generated by condor_annex -setup.\n" );
	}

	std::string value;
	for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
		value.clear();
		scratchpad->LookupString( i->first.c_str(), value );
		if(! value.empty()) {
			fprintf( configFile, "%s%s%s = %s\n",
				safeRegion ? safeRegion : "",
				safeRegion ? "." : "",
				i->second.c_str(), value.c_str() );
		}
	}

	std::string keyPath;
	scratchpad->LookupString( "KeyPath", keyPath );
	if(! keyPath.empty()) {
		fprintf( configFile, "# For debugging:\n" );
		fprintf( configFile, "# ssh -i %s ec2-user@<address>\n", keyPath.c_str() );
	}

	fprintf( configFile, "\n" );

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}

int
GenerateConfigFile::rollback() {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );

	// This functor does nothing (to the service), so don't undo anything.

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}
<commit_msg>(#6633)  Newly-generated SSH keys will have region-specific names.<commit_after>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"

#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"

int
GenerateConfigFile::operator() () {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );

	std::map< std::string, std::string > mapping;
	mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
	mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
	mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
	mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
	mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
	mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
	mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
	mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";

	// Append the annex configuration to the user config file.
	FILE * configFile = NULL;

	// Consider using createUserConfigDir() from user-config-dir.h.
	std::string userConfigName;
	MyString userConfigSource;
	param( userConfigName, "USER_CONFIG_FILE" );
	if(! userConfigName.empty()) {
		find_user_file( userConfigSource, userConfigName.c_str(), false );
		if(! userConfigSource.empty()) {
			// Create the containing directory if necessary, and only the
			// containing directory -- don't do anything stupid if the
			// user configuration directory is misconfigured.
			std::string dir, file;
			filename_split( userConfigSource.c_str(), dir, file );
			if(! IsDirectory( dir.c_str() )) {
				mkdir( dir.c_str(), 0755 );
			}

			configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
				"a", 0644 );
			if( configFile == NULL ) {
				fprintf( stderr, "Failed to open user configuration file '%s': %s (%d).  Printing configuration...\n",
					userConfigSource.c_str(), strerror( errno ), errno );
				configFile = stdout;
			}
		} else {
			fprintf( stderr, "Unable to locate your user configuration file.  Printing configuration...\n" );
			configFile = stdout;
		}
	} else {
		fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files.  Contact your system administrator.  Printing configuration...\n" );
		configFile = stdout;
	}

	char * safeRegion = NULL;
	if( region != NULL ) {
		safeRegion = strdup( region );
		assert( safeRegion != NULL );
		for( unsigned i = 0; i < strlen( region ); ++i ) {
			if( ('a' <= region[i] && region[i] <= 'z') ||
			    ('A' <= region[i] && region[i] <= 'Z') ||
			    ('0' <= region[i] && region[i] <= '9') ||
			    strchr( "_./", region[i] ) != NULL )
			{
				continue;
			} else {
				safeRegion[i] = '_';
			}
		}
	}

	fprintf( configFile, "\n" );
	if( safeRegion ) {
		fprintf( configFile, "# Generated by condor-annex -setup for region %s.\n", safeRegion );
	} else {
		fprintf( configFile, "# Generated by condor_annex -setup.\n" );
	}

	std::string value;
	for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
		value.clear();
		scratchpad->LookupString( i->first.c_str(), value );
		if(! value.empty()) {
			fprintf( configFile, "%s%s%s = %s\n",
				safeRegion ? safeRegion : "",
				safeRegion ? "." : "",
				i->second.c_str(), value.c_str() );
		}
	}

	std::string keyPath;
	scratchpad->LookupString( "KeyPath", keyPath );
	if(! keyPath.empty()) {
		std::string newKeyPath = keyPath;
		size_t idx = keyPath.rfind( ".pem" );
		if( idx != std::string::npos ) {
			newKeyPath.insert( idx, region );
			newKeyPath.insert( idx, "." );
			rename( keyPath.c_str(), newKeyPath.c_str() );
		}

		fprintf( configFile, "# For debugging:\n" );
		fprintf( configFile, "# ssh -i %s ec2-user@<address>\n", newKeyPath.c_str() );
	}

	fprintf( configFile, "\n" );

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}

int
GenerateConfigFile::rollback() {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );

	// This functor does nothing (to the service), so don't undo anything.

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}
<|endoftext|>


<commit_before>//===-- MachineCodeForInstruction.cpp -------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Representation of the sequence of machine instructions created for a single
// VM instruction.  Additionally records information about hidden and implicit
// values used by the machine instructions: about hidden values used by the
// machine instructions:
//
// "Temporary values" are intermediate values used in the machine instruction
// sequence, but not in the VM instruction Note that such values should be
// treated as pure SSA values with no interpretation of their operands (i.e., as
// a TmpInstruction object which actually represents such a value).
//
// (2) "Implicit uses" are values used in the VM instruction but not in the
//     machine instruction sequence
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrAnnot.h"
#include "llvm/Instruction.h"
using namespace llvm;

MachineCodeForInstruction &MachineCodeForInstruction::get(const Instruction *I){
  return *(MachineCodeForInstruction*)I->getOrCreateAnnotation(MCFI_AID);
}
void MachineCodeForInstruction::destroy(const Instruction *I) {
  I->deleteAnnotation(MCFI_AID);
}

AnnotationID llvm::MCFI_AID(
             AnnotationManager::getID("CodeGen::MachineCodeForInstruction"));

static Annotation *CreateMCFI(AnnotationID AID, const Annotable *, void *) {
  assert(AID == MCFI_AID);
  return new MachineCodeForInstruction();  // Invoke constructor!
}

// Register the annotation with the annotation factory
static struct MCFIInitializer {
  MCFIInitializer() {
    AnnotationManager::registerAnnotationFactory(MCFI_AID, &CreateMCFI);
  }
} RegisterCreateMCFI;

void
MachineCodeForInstruction::dropAllReferences()
{
  for (unsigned i=0, N=tempVec.size(); i < N; i++)
    cast<Instruction>(tempVec[i])->dropAllReferences();
}

MachineCodeForInstruction::~MachineCodeForInstruction() {
  // Let go of all uses in temp. instructions
  dropAllReferences();

  // Free the Value objects created to hold intermediate values
  for (unsigned i=0, N=tempVec.size(); i < N; i++)
    delete tempVec[i];

  // do not free the MachineInstr objects allocated. they are managed
  // by the ilist in MachineBasicBlock

  // Free the CallArgsDescriptor if it exists.
  delete callArgsDesc;
}
<commit_msg>Urg, forgot to check this in.<commit_after>//===-- MachineCodeForInstruction.cpp -------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Representation of the sequence of machine instructions created for a single
// VM instruction.  Additionally records information about hidden and implicit
// values used by the machine instructions: about hidden values used by the
// machine instructions:
//
// "Temporary values" are intermediate values used in the machine instruction
// sequence, but not in the VM instruction Note that such values should be
// treated as pure SSA values with no interpretation of their operands (i.e., as
// a TmpInstruction object which actually represents such a value).
//
// (2) "Implicit uses" are values used in the VM instruction but not in the
//     machine instruction sequence
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Instruction.h"
using namespace llvm;

MachineCodeForInstruction &MachineCodeForInstruction::get(const Instruction *I){
  return *(MachineCodeForInstruction*)I->getOrCreateAnnotation(MCFI_AID);
}
void MachineCodeForInstruction::destroy(const Instruction *I) {
  I->deleteAnnotation(MCFI_AID);
}

AnnotationID llvm::MCFI_AID(
             AnnotationManager::getID("CodeGen::MachineCodeForInstruction"));

static Annotation *CreateMCFI(AnnotationID AID, const Annotable *, void *) {
  assert(AID == MCFI_AID);
  return new MachineCodeForInstruction();  // Invoke constructor!
}

// Register the annotation with the annotation factory
static struct MCFIInitializer {
  MCFIInitializer() {
    AnnotationManager::registerAnnotationFactory(MCFI_AID, &CreateMCFI);
  }
} RegisterCreateMCFI;

void
MachineCodeForInstruction::dropAllReferences()
{
  for (unsigned i=0, N=tempVec.size(); i < N; i++)
    cast<Instruction>(tempVec[i])->dropAllReferences();
}

MachineCodeForInstruction::~MachineCodeForInstruction() {
  // Let go of all uses in temp. instructions
  dropAllReferences();

  // Free the Value objects created to hold intermediate values
  for (unsigned i=0, N=tempVec.size(); i < N; i++)
    delete tempVec[i];

  // do not free the MachineInstr objects allocated. they are managed
  // by the ilist in MachineBasicBlock

  // Free the CallArgsDescriptor if it exists.
  delete callArgsDesc;
}
<|endoftext|>


<commit_before>#include "common/common/utility.h"

#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iterator>
#include <string>

#include "envoy/common/exception.h"

#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/common/hash.h"

#include "absl/strings/ascii.h"
#include "absl/strings/internal/memutil.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "spdlog/spdlog.h"

namespace Envoy {
std::string DateFormatter::fromTime(const SystemTime& time) {
  return fromTimeT(std::chrono::system_clock::to_time_t(time));
}

std::string DateFormatter::fromTimeT(time_t time) {
  tm current_tm;
  gmtime_r(&time, &current_tm);

  std::array<char, 1024> buf;
  strftime(&buf[0], buf.size(), format_string_.c_str(), &current_tm);
  return std::string(&buf[0]);
}

std::string DateFormatter::now() {
  time_t current_time_t;
  time(&current_time_t);
  return fromTimeT(current_time_t);
}

ProdSystemTimeSource ProdSystemTimeSource::instance_;
ProdMonotonicTimeSource ProdMonotonicTimeSource::instance_;

ConstMemoryStreamBuffer::ConstMemoryStreamBuffer(const char* data, size_t size) {
  // std::streambuf won't modify `data`, but the interface still requires a char* for convenience,
  // so we need to const_cast.
  char* ptr = const_cast<char*>(data);

  this->setg(ptr, ptr, ptr + size);
}

InputConstMemoryStream::InputConstMemoryStream(const char* data, size_t size)
    : ConstMemoryStreamBuffer{data, size}, std::istream{static_cast<std::streambuf*>(this)} {}

bool DateUtil::timePointValid(SystemTime time_point) {
  return std::chrono::duration_cast<std::chrono::milliseconds>(time_point.time_since_epoch())
             .count() != 0;
}

bool DateUtil::timePointValid(MonotonicTime time_point) {
  return std::chrono::duration_cast<std::chrono::milliseconds>(time_point.time_since_epoch())
             .count() != 0;
}

const char StringUtil::WhitespaceChars[] = " \t\f\v\n\r";

bool StringUtil::atoul(const char* str, uint64_t& out, int base) {
  if (strlen(str) == 0) {
    return false;
  }

  char* end_ptr;
  out = strtoul(str, &end_ptr, base);
  if (*end_ptr != '\0' || (out == ULONG_MAX && errno == ERANGE)) {
    return false;
  } else {
    return true;
  }
}

absl::string_view StringUtil::ltrim(absl::string_view source) {
  const absl::string_view::size_type pos = source.find_first_not_of(WhitespaceChars);
  if (pos != absl::string_view::npos) {
    source.remove_prefix(pos);
  } else {
    source.remove_prefix(source.size());
  }
  return source;
}

absl::string_view StringUtil::rtrim(absl::string_view source) {
  const absl::string_view::size_type pos = source.find_last_not_of(WhitespaceChars);
  if (pos != absl::string_view::npos) {
    source.remove_suffix(source.size() - pos - 1);
  } else {
    source.remove_suffix(source.size());
  }
  return source;
}

absl::string_view StringUtil::trim(absl::string_view source) { return ltrim(rtrim(source)); }

bool StringUtil::findToken(absl::string_view source, absl::string_view delimiters,
                           absl::string_view key_token, bool trim_whitespace) {
  const auto tokens = splitToken(source, delimiters, trim_whitespace);
  if (trim_whitespace) {
    for (const auto token : tokens) {
      if (key_token == trim(token)) {
        return true;
      }
    }
    return false;
  }

  return std::find(tokens.begin(), tokens.end(), key_token) != tokens.end();
}

bool StringUtil::caseFindToken(absl::string_view source, absl::string_view delimiters,
                               absl::string_view key_token, bool trim_whitespace) {
  const auto tokens = splitToken(source, delimiters, trim_whitespace);
  std::function<bool(absl::string_view)> predicate;

  if (trim_whitespace) {
    predicate = [&](absl::string_view token) { return caseCompare(key_token, trim(token)); };
  } else {
    predicate = [&](absl::string_view token) { return caseCompare(key_token, token); };
  }

  return std::find_if(tokens.begin(), tokens.end(), predicate) != tokens.end();
}

bool StringUtil::caseCompare(absl::string_view lhs, absl::string_view rhs) {
  if (rhs.size() != lhs.size()) {
    return false;
  }
  return absl::strings_internal::memcasecmp(rhs.data(), lhs.data(), rhs.size()) == 0;
}

absl::string_view StringUtil::cropRight(absl::string_view source, absl::string_view delimiter) {
  const absl::string_view::size_type pos = source.find(delimiter);
  if (pos != absl::string_view::npos) {
    source.remove_suffix(source.size() - pos);
  }
  return source;
}

absl::string_view StringUtil::cropLeft(absl::string_view source, absl::string_view delimiter) {
  const absl::string_view::size_type pos = source.find(delimiter);
  if (pos != absl::string_view::npos) {
    source.remove_prefix(pos + delimiter.size());
  }
  return source;
}

std::vector<absl::string_view> StringUtil::splitToken(absl::string_view source,
                                                      absl::string_view delimiters,
                                                      bool keep_empty_string) {
  if (keep_empty_string) {
    return absl::StrSplit(source, absl::ByAnyChar(delimiters));
  }
  return absl::StrSplit(source, absl::ByAnyChar(delimiters), absl::SkipEmpty());
}

uint32_t StringUtil::itoa(char* out, size_t buffer_size, uint64_t i) {
  // The maximum size required for an unsigned 64-bit integer is 21 chars (including null).
  if (buffer_size < 21) {
    throw std::invalid_argument("itoa buffer too small");
  }

  char* current = out;
  do {
    *current++ = "0123456789"[i % 10];
    i /= 10;
  } while (i > 0);

  for (uint64_t i = 0, j = current - out - 1; i < j; i++, j--) {
    char c = out[i];
    out[i] = out[j];
    out[j] = c;
  }

  *current = 0;
  return current - out;
}

size_t StringUtil::strlcpy(char* dst, const char* src, size_t size) {
  strncpy(dst, src, size - 1);
  dst[size - 1] = '\0';
  return strlen(src);
}

std::string StringUtil::join(const std::vector<std::string>& source, const std::string& delimiter) {
  std::ostringstream buf;
  std::copy(source.begin(), source.end(),
            std::ostream_iterator<std::string>(buf, delimiter.c_str()));
  std::string ret = buf.str();
  // copy will always end with an extra delimiter, we remove it here.
  return ret.substr(0, ret.length() - delimiter.length());
}

std::string StringUtil::subspan(const std::string& source, size_t start, size_t end) {
  return source.substr(start, end - start);
}

std::string StringUtil::escape(const std::string& source) {
  std::string ret;

  // Prevent unnecessary allocation by allocating 2x original size.
  ret.reserve(source.length() * 2);
  for (char c : source) {
    switch (c) {
    case '\r':
      ret += "\\r";
      break;
    case '\n':
      ret += "\\n";
      break;
    case '\t':
      ret += "\\t";
      break;
    case '"':
      ret += "\\\"";
      break;
    default:
      ret += c;
      break;
    }
  }

  return ret;
}

std::string AccessLogDateTimeFormatter::fromTime(const SystemTime& time) {
  static DateFormatter date_format("%Y-%m-%dT%H:%M:%S");

  return fmt::format(
      "{}.{:03d}Z", date_format.fromTime(time),
      std::chrono::duration_cast<std::chrono::milliseconds>(time.time_since_epoch()).count() %
          1000);
}

bool StringUtil::endsWith(const std::string& source, const std::string& end) {
  if (source.length() < end.length()) {
    return false;
  }

  size_t start_position = source.length() - end.length();
  return std::equal(source.begin() + start_position, source.end(), end.begin());
}

bool StringUtil::startsWith(const char* source, const std::string& start, bool case_sensitive) {
  if (case_sensitive) {
    return strncmp(source, start.c_str(), start.size()) == 0;
  } else {
    return strncasecmp(source, start.c_str(), start.size()) == 0;
  }
}

const std::string& StringUtil::nonEmptyStringOrDefault(const std::string& s,
                                                       const std::string& default_value) {
  return s.empty() ? default_value : s;
}

std::string StringUtil::toUpper(absl::string_view s) {
  std::string upper_s;
  upper_s.reserve(s.size());
  std::transform(s.cbegin(), s.cend(), std::back_inserter(upper_s), absl::ascii_toupper);
  return upper_s;
}

bool StringUtil::CaseInsensitiveCompare::operator()(absl::string_view lhs,
                                                    absl::string_view rhs) const {
  return StringUtil::caseCompare(lhs, rhs);
}

uint64_t StringUtil::CaseInsensitiveHash::operator()(absl::string_view key) const {
  return HashUtil::djb2CaseInsensitiveHash(key);
}

std::string StringUtil::removeCharacters(const absl::string_view& str,
                                         const IntervalSet<size_t>& remove_characters) {
  std::string ret;
  size_t pos = 0;
  const auto intervals = remove_characters.toVector();
  std::vector<absl::string_view> pieces;
  pieces.reserve(intervals.size());
  for (const auto& interval : intervals) {
    if (interval.first != pos) {
      ASSERT(interval.second <= str.size());
      pieces.push_back(str.substr(pos, interval.first - pos));
    }
    pos = interval.second;
  }
  if (pos != str.size()) {
    pieces.push_back(str.substr(pos));
  }
  return absl::StrJoin(pieces, "");
}

bool Primes::isPrime(uint32_t x) {
  if (x < 4) {
    return true; // eliminates special-casing 2.
  } else if ((x & 1) == 0) {
    return false; // eliminates even numbers >2.
  }

  uint32_t limit = sqrt(x);
  for (uint32_t factor = 3; factor <= limit; factor += 2) {
    if ((x % factor) == 0) {
      return false;
    }
  }
  return true;
}

uint32_t Primes::findPrimeLargerThan(uint32_t x) {
  x += (x % 2) + 1;
  while (!isPrime(x)) {
    x += 2;
  }
  return x;
}

std::regex RegexUtil::parseRegex(const std::string& regex, std::regex::flag_type flags) {
  // TODO(zuercher): In the future, PGV (https://github.com/lyft/protoc-gen-validate) annotations
  // may allow us to remove this in favor of direct validation of regular expressions.
  try {
    return std::regex(regex, flags);
  } catch (const std::regex_error& e) {
    throw EnvoyException(fmt::format("Invalid regex '{}': {}", regex, e.what()));
  }
}

// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
void WelfordStandardDeviation::update(double newValue) {
  ++count_;
  const double delta = newValue - mean_;
  mean_ += delta / count_;
  const double delta2 = newValue - mean_;
  m2_ += delta * delta2;
}

double WelfordStandardDeviation::computeVariance() const {
  if (count_ < 2) {
    return std::nan("");
  }
  return m2_ / (count_ - 1);
}

double WelfordStandardDeviation::computeStandardDeviation() const {
  const double variance = computeVariance();
  // It seems very difficult for variance to go negative, but from the calculation in update()
  // above, I can't quite convince myself it's impossible, so put in a guard to be sure.
  return (std::isnan(variance) || variance < 0) ? std::nan("") : sqrt(variance);
}

} // namespace Envoy
<commit_msg>utility: remove absl::strings_internal::memcasecmp usage (#2700) (#2702)<commit_after>#include "common/common/utility.h"

#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iterator>
#include <string>

#include "envoy/common/exception.h"

#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/common/hash.h"

#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "spdlog/spdlog.h"

namespace Envoy {
std::string DateFormatter::fromTime(const SystemTime& time) {
  return fromTimeT(std::chrono::system_clock::to_time_t(time));
}

std::string DateFormatter::fromTimeT(time_t time) {
  tm current_tm;
  gmtime_r(&time, &current_tm);

  std::array<char, 1024> buf;
  strftime(&buf[0], buf.size(), format_string_.c_str(), &current_tm);
  return std::string(&buf[0]);
}

std::string DateFormatter::now() {
  time_t current_time_t;
  time(&current_time_t);
  return fromTimeT(current_time_t);
}

ProdSystemTimeSource ProdSystemTimeSource::instance_;
ProdMonotonicTimeSource ProdMonotonicTimeSource::instance_;

ConstMemoryStreamBuffer::ConstMemoryStreamBuffer(const char* data, size_t size) {
  // std::streambuf won't modify `data`, but the interface still requires a char* for convenience,
  // so we need to const_cast.
  char* ptr = const_cast<char*>(data);

  this->setg(ptr, ptr, ptr + size);
}

InputConstMemoryStream::InputConstMemoryStream(const char* data, size_t size)
    : ConstMemoryStreamBuffer{data, size}, std::istream{static_cast<std::streambuf*>(this)} {}

bool DateUtil::timePointValid(SystemTime time_point) {
  return std::chrono::duration_cast<std::chrono::milliseconds>(time_point.time_since_epoch())
             .count() != 0;
}

bool DateUtil::timePointValid(MonotonicTime time_point) {
  return std::chrono::duration_cast<std::chrono::milliseconds>(time_point.time_since_epoch())
             .count() != 0;
}

const char StringUtil::WhitespaceChars[] = " \t\f\v\n\r";

bool StringUtil::atoul(const char* str, uint64_t& out, int base) {
  if (strlen(str) == 0) {
    return false;
  }

  char* end_ptr;
  out = strtoul(str, &end_ptr, base);
  if (*end_ptr != '\0' || (out == ULONG_MAX && errno == ERANGE)) {
    return false;
  } else {
    return true;
  }
}

absl::string_view StringUtil::ltrim(absl::string_view source) {
  const absl::string_view::size_type pos = source.find_first_not_of(WhitespaceChars);
  if (pos != absl::string_view::npos) {
    source.remove_prefix(pos);
  } else {
    source.remove_prefix(source.size());
  }
  return source;
}

absl::string_view StringUtil::rtrim(absl::string_view source) {
  const absl::string_view::size_type pos = source.find_last_not_of(WhitespaceChars);
  if (pos != absl::string_view::npos) {
    source.remove_suffix(source.size() - pos - 1);
  } else {
    source.remove_suffix(source.size());
  }
  return source;
}

absl::string_view StringUtil::trim(absl::string_view source) { return ltrim(rtrim(source)); }

bool StringUtil::findToken(absl::string_view source, absl::string_view delimiters,
                           absl::string_view key_token, bool trim_whitespace) {
  const auto tokens = splitToken(source, delimiters, trim_whitespace);
  if (trim_whitespace) {
    for (const auto token : tokens) {
      if (key_token == trim(token)) {
        return true;
      }
    }
    return false;
  }

  return std::find(tokens.begin(), tokens.end(), key_token) != tokens.end();
}

bool StringUtil::caseFindToken(absl::string_view source, absl::string_view delimiters,
                               absl::string_view key_token, bool trim_whitespace) {
  const auto tokens = splitToken(source, delimiters, trim_whitespace);
  std::function<bool(absl::string_view)> predicate;

  if (trim_whitespace) {
    predicate = [&](absl::string_view token) { return caseCompare(key_token, trim(token)); };
  } else {
    predicate = [&](absl::string_view token) { return caseCompare(key_token, token); };
  }

  return std::find_if(tokens.begin(), tokens.end(), predicate) != tokens.end();
}

bool StringUtil::caseCompare(absl::string_view lhs, absl::string_view rhs) {
  if (rhs.size() != lhs.size()) {
    return false;
  }
  return absl::StartsWithIgnoreCase(rhs, lhs);
}

absl::string_view StringUtil::cropRight(absl::string_view source, absl::string_view delimiter) {
  const absl::string_view::size_type pos = source.find(delimiter);
  if (pos != absl::string_view::npos) {
    source.remove_suffix(source.size() - pos);
  }
  return source;
}

absl::string_view StringUtil::cropLeft(absl::string_view source, absl::string_view delimiter) {
  const absl::string_view::size_type pos = source.find(delimiter);
  if (pos != absl::string_view::npos) {
    source.remove_prefix(pos + delimiter.size());
  }
  return source;
}

std::vector<absl::string_view> StringUtil::splitToken(absl::string_view source,
                                                      absl::string_view delimiters,
                                                      bool keep_empty_string) {
  if (keep_empty_string) {
    return absl::StrSplit(source, absl::ByAnyChar(delimiters));
  }
  return absl::StrSplit(source, absl::ByAnyChar(delimiters), absl::SkipEmpty());
}

uint32_t StringUtil::itoa(char* out, size_t buffer_size, uint64_t i) {
  // The maximum size required for an unsigned 64-bit integer is 21 chars (including null).
  if (buffer_size < 21) {
    throw std::invalid_argument("itoa buffer too small");
  }

  char* current = out;
  do {
    *current++ = "0123456789"[i % 10];
    i /= 10;
  } while (i > 0);

  for (uint64_t i = 0, j = current - out - 1; i < j; i++, j--) {
    char c = out[i];
    out[i] = out[j];
    out[j] = c;
  }

  *current = 0;
  return current - out;
}

size_t StringUtil::strlcpy(char* dst, const char* src, size_t size) {
  strncpy(dst, src, size - 1);
  dst[size - 1] = '\0';
  return strlen(src);
}

std::string StringUtil::join(const std::vector<std::string>& source, const std::string& delimiter) {
  std::ostringstream buf;
  std::copy(source.begin(), source.end(),
            std::ostream_iterator<std::string>(buf, delimiter.c_str()));
  std::string ret = buf.str();
  // copy will always end with an extra delimiter, we remove it here.
  return ret.substr(0, ret.length() - delimiter.length());
}

std::string StringUtil::subspan(const std::string& source, size_t start, size_t end) {
  return source.substr(start, end - start);
}

std::string StringUtil::escape(const std::string& source) {
  std::string ret;

  // Prevent unnecessary allocation by allocating 2x original size.
  ret.reserve(source.length() * 2);
  for (char c : source) {
    switch (c) {
    case '\r':
      ret += "\\r";
      break;
    case '\n':
      ret += "\\n";
      break;
    case '\t':
      ret += "\\t";
      break;
    case '"':
      ret += "\\\"";
      break;
    default:
      ret += c;
      break;
    }
  }

  return ret;
}

std::string AccessLogDateTimeFormatter::fromTime(const SystemTime& time) {
  static DateFormatter date_format("%Y-%m-%dT%H:%M:%S");

  return fmt::format(
      "{}.{:03d}Z", date_format.fromTime(time),
      std::chrono::duration_cast<std::chrono::milliseconds>(time.time_since_epoch()).count() %
          1000);
}

bool StringUtil::endsWith(const std::string& source, const std::string& end) {
  if (source.length() < end.length()) {
    return false;
  }

  size_t start_position = source.length() - end.length();
  return std::equal(source.begin() + start_position, source.end(), end.begin());
}

bool StringUtil::startsWith(const char* source, const std::string& start, bool case_sensitive) {
  if (case_sensitive) {
    return strncmp(source, start.c_str(), start.size()) == 0;
  } else {
    return strncasecmp(source, start.c_str(), start.size()) == 0;
  }
}

const std::string& StringUtil::nonEmptyStringOrDefault(const std::string& s,
                                                       const std::string& default_value) {
  return s.empty() ? default_value : s;
}

std::string StringUtil::toUpper(absl::string_view s) {
  std::string upper_s;
  upper_s.reserve(s.size());
  std::transform(s.cbegin(), s.cend(), std::back_inserter(upper_s), absl::ascii_toupper);
  return upper_s;
}

bool StringUtil::CaseInsensitiveCompare::operator()(absl::string_view lhs,
                                                    absl::string_view rhs) const {
  return StringUtil::caseCompare(lhs, rhs);
}

uint64_t StringUtil::CaseInsensitiveHash::operator()(absl::string_view key) const {
  return HashUtil::djb2CaseInsensitiveHash(key);
}

std::string StringUtil::removeCharacters(const absl::string_view& str,
                                         const IntervalSet<size_t>& remove_characters) {
  std::string ret;
  size_t pos = 0;
  const auto intervals = remove_characters.toVector();
  std::vector<absl::string_view> pieces;
  pieces.reserve(intervals.size());
  for (const auto& interval : intervals) {
    if (interval.first != pos) {
      ASSERT(interval.second <= str.size());
      pieces.push_back(str.substr(pos, interval.first - pos));
    }
    pos = interval.second;
  }
  if (pos != str.size()) {
    pieces.push_back(str.substr(pos));
  }
  return absl::StrJoin(pieces, "");
}

bool Primes::isPrime(uint32_t x) {
  if (x < 4) {
    return true; // eliminates special-casing 2.
  } else if ((x & 1) == 0) {
    return false; // eliminates even numbers >2.
  }

  uint32_t limit = sqrt(x);
  for (uint32_t factor = 3; factor <= limit; factor += 2) {
    if ((x % factor) == 0) {
      return false;
    }
  }
  return true;
}

uint32_t Primes::findPrimeLargerThan(uint32_t x) {
  x += (x % 2) + 1;
  while (!isPrime(x)) {
    x += 2;
  }
  return x;
}

std::regex RegexUtil::parseRegex(const std::string& regex, std::regex::flag_type flags) {
  // TODO(zuercher): In the future, PGV (https://github.com/lyft/protoc-gen-validate) annotations
  // may allow us to remove this in favor of direct validation of regular expressions.
  try {
    return std::regex(regex, flags);
  } catch (const std::regex_error& e) {
    throw EnvoyException(fmt::format("Invalid regex '{}': {}", regex, e.what()));
  }
}

// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
void WelfordStandardDeviation::update(double newValue) {
  ++count_;
  const double delta = newValue - mean_;
  mean_ += delta / count_;
  const double delta2 = newValue - mean_;
  m2_ += delta * delta2;
}

double WelfordStandardDeviation::computeVariance() const {
  if (count_ < 2) {
    return std::nan("");
  }
  return m2_ / (count_ - 1);
}

double WelfordStandardDeviation::computeStandardDeviation() const {
  const double variance = computeVariance();
  // It seems very difficult for variance to go negative, but from the calculation in update()
  // above, I can't quite convince myself it's impossible, so put in a guard to be sure.
  return (std::isnan(variance) || variance < 0) ? std::nan("") : sqrt(variance);
}

} // namespace Envoy
<|endoftext|>


<commit_before>#ifndef EPA_PLACEMENT_SET_H_
#define EPA_PLACEMENT_SET_H_

#include "Placement.hpp"

class Placement_Set {
public:
  typedef Placement                                        value_type;
  typedef typename std::vector<Placement>::iterator        iterator;
  typedef typename std::vector<Placement>::const_iterator  const_iterator;

  Placement_Set();
  Placement_Set(const unsigned int size);
  ~Placement_Set();

  // member access
  inline Placement& back() {return placements_.back();};
  inline unsigned int size() {return placements_.size();};
  // TODO shoudl pass in variadic fashion
  inline void emplace_back(const unsigned int size, const Sequence& s) {placements_.emplace_back(size, s);};

  //Iterator Compatability
  inline iterator begin() {return placements_.begin();};
  inline iterator end() {return placements_.end();};
  inline const_iterator begin() const {return placements_.cbegin();};
  inline const_iterator end() const {return placements_.cend();};
  inline const_iterator cbegin() {return placements_.cbegin();};
  inline const_iterator cend() {return placements_.cend();};

private:
  std::vector<Placement> placements_;
};

#endif
<commit_msg>made emplace_back variadic<commit_after>#ifndef EPA_PLACEMENT_SET_H_
#define EPA_PLACEMENT_SET_H_

#include "Placement.hpp"

#include <utility>

class Placement_Set {
public:
  typedef Placement                                        value_type;
  typedef typename std::vector<Placement>::iterator        iterator;
  typedef typename std::vector<Placement>::const_iterator  const_iterator;

  Placement_Set();
  Placement_Set(const unsigned int size);
  ~Placement_Set();

  // member access
  inline Placement& back() {return placements_.back();};
  inline unsigned int size() {return placements_.size();};

  // needs to be in the header
  template<typename ...Args> void emplace_back(Args && ...args)
  {
    placements_.emplace_back(std::forward<Args>(args)...);
  };

  // Iterator Compatability
  inline iterator begin() {return placements_.begin();};
  inline iterator end() {return placements_.end();};
  inline const_iterator begin() const {return placements_.cbegin();};
  inline const_iterator end() const {return placements_.cend();};
  inline const_iterator cbegin() {return placements_.cbegin();};
  inline const_iterator cend() {return placements_.cend();};

private:
  std::vector<Placement> placements_;
};

#endif
<|endoftext|>


<commit_before>#include "synctool.h"
#include <dirent.h>
#include <unistd.h>
#include <utime.h>

bool isLink(string path)
{
	struct stat st;
	return (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFLNK;
}

/* Write with colorized output */
void setColor(string color)
{
	if (gUseColors)
		cout << color;
}

/* File operations */
void createDirectory(string dir)
{
	if (isDirectory(dir))
		return;

	logMessage("MK " + dir, GREEN);
	if (mkdir(dir.c_str(), 0775) == -1)
		die(EXIT_FAILURE, "Error: Could not create directory " + dir);
}

void removeFile(string file)
{
	if (!isFile(file) || !isLink(file))
		return;

	logMessage("RM " + file, RED);
	if(remove(file.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not delete " + file);
}

void copyFile(string src, string dst)
{
	if (!filesDiffer(src, dst))
		return;

	if (isFile(dst) || isLink(dst))
		removeFile(dst);

	logMessage("CP " + src + " -> " + dst, BLUE);

	ifstream fin(src.c_str(), ios::binary);
	ofstream fout(dst.c_str(), ios::binary);

	if (!(fin.is_open() && fout.is_open()))
		die(EXIT_FAILURE, "Error: Could not copy " + src);

	fout << fin.rdbuf();

	fin.close();
	fout.close();

	struct stat st;

	if (stat(src.c_str(), &st) != -1)
	{
		struct utimbuf buf;

		buf.actime = st.st_atime;
		buf.modtime = st.st_mtime;

		utime(dst.c_str(), &buf);

		/* also copy file permissions */
		chmod(dst.c_str(), st.st_mode);
	}
}

void copyLink(string src, string dst)
{
	int r;
	char *target;

	int size = 1024;
	struct stat st;

	if (isFile(dst) || isLink(dst))
		removeFile(dst);

	if ((r = lstat(src.c_str(), &st)) != -1)
	{
		size = st.st_size;
	}

	target = new char[size+1];
	memset(target, 0, size + 1);

	if (readlink(src.c_str(), target, size) == -1)
		die(EXIT_FAILURE, "Error: Could not read link " + src);

	target[size] = '\0';
	logMessage("LN " + dst + " -> " + target, BLUE);

	if (symlink(target, dst.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not create link " + dst);

	delete target;

	if (r != -1)
	{
		struct utimbuf buf;

		buf.actime = st.st_atime;
		buf.modtime = st.st_mtime;

		utime(dst.c_str(), &buf);
	}
}

void removeDirectory(string dir)
{
	if (!isDirectory(dir))
		return;

	DIR *d = opendir(dir.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string path = dir + '/' + ent->d_name;

		if (isDirectory(path))
			removeDirectory(path);
		else
			removeFile(path);
	}

	closedir(d);

	logMessage("RM " + dir, RED);
	if (rmdir(dir.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not delete " + dir);
}

void assertCanOpenDirectory(string dir)
{
	DIR *d = opendir(dir.c_str());
	if (d == NULL)
		die(EXIT_FAILURE, "Error: Cannot access " + dir);

	closedir(d);
}

void copyAllFiles(string src, string dst)
{
	DIR *d = opendir(src.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(srcPath) && !isDirectory(dstPath))
		{
			if (isFile(dstPath) || isLink(dstPath))
				removeFile(dstPath);

			createDirectory(dstPath);
			copyAllFiles(srcPath, dstPath);
		}
		else if (isDirectory(srcPath) && isDirectory(dstPath)
			copyAllFiles(srcPath, dstPath);
		else if (isFile(srcPath))
			copyFile(srcPath, dstPath);
		else if (isLink(srcPath))
			copyLink(srcPath, dstPath);
	}

	closedir(d);
}

void copyNewAndUpdatedFiles(string src, string dst)
{
	DIR *d = opendir(src.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(srcPath) && !isDirectory(dstPath))
		{
			if (isFile(dstPath) || isLink(dstPath))
				logMessage("Warning: " + srcPath + " is a directory, but " + dstPath + " is not.");
			else
			{
				createDirectory(dstPath);
				copyNewAndUpdatedFiles(srcPath, dstPath);
			}
		}
		else if (isDirectory(srcPath) && isDirectory(dstPath))
			copyNewAndUpdatedFiles(srcPath, dstPath);
		else if ((isFile(srcPath) || isLink(srcPath)) && isDirectory(dstPath))
			logMessage("Warning: " + srcPath + " is not a directory, but " + dstPath + " is.");
		else if (isFile(srcPath) && (!isFile(dstPath) || isNewer(srcPath, dstPath)))
			copyFile(srcPath, dstPath);
		else if (isLink(srcPath) && (!isLink(dstPath) || isNewer(srcPath, dstPath)))
			copyLink(srcPath, dstPath);
	}

	closedir(d);
}

void removeMissing(string src, string dst)
{
	DIR *d = opendir(dst.c_str());
	struct dirent *ent;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(dstPath) && !isDirectory(srcPath))
			removeDirectory(dstPath);
		else if (isFile(dstPath) && !isFile(srcPath))
			removeFile(dstPath);
		else if (isLink(dstPath) && !isLink(srcPath))
			removeFile(dstPath);
		else if (isDirectory(dstPath) && isDirectory(srcPath))
			removeMissing(srcPath, dstPath);

	}

	closedir(d);
}
<commit_msg>Fixed missing )<commit_after>#include "synctool.h"
#include <dirent.h>
#include <unistd.h>
#include <utime.h>

bool isLink(string path)
{
	struct stat st;
	return (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFLNK;
}

/* Write with colorized output */
void setColor(string color)
{
	if (gUseColors)
		cout << color;
}

/* File operations */
void createDirectory(string dir)
{
	if (isDirectory(dir))
		return;

	logMessage("MK " + dir, GREEN);
	if (mkdir(dir.c_str(), 0775) == -1)
		die(EXIT_FAILURE, "Error: Could not create directory " + dir);
}

void removeFile(string file)
{
	if (!isFile(file) || !isLink(file))
		return;

	logMessage("RM " + file, RED);
	if(remove(file.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not delete " + file);
}

void copyFile(string src, string dst)
{
	if (!filesDiffer(src, dst))
		return;

	if (isFile(dst) || isLink(dst))
		removeFile(dst);

	logMessage("CP " + src + " -> " + dst, BLUE);

	ifstream fin(src.c_str(), ios::binary);
	ofstream fout(dst.c_str(), ios::binary);

	if (!(fin.is_open() && fout.is_open()))
		die(EXIT_FAILURE, "Error: Could not copy " + src);

	fout << fin.rdbuf();

	fin.close();
	fout.close();

	struct stat st;

	if (stat(src.c_str(), &st) != -1)
	{
		struct utimbuf buf;

		buf.actime = st.st_atime;
		buf.modtime = st.st_mtime;

		utime(dst.c_str(), &buf);

		/* also copy file permissions */
		chmod(dst.c_str(), st.st_mode);
	}
}

void copyLink(string src, string dst)
{
	int r;
	char *target;

	int size = 1024;
	struct stat st;

	if (isFile(dst) || isLink(dst))
		removeFile(dst);

	if ((r = lstat(src.c_str(), &st)) != -1)
	{
		size = st.st_size;
	}

	target = new char[size+1];
	memset(target, 0, size + 1);

	if (readlink(src.c_str(), target, size) == -1)
		die(EXIT_FAILURE, "Error: Could not read link " + src);

	target[size] = '\0';
	logMessage("LN " + dst + " -> " + target, BLUE);

	if (symlink(target, dst.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not create link " + dst);

	delete target;

	if (r != -1)
	{
		struct utimbuf buf;

		buf.actime = st.st_atime;
		buf.modtime = st.st_mtime;

		utime(dst.c_str(), &buf);
	}
}

void removeDirectory(string dir)
{
	if (!isDirectory(dir))
		return;

	DIR *d = opendir(dir.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string path = dir + '/' + ent->d_name;

		if (isDirectory(path))
			removeDirectory(path);
		else
			removeFile(path);
	}

	closedir(d);

	logMessage("RM " + dir, RED);
	if (rmdir(dir.c_str()) == -1)
		die(EXIT_FAILURE, "Error: Could not delete " + dir);
}

void assertCanOpenDirectory(string dir)
{
	DIR *d = opendir(dir.c_str());
	if (d == NULL)
		die(EXIT_FAILURE, "Error: Cannot access " + dir);

	closedir(d);
}

void copyAllFiles(string src, string dst)
{
	DIR *d = opendir(src.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(srcPath) && !isDirectory(dstPath))
		{
			if (isFile(dstPath) || isLink(dstPath))
				removeFile(dstPath);

			createDirectory(dstPath);
			copyAllFiles(srcPath, dstPath);
		}
		else if (isDirectory(srcPath) && isDirectory(dstPath))
			copyAllFiles(srcPath, dstPath);
		else if (isFile(srcPath))
			copyFile(srcPath, dstPath);
		else if (isLink(srcPath))
			copyLink(srcPath, dstPath);
	}

	closedir(d);
}

void copyNewAndUpdatedFiles(string src, string dst)
{
	DIR *d = opendir(src.c_str());
	struct dirent *ent = NULL;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(srcPath) && !isDirectory(dstPath))
		{
			if (isFile(dstPath) || isLink(dstPath))
				logMessage("Warning: " + srcPath + " is a directory, but " + dstPath + " is not.");
			else
			{
				createDirectory(dstPath);
				copyNewAndUpdatedFiles(srcPath, dstPath);
			}
		}
		else if (isDirectory(srcPath) && isDirectory(dstPath))
			copyNewAndUpdatedFiles(srcPath, dstPath);
		else if ((isFile(srcPath) || isLink(srcPath)) && isDirectory(dstPath))
			logMessage("Warning: " + srcPath + " is not a directory, but " + dstPath + " is.");
		else if (isFile(srcPath) && (!isFile(dstPath) || isNewer(srcPath, dstPath)))
			copyFile(srcPath, dstPath);
		else if (isLink(srcPath) && (!isLink(dstPath) || isNewer(srcPath, dstPath)))
			copyLink(srcPath, dstPath);
	}

	closedir(d);
}

void removeMissing(string src, string dst)
{
	DIR *d = opendir(dst.c_str());
	struct dirent *ent;

	while ((ent = readdir(d)))
	{
		if (string(ent->d_name) == "." || string(ent->d_name) == "..")
			continue;

		string srcPath = src + '/' + ent->d_name;
		string dstPath = dst + '/' + ent->d_name;

		if (isDirectory(dstPath) && !isDirectory(srcPath))
			removeDirectory(dstPath);
		else if (isFile(dstPath) && !isFile(srcPath))
			removeFile(dstPath);
		else if (isLink(dstPath) && !isLink(srcPath))
			removeFile(dstPath);
		else if (isDirectory(dstPath) && isDirectory(srcPath))
			removeMissing(srcPath, dstPath);

	}

	closedir(d);
}
<|endoftext|>


<commit_before>
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/planner/aggregate_node.h"

#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "utils/syscache.h"

namespace peloton {
namespace bridge {

planner::AbstractPlanNode*
PlanTransformer::TransformAgg(const AggState *plan_state){
  const AggState* agg_state = plan_state;

  LOG_INFO("Number of Agg nodes: %d \n", agg_state->numaggs);
  LOG_INFO("Number of Agg phases: %d \n", agg_state->numphases);

  int aggno = 0;

//  ListCell   *l;
//  foreach(l, agg_state->aggs)
//  {
//    AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(l);
//    Aggref *aggref = (Aggref *) aggrefstate->xprstate.expr;
//
//    auto aggTuple = SearchSysCache1(AGGFNOID,
//                                    ObjectIdGetDatum(aggref->aggfnoid));
//
//    auto aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
//
//    auto pg_func_oid = aggform->aggtransfn;
//
//    ReleaseSysCache(aggTuple);
//
//    LOG_INFO("Aggno : %d , PG_Func_Oid = %u \n", ++aggno, pg_func_oid);
//
//  }

  return nullptr;
}

}
}
<commit_msg>fix compilation<commit_after>
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/planner/aggregate_node.h"

#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "utils/syscache.h"

namespace peloton {
namespace bridge {

planner::AbstractPlanNode*
PlanTransformer::TransformAgg(const AggState *plan_state){
  const AggState* agg_state = plan_state;

  LOG_INFO("Number of Agg nodes: %d \n", agg_state->numaggs);
  LOG_INFO("Number of Agg phases: %d \n", agg_state->numphases);

//  int aggno = 0;

//  ListCell   *l;
//  foreach(l, agg_state->aggs)
//  {
//    AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(l);
//    Aggref *aggref = (Aggref *) aggrefstate->xprstate.expr;
//
//    auto aggTuple = SearchSysCache1(AGGFNOID,
//                                    ObjectIdGetDatum(aggref->aggfnoid));
//
//    auto aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
//
//    auto pg_func_oid = aggform->aggtransfn;
//
//    ReleaseSysCache(aggTuple);
//
//    LOG_INFO("Aggno : %d , PG_Func_Oid = %u \n", ++aggno, pg_func_oid);
//
//  }

  return nullptr;
}

}
}
<|endoftext|>