<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 "v8-line-editor.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

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class V8LineEditor
// -----------------------------------------------------------------------------

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8Shell
/// @{
////////////////////////////////////////////////////////////////////////////////

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

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

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

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) {
          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;
  }
}

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

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;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if javascript is missing a closing bracket
////////////////////////////////////////////////////////////////////////////////

static bool CheckJavaScript (string const& source) {
  char const* ptr;
  char const* end;
  int openParen;
  int openBrackets;
  int openBraces;

  enum {
    NORMAL,             // start
    NORMAL_1,           // from NORMAL: seen a single /
    DOUBLE_QUOTE,       // from NORMAL: seen a single "
    DOUBLE_QUOTE_ESC,   // from DOUBLE_QUOTE: seen a backslash
    SINGLE_QUOTE,       // from NORMAL: seen a single '
    SINGLE_QUOTE_ESC,   // from SINGLE_QUOTE: seen a backslash
    MULTI_COMMENT,      // from NORMAL_1: seen a *
    MULTI_COMMENT_1,    // from MULTI_COMMENT, seen a *
    SINGLE_COMMENT      // from NORMAL_1; seen a /
  }
  state;

  openParen = 0;
  openBrackets = 0;
  openBraces = 0;

  ptr = source.c_str();
  end = ptr + source.length();
  state = NORMAL;

  while (ptr < end) {
    if (state == DOUBLE_QUOTE) {
      if (*ptr == '\\') {
        state = DOUBLE_QUOTE_ESC;
      }
      else if (*ptr == '"') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == DOUBLE_QUOTE_ESC) {
      state = DOUBLE_QUOTE;
      ptr++;
    }
    else if (state == SINGLE_QUOTE) {
      if (*ptr == '\\') {
        state = SINGLE_QUOTE_ESC;
      }
      else if (*ptr == '\'') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_QUOTE_ESC) {
      state = SINGLE_QUOTE;
      ptr++;
    }
    else if (state == MULTI_COMMENT) {
      if (*ptr == '*') {
        state = MULTI_COMMENT_1;
      }

      ++ptr;
    }
    else if (state == MULTI_COMMENT_1) {
      if (*ptr == '/') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_COMMENT) {
      ++ptr;

      if (ptr == end) {
        state = NORMAL;
      }
    }
    else if (state == NORMAL_1) {
      switch (*ptr) {
        case '/':
          state = SINGLE_COMMENT;
          ++ptr;
          break;

        case '*':
          state = MULTI_COMMENT;
          ++ptr;
          break;

        default:
          state = NORMAL; // try again, do not change ptr
          break;
      }
    }
    else {
      switch (*ptr) {
        case '"':
          state = DOUBLE_QUOTE;
          break;

        case '\'':
          state = SINGLE_QUOTE;
          break;

        case '/':
          state = NORMAL_1;
          break;

        case '(':
          ++openParen;
          break;

        case ')':
          --openParen;
          break;

        case '[':
          ++openBrackets;
          break;

        case ']':
          --openBrackets;
          break;

        case '{':
          ++openBraces;
          break;

        case '}':
          --openBraces;
          break;
      }

      ++ptr;
    }
  }

  return openParen <= 0 && openBrackets <= 0 && openBraces <= 0;
}

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, string const& history)
  : _current(), _historyFilename(history), _context(context) {
}

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

bool V8LineEditor::open (const bool autoComplete) {
  rl_initialize();

  if (autoComplete) {
    rl_attempted_completion_function = AttemptedCompletion;
    rl_completer_word_break_characters = WordBreakCharacters;

    rl_bind_key('\t', rl_complete);
  }

  using_history();
  stifle_history(MAX_HISTORY_ENTRIES);

  return read_history(getHistoryPath().c_str()) == 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor shutdown
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::close () {
  bool result = write_history(getHistoryPath().c_str());

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the history file path
////////////////////////////////////////////////////////////////////////////////

string V8LineEditor::getHistoryPath () {
  string path;

  if (getenv("HOME")) {
    path.append(getenv("HOME"));
    path += '/';
  }

  path.append(_historyFilename);

  return path;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor prompt
////////////////////////////////////////////////////////////////////////////////

char* V8LineEditor::prompt (char const* prompt) {
  string dotdot;
  char const* p = prompt;
  size_t len1 = strlen(prompt);
  size_t len2 = len1;

  if (len1 < 3) {
    dotdot = "> ";
    len2 = 2;
  }
  else {
    dotdot = string(len1 - 2, '.') + "> ";
  }

  char const* sep = "";
  char* originalLine = 0;

  while (true) {
    char* result = readline(p);
    originalLine = result;
    p = dotdot.c_str();

    if (result == 0) {
      // give up, if the user pressed control-D on the top-most level
      if (_current.empty()) {
        return 0;
      }

      // otherwise clear current content
      _current.clear();
      break;
    }

    _current += sep;
    sep = "\n";

    bool c1 = strncmp(result, prompt, len1) == 0;
    bool c2 = strncmp(result, dotdot.c_str(), len2) == 0;

    while (c1 || c2) {
      if (c1) {
        result += len1;
      }
      else if (c2) {
        result += len2;
      }

      c1 = strncmp(result, prompt, len1) == 0;
      c2 = strncmp(result, dotdot.c_str(), len2) == 0;
    }

    _current += result;
    bool ok = CheckJavaScript(_current);

    if (ok) {
      break;
    }
    TRI_Free(originalLine);
  }

  char* line = TRI_DuplicateString(_current.c_str());
  _current.clear();

  // avoid memleaks
  if (originalLine != 0) {
    TRI_Free(originalLine);
  }

  return line;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief add to history
////////////////////////////////////////////////////////////////////////////////

void V8LineEditor::addHistory (char const* str) {
  if (*str == '\0') {
    return;
  }

  history_set_pos(history_length-1);

  if (current_history()) {
    do {
      if (strcmp(current_history()->line, str) == 0) {
        remove_history(where_history());
        break;
      }
    }
    while (previous_history());
  }

  add_history(str);
}

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

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>MacOS old readline<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 "v8-line-editor.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

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class V8LineEditor
// -----------------------------------------------------------------------------

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8Shell
/// @{
////////////////////////////////////////////////////////////////////////////////

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

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

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

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) {
          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;
  }
}

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

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;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if javascript is missing a closing bracket
////////////////////////////////////////////////////////////////////////////////

static bool CheckJavaScript (string const& source) {
  char const* ptr;
  char const* end;
  int openParen;
  int openBrackets;
  int openBraces;

  enum {
    NORMAL,             // start
    NORMAL_1,           // from NORMAL: seen a single /
    DOUBLE_QUOTE,       // from NORMAL: seen a single "
    DOUBLE_QUOTE_ESC,   // from DOUBLE_QUOTE: seen a backslash
    SINGLE_QUOTE,       // from NORMAL: seen a single '
    SINGLE_QUOTE_ESC,   // from SINGLE_QUOTE: seen a backslash
    MULTI_COMMENT,      // from NORMAL_1: seen a *
    MULTI_COMMENT_1,    // from MULTI_COMMENT, seen a *
    SINGLE_COMMENT      // from NORMAL_1; seen a /
  }
  state;

  openParen = 0;
  openBrackets = 0;
  openBraces = 0;

  ptr = source.c_str();
  end = ptr + source.length();
  state = NORMAL;

  while (ptr < end) {
    if (state == DOUBLE_QUOTE) {
      if (*ptr == '\\') {
        state = DOUBLE_QUOTE_ESC;
      }
      else if (*ptr == '"') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == DOUBLE_QUOTE_ESC) {
      state = DOUBLE_QUOTE;
      ptr++;
    }
    else if (state == SINGLE_QUOTE) {
      if (*ptr == '\\') {
        state = SINGLE_QUOTE_ESC;
      }
      else if (*ptr == '\'') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_QUOTE_ESC) {
      state = SINGLE_QUOTE;
      ptr++;
    }
    else if (state == MULTI_COMMENT) {
      if (*ptr == '*') {
        state = MULTI_COMMENT_1;
      }

      ++ptr;
    }
    else if (state == MULTI_COMMENT_1) {
      if (*ptr == '/') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_COMMENT) {
      ++ptr;

      if (ptr == end) {
        state = NORMAL;
      }
    }
    else if (state == NORMAL_1) {
      switch (*ptr) {
        case '/':
          state = SINGLE_COMMENT;
          ++ptr;
          break;

        case '*':
          state = MULTI_COMMENT;
          ++ptr;
          break;

        default:
          state = NORMAL; // try again, do not change ptr
          break;
      }
    }
    else {
      switch (*ptr) {
        case '"':
          state = DOUBLE_QUOTE;
          break;

        case '\'':
          state = SINGLE_QUOTE;
          break;

        case '/':
          state = NORMAL_1;
          break;

        case '(':
          ++openParen;
          break;

        case ')':
          --openParen;
          break;

        case '[':
          ++openBrackets;
          break;

        case ']':
          --openBrackets;
          break;

        case '{':
          ++openBraces;
          break;

        case '}':
          --openBraces;
          break;
      }

      ++ptr;
    }
  }

  return openParen <= 0 && openBrackets <= 0 && openBraces <= 0;
}

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, string const& history)
  : _current(), _historyFilename(history), _context(context) {
}

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

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

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

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

bool V8LineEditor::open (const bool autoComplete) {
  rl_initialize();

  if (autoComplete) {
    rl_attempted_completion_function = AttemptedCompletion;
    rl_completer_word_break_characters = WordBreakCharacters;

    rl_bind_key('\t', rl_complete);
  }

  using_history();
  stifle_history(MAX_HISTORY_ENTRIES);

  return read_history(getHistoryPath().c_str()) == 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor shutdown
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::close () {
  bool result = write_history(getHistoryPath().c_str());

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the history file path
////////////////////////////////////////////////////////////////////////////////

string V8LineEditor::getHistoryPath () {
  string path;

  if (getenv("HOME")) {
    path.append(getenv("HOME"));
    path += '/';
  }

  path.append(_historyFilename);

  return path;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor prompt
////////////////////////////////////////////////////////////////////////////////

char* V8LineEditor::prompt (char const* prompt) {
  string dotdot;
  char const* p = prompt;
  size_t len1 = strlen(prompt);
  size_t len2 = len1;

  if (len1 < 3) {
    dotdot = "> ";
    len2 = 2;
  }
  else {
    dotdot = string(len1 - 2, '.') + "> ";
  }

  char const* sep = "";
  char* originalLine = 0;

  while (true) {
    char* result = readline(p);
    originalLine = result;
    p = dotdot.c_str();

    if (result == 0) {
      // give up, if the user pressed control-D on the top-most level
      if (_current.empty()) {
        return 0;
      }

      // otherwise clear current content
      _current.clear();
      break;
    }

    _current += sep;
    sep = "\n";

    bool c1 = strncmp(result, prompt, len1) == 0;
    bool c2 = strncmp(result, dotdot.c_str(), len2) == 0;

    while (c1 || c2) {
      if (c1) {
        result += len1;
      }
      else if (c2) {
        result += len2;
      }

      c1 = strncmp(result, prompt, len1) == 0;
      c2 = strncmp(result, dotdot.c_str(), len2) == 0;
    }

    _current += result;
    bool ok = CheckJavaScript(_current);

    if (ok) {
      break;
    }
    TRI_Free(originalLine);
  }

  char* line = TRI_DuplicateString(_current.c_str());
  _current.clear();

  // avoid memleaks
  if (originalLine != 0) {
    TRI_Free(originalLine);
  }

  return line;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief add to history
////////////////////////////////////////////////////////////////////////////////

void V8LineEditor::addHistory (char const* str) {
  if (*str == '\0') {
    return;
  }

  history_set_pos(history_length-1);

  if (current_history()) {
    do {
      if (strcmp(current_history()->line, str) == 0) {
        remove_history(where_history());
        break;
      }
    }
    while (previous_history());
  }

  add_history(str);
}

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

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


<commit_before>#ifndef __STAN__GM__COMMAND_HPP__
#define __STAN__GM__COMMAND_HPP__

#include <cmath>
#include <cstddef>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <stan/io/cmd_line.hpp>
#include <stan/io/dump.hpp>
#include <stan/mcmc/adaptive_sampler.hpp>
#include <stan/mcmc/adaptive_hmc.hpp>
#include <stan/mcmc/hmc.hpp>
#include <stan/mcmc/nuts.hpp>
#include <stan/model/prob_grad_ad.hpp>
#include <stan/model/prob_grad.hpp>
#include <stan/mcmc/sampler.hpp>

namespace stan {

  namespace gm {

    void print_help_2(const std::string& key_val,
                      const std::string& msg,
                      const std::string& note = "") {
      stan::io::pad_help_option(key_val);
      std::cout << msg
                << std::endl;
      if (note.size() > 0) {
        stan::io::pad_help_option("");
        std::cout << "    (" << note << ")"
                  << std::endl;
      }
      std::cout << std::endl;
    }

    void print_help_option(const std::string& key,
                           const std::string& value_type,
                           const std::string& msg,
                           const std::string& note = "") {
      std::stringstream ss;
      ss << "--" << key;
      if (value_type.size() > 0)
        ss << "=<" << value_type << ">";
      print_help_2(ss.str(),msg,note);
    }

    void print_nuts_help(std::string cmd) {
      using stan::io::pad_help_option;

      std::cout << std::endl;
      std::cout << "Compiled Stan Graphical Model Command" << std::endl;
      std::cout << std::endl;

      std::cout << "USAGE:  " << cmd << " [options]" << std::endl;
      std::cout << std::endl;

      std::cout << "OPTIONS:" << std::endl;
      std::cout << std::endl;

      print_help_option("help","",
                        "Display this information");

      print_help_option("data","file",
                        "Read data from specified dump-format file",
                        "required if model declares data");

      print_help_option("init","file",
                        "Use initial values from specified file or zero values if <file>=0",
                        "default is random initialization");

      print_help_option("samples","file",
                        "File into which samples are written.",
                        "default = samples.csv");

      print_help_option("append_samples","",
                        "Append samples to existing file if it exists");

      print_help_option("seed","int",
                        "Random number generation seed",
                        "default = randomly generated from time");

      print_help_option("chain_id","int",
                        "Markov chain identifier",
                        "default = 1");

      print_help_option("iter","+int",
                        "Total number of iterations, including warmup",
                        "default = 2000");

      print_help_option("warmup","+int",
                        "Discard the specified number of initial samples",
                        "default = iter / 2");

      print_help_option("thin","+int",
                        "Period between saved samples after warm up",
                        "default = max(1, floor(iter - warmup) / 1000)");

      print_help_option("refresh","+int"
                        "Period between samples updating progress report print",
                        "default = max(1,iter/200))");

      print_help_option("leapfrog_steps","int",
                        "Number of leapfrog steps; -1 for No-U-Turn adaptation",
                        "default = -1");

      print_help_option("epsilon","float",
                        "Initial value for step size, or -1 to set automatically",
                        "default = -1");

      print_help_option("epsilon_pm","[0,1]",
                        "Sample epsilon +/- epsilon * epsilon_pm",
                        "default = 0.0");

      print_help_option("epsilon_adapt_off","",
                        "Turn off step size adaptation (default is on)");

      print_help_option("delta","+float",
                        "Initial parameter for NUTS step-size tuning.",
                        "default = 0.5");

      print_help_option("gamma","+float",
                        "Gamma parameter for dual averaging step-size adaptation.",
                        "default = 0.05");

      print_help_option("test_grad","",
                        "Test gradient calculations using finite differences");

      std::cout << std::endl;
    }

    bool do_print(int refresh) {
      return refresh > 0;
    }

    bool do_print(int n, int refresh) {
      return do_print(refresh)
        && ((n + 1) % refresh == 0);
    }

    template <typename T_model>
    void sample_from(stan::mcmc::adaptive_sampler& sampler,
                     bool epsilon_adapt,
                     int refresh,
                     int num_iterations,
                     int num_warmup,
                     int num_thin,
                     std::ostream& sample_file_stream,
                     std::vector<double>& params_r,
                     std::vector<int>& params_i,
                     T_model& model) {

      int it_print_width = std::ceil(std::log10(num_iterations));
      std::cout << std::endl;

      if (epsilon_adapt)
        sampler.adapt_on();
      for (int m = 0; m < num_iterations; ++m) {
        if (do_print(m,refresh)) {
          std::cout << "\rIteration: ";
          std::cout << std::setw(it_print_width) << (m + 1)
                    << " / " << num_iterations;
          std::cout << " [" << std::setw(3)
                    << static_cast<int>((100.0 * (m + 1))/num_iterations)
                    << "%] ";
          std::cout << ((m < num_warmup) ? " (Adapting)" : " (Sampling)");
          std::cout.flush();
        }
        if (m < num_warmup) {
          sampler.next(); // discard
        } else {
          if (epsilon_adapt)
            sampler.adapt_off();
          if (((m - num_warmup) % num_thin) != 0) {
            sampler.next();
            continue;
          } else {
            stan::mcmc::sample sample = sampler.next();

            // FIXME: use csv_writer arg to make comma optional?
            sample_file_stream << sample.log_prob() << ',';
            sample.params_r(params_r);
            sample.params_i(params_i);
            model.write_csv(params_r,params_i,sample_file_stream);
          }
        }
      }
    }

    template <typename T_model>
    int nuts_command(int argc, const char* argv[]) {

      stan::io::cmd_line command(argc,argv);

      if (command.has_flag("help")) {
        print_nuts_help(argv[0]);
        return 0;
      }

      std::string data_file;
      command.val("data",data_file);
      std::fstream data_stream(data_file.c_str(),
                               std::fstream::in);
      stan::io::dump data_var_context(data_stream);
      data_stream.close();

      T_model model(data_var_context);

      std::string sample_file = "samples.csv";
      command.val("samples",sample_file);

      unsigned int num_iterations = 2000U;
      command.val("iter",num_iterations);

      unsigned int num_warmup = num_iterations / 2;
      command.val("warmup",num_warmup);

      unsigned int calculated_thin = (num_iterations - num_warmup) / 1000U;
      unsigned int num_thin = (calculated_thin > 1) ? calculated_thin : 1U;
      command.val("thin",num_thin);

      int leapfrog_steps = -1;
      command.val("leapfrog_steps",leapfrog_steps);

      double epsilon = -1.0;
      command.val("epsilon",epsilon);

      double epsilon_pm = 0.0;
      command.val("epsilon_pm",epsilon_pm);

      bool epsilon_adapt_off = command.has_flag("epsilon_adapt_off");
      bool epsilon_adapt = !epsilon_adapt_off;

      double delta = 0.5;
      command.val("delta", delta);

      double gamma = 0.05;
      command.val("gamma", gamma);

      int refresh = 1;
      command.val("refresh",refresh);

      int random_seed = 0;
      if (command.has_key("seed")) {
        bool well_formed = command.val("seed",random_seed);
        if (!well_formed) {
          std::string seed_val;
          command.val("seed",seed_val);
          std::cerr << "value for seed must be integer"
                    << "; found value=" << seed_val << std::endl;
          return -1;
        }
      } else {
        random_seed = std::time(0);
      }

      int chain_id = 1;
      if (command.has_key("chain_id")) {
        bool well_formed = command.val("chain_id",chain_id);
        if (!well_formed || chain_id < 0) {
          std::string chain_id_val;
          command.val("chain_id",chain_id_val);
          std::cerr << "value for chain_id must be positive integer"
                    << "; found chain_id=" << chain_id_val
                    << std::endl;
          return -1;
        }
      }

      // FASTER, but no parallel guarantees
      // typedef boost::mt19937 rng_t;
      // rng_t base_rng(static_cast<unsigned int>(random_seed + chain_id - 1);

      typedef boost::ecuyer1988 rng_t;
      rng_t base_rng(random_seed);
      // (2**50 = 1T samples, 1000 chains)
      static long unsigned int DISCARD_STRIDE = (1UL << 50);
      base_rng.discard(DISCARD_STRIDE * (chain_id - 1));

      std::vector<int> params_i;
      std::vector<double> params_r;

      std::string init_val;
      // parameter initialization
      if (command.has_key("init")) {
        command.val("init",init_val);
        if (init_val == "0") {
          params_i = std::vector<int>(model.num_params_i(),0);
          params_r = std::vector<double>(model.num_params_r(),0.0);
        } else {
          std::cout << "init file=" << init_val << std::endl;

          std::fstream init_stream(init_val.c_str(),std::fstream::in);
          stan::io::dump init_var_context(init_stream);
          init_stream.close();
          model.transform_inits(init_var_context,params_i,params_r);
        }
      } else {
        init_val = "random initialization";
        // init_rng generates uniformly from -2 to 2
        boost::random::uniform_real_distribution<double>
          init_range_distribution(-2.0,2.0);
        boost::variate_generator<rng_t&,
                       boost::random::uniform_real_distribution<double> >
          init_rng(base_rng,init_range_distribution);

        params_i = std::vector<int>(model.num_params_i(),0);
        params_r = std::vector<double>(model.num_params_r());
        for (size_t i = 0; i < params_r.size(); ++i)
          params_r[i] = init_rng();
      }

      bool append_samples = command.has_flag("append_samples");
      std::ios_base::openmode samples_append_mode
        = append_samples
        ? (std::fstream::out | std::fstream::app)
        : std::fstream::out;

      std::cout << "STAN SAMPLING COMMAND" << std::endl;
      std::cout << "data = " << data_file << std::endl;
      std::cout << "init = " << init_val << std::endl;
      std::cout << "samples = " << sample_file << std::endl;
      std::cout << "append_samples = " << append_samples << std::endl;

      std::cout << "seed = " << random_seed
                << " (" << (command.has_key("seed")
                            ? "user specified"
                            : "randomly generated") << ")"
                << std::endl;
      std::cout << "chain_id=" << chain_id
                << " (" << (command.has_key("seed")
                            ? "user specified"
                            : "randomly generated") << ")"
                << std::endl;

      std::cout << "iter = " << num_iterations << std::endl;
      std::cout << "warmup = " << num_warmup << std::endl;
      std::cout << "thin = " << num_thin << std::endl;

      std::cout << "leapfrog steps = " << leapfrog_steps << std::endl;
      std::cout << "epsilon = " << epsilon << std::endl;;
      std::cout << "epsilon_pm = " << epsilon_pm << std::endl;;
      std::cout << "epsilon_adapt_off = " << epsilon_adapt_off << std::endl;;
      std::cout << "delta = " << delta << std::endl;
      std::cout << "gamma = " << gamma << std::endl;

      if (command.has_flag("test_grad")) {
        std::cout << std::endl << "TEST GRADIENT MODE" << std::endl;
        model.test_gradients(params_r,params_i);
        return 0;
      }

      std::fstream sample_file_stream(sample_file.c_str(),
                                      samples_append_mode);

      sample_file_stream << "lp__,"; // log probability first
      model.write_csv_header(sample_file_stream);

      if (leapfrog_steps < 0) {
        stan::mcmc::nuts<rng_t> nuts_sampler(model,
                                             epsilon, epsilon_pm, epsilon_adapt,
                                             delta, gamma,
                                             base_rng);
        sample_from(nuts_sampler,epsilon_adapt,refresh,
                    num_iterations,num_warmup,num_thin,
                    sample_file_stream,params_r,params_i,
                    model);
      } else {
        stan::mcmc::adaptive_hmc<rng_t> hmc_sampler(model,
                                                    leapfrog_steps,
                                                    epsilon, epsilon_pm, epsilon_adapt,
                                                    delta, gamma,
                                                    base_rng);
        sample_from(hmc_sampler,epsilon_adapt,refresh,
                    num_iterations,num_warmup,num_thin,
                    sample_file_stream,params_r,params_i,
                    model);
      }

      sample_file_stream.close();
      std::cout << std::endl << std::endl;
      return 0;
    }

  } // namespace prob

} // namespace stan

#endif
<commit_msg>fixed command so header is not written in append mode<commit_after>#ifndef __STAN__GM__COMMAND_HPP__
#define __STAN__GM__COMMAND_HPP__

#include <cmath>
#include <cstddef>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <stan/io/cmd_line.hpp>
#include <stan/io/dump.hpp>
#include <stan/mcmc/adaptive_sampler.hpp>
#include <stan/mcmc/adaptive_hmc.hpp>
#include <stan/mcmc/hmc.hpp>
#include <stan/mcmc/nuts.hpp>
#include <stan/model/prob_grad_ad.hpp>
#include <stan/model/prob_grad.hpp>
#include <stan/mcmc/sampler.hpp>

namespace stan {

  namespace gm {

    void print_help_2(const std::string& key_val,
                      const std::string& msg,
                      const std::string& note = "") {
      stan::io::pad_help_option(key_val);
      std::cout << msg
                << std::endl;
      if (note.size() > 0) {
        stan::io::pad_help_option("");
        std::cout << "    (" << note << ")"
                  << std::endl;
      }
      std::cout << std::endl;
    }

    void print_help_option(const std::string& key,
                           const std::string& value_type,
                           const std::string& msg,
                           const std::string& note = "") {
      std::stringstream ss;
      ss << "--" << key;
      if (value_type.size() > 0)
        ss << "=<" << value_type << ">";
      print_help_2(ss.str(),msg,note);
    }

    void print_nuts_help(std::string cmd) {
      using stan::io::pad_help_option;

      std::cout << std::endl;
      std::cout << "Compiled Stan Graphical Model Command" << std::endl;
      std::cout << std::endl;

      std::cout << "USAGE:  " << cmd << " [options]" << std::endl;
      std::cout << std::endl;

      std::cout << "OPTIONS:" << std::endl;
      std::cout << std::endl;

      print_help_option("help","",
                        "Display this information");

      print_help_option("data","file",
                        "Read data from specified dump-format file",
                        "required if model declares data");

      print_help_option("init","file",
                        "Use initial values from specified file or zero values if <file>=0",
                        "default is random initialization");

      print_help_option("samples","file",
                        "File into which samples are written",
                        "default = samples.csv");

      print_help_option("append_samples","",
                        "Append samples to existing file if it exists",
                        "does not write header in append mode");

      print_help_option("seed","int",
                        "Random number generation seed",
                        "default = randomly generated from time");

      print_help_option("chain_id","int",
                        "Markov chain identifier",
                        "default = 1");

      print_help_option("iter","+int",
                        "Total number of iterations, including warmup",
                        "default = 2000");

      print_help_option("warmup","+int",
                        "Discard the specified number of initial samples",
                        "default = iter / 2");

      print_help_option("thin","+int",
                        "Period between saved samples after warm up",
                        "default = max(1, floor(iter - warmup) / 1000)");

      print_help_option("refresh","+int"
                        "Period between samples updating progress report print",
                        "default = max(1,iter/200))");

      print_help_option("leapfrog_steps","int",
                        "Number of leapfrog steps; -1 for No-U-Turn adaptation",
                        "default = -1");

      print_help_option("epsilon","float",
                        "Initial value for step size, or -1 to set automatically",
                        "default = -1");

      print_help_option("epsilon_pm","[0,1]",
                        "Sample epsilon +/- epsilon * epsilon_pm",
                        "default = 0.0");

      print_help_option("epsilon_adapt_off","",
                        "Turn off step size adaptation (default is on)");

      print_help_option("delta","+float",
                        "Initial parameter for NUTS step-size tuning.",
                        "default = 0.5");

      print_help_option("gamma","+float",
                        "Gamma parameter for dual averaging step-size adaptation.",
                        "default = 0.05");

      print_help_option("test_grad","",
                        "Test gradient calculations using finite differences");

      std::cout << std::endl;
    }

    bool do_print(int refresh) {
      return refresh > 0;
    }

    bool do_print(int n, int refresh) {
      return do_print(refresh)
        && ((n + 1) % refresh == 0);
    }

    template <typename T_model>
    void sample_from(stan::mcmc::adaptive_sampler& sampler,
                     bool epsilon_adapt,
                     int refresh,
                     int num_iterations,
                     int num_warmup,
                     int num_thin,
                     std::ostream& sample_file_stream,
                     std::vector<double>& params_r,
                     std::vector<int>& params_i,
                     T_model& model) {

      int it_print_width = std::ceil(std::log10(num_iterations));
      std::cout << std::endl;

      if (epsilon_adapt)
        sampler.adapt_on();
      for (int m = 0; m < num_iterations; ++m) {
        if (do_print(m,refresh)) {
          std::cout << "\rIteration: ";
          std::cout << std::setw(it_print_width) << (m + 1)
                    << " / " << num_iterations;
          std::cout << " [" << std::setw(3)
                    << static_cast<int>((100.0 * (m + 1))/num_iterations)
                    << "%] ";
          std::cout << ((m < num_warmup) ? " (Adapting)" : " (Sampling)");
          std::cout.flush();
        }
        if (m < num_warmup) {
          sampler.next(); // discard
        } else {
          if (epsilon_adapt)
            sampler.adapt_off();
          if (((m - num_warmup) % num_thin) != 0) {
            sampler.next();
            continue;
          } else {
            stan::mcmc::sample sample = sampler.next();

            // FIXME: use csv_writer arg to make comma optional?
            sample_file_stream << sample.log_prob() << ',';
            sample.params_r(params_r);
            sample.params_i(params_i);
            model.write_csv(params_r,params_i,sample_file_stream);
          }
        }
      }
    }

    template <typename T_model>
    int nuts_command(int argc, const char* argv[]) {

      stan::io::cmd_line command(argc,argv);

      if (command.has_flag("help")) {
        print_nuts_help(argv[0]);
        return 0;
      }

      std::string data_file;
      command.val("data",data_file);
      std::fstream data_stream(data_file.c_str(),
                               std::fstream::in);
      stan::io::dump data_var_context(data_stream);
      data_stream.close();

      T_model model(data_var_context);

      std::string sample_file = "samples.csv";
      command.val("samples",sample_file);

      unsigned int num_iterations = 2000U;
      command.val("iter",num_iterations);

      unsigned int num_warmup = num_iterations / 2;
      command.val("warmup",num_warmup);

      unsigned int calculated_thin = (num_iterations - num_warmup) / 1000U;
      unsigned int num_thin = (calculated_thin > 1) ? calculated_thin : 1U;
      command.val("thin",num_thin);

      int leapfrog_steps = -1;
      command.val("leapfrog_steps",leapfrog_steps);

      double epsilon = -1.0;
      command.val("epsilon",epsilon);

      double epsilon_pm = 0.0;
      command.val("epsilon_pm",epsilon_pm);

      bool epsilon_adapt_off = command.has_flag("epsilon_adapt_off");
      bool epsilon_adapt = !epsilon_adapt_off;

      double delta = 0.5;
      command.val("delta", delta);

      double gamma = 0.05;
      command.val("gamma", gamma);

      int refresh = 1;
      command.val("refresh",refresh);

      int random_seed = 0;
      if (command.has_key("seed")) {
        bool well_formed = command.val("seed",random_seed);
        if (!well_formed) {
          std::string seed_val;
          command.val("seed",seed_val);
          std::cerr << "value for seed must be integer"
                    << "; found value=" << seed_val << std::endl;
          return -1;
        }
      } else {
        random_seed = std::time(0);
      }

      int chain_id = 1;
      if (command.has_key("chain_id")) {
        bool well_formed = command.val("chain_id",chain_id);
        if (!well_formed || chain_id < 0) {
          std::string chain_id_val;
          command.val("chain_id",chain_id_val);
          std::cerr << "value for chain_id must be positive integer"
                    << "; found chain_id=" << chain_id_val
                    << std::endl;
          return -1;
        }
      }

      // FASTER, but no parallel guarantees:
      // typedef boost::mt19937 rng_t;
      // rng_t base_rng(static_cast<unsigned int>(random_seed + chain_id - 1);

      typedef boost::ecuyer1988 rng_t;
      rng_t base_rng(random_seed);
      // (2**50 = 1T samples, 1000 chains)
      static long unsigned int DISCARD_STRIDE = (1UL << 50);
      base_rng.discard(DISCARD_STRIDE * (chain_id - 1));

      std::vector<int> params_i;
      std::vector<double> params_r;

      std::string init_val;
      // parameter initialization
      if (command.has_key("init")) {
        command.val("init",init_val);
        if (init_val == "0") {
          params_i = std::vector<int>(model.num_params_i(),0);
          params_r = std::vector<double>(model.num_params_r(),0.0);
        } else {
          std::cout << "init file=" << init_val << std::endl;

          std::fstream init_stream(init_val.c_str(),std::fstream::in);
          stan::io::dump init_var_context(init_stream);
          init_stream.close();
          model.transform_inits(init_var_context,params_i,params_r);
        }
      } else {
        init_val = "random initialization";
        // init_rng generates uniformly from -2 to 2
        boost::random::uniform_real_distribution<double>
          init_range_distribution(-2.0,2.0);
        boost::variate_generator<rng_t&,
                       boost::random::uniform_real_distribution<double> >
          init_rng(base_rng,init_range_distribution);

        params_i = std::vector<int>(model.num_params_i(),0);
        params_r = std::vector<double>(model.num_params_r());
        for (size_t i = 0; i < params_r.size(); ++i)
          params_r[i] = init_rng();
      }

      bool append_samples = command.has_flag("append_samples");
      std::ios_base::openmode samples_append_mode
        = append_samples
        ? (std::fstream::out | std::fstream::app)
        : std::fstream::out;

      std::cout << "STAN SAMPLING COMMAND" << std::endl;
      std::cout << "data = " << data_file << std::endl;
      std::cout << "init = " << init_val << std::endl;
      std::cout << "samples = " << sample_file << std::endl;
      std::cout << "append_samples = " << append_samples << std::endl;

      std::cout << "seed = " << random_seed
                << " (" << (command.has_key("seed")
                            ? "user specified"
                            : "randomly generated") << ")"
                << std::endl;
      std::cout << "chain_id=" << chain_id
                << " (" << (command.has_key("seed")
                            ? "user specified"
                            : "randomly generated") << ")"
                << std::endl;

      std::cout << "iter = " << num_iterations << std::endl;
      std::cout << "warmup = " << num_warmup << std::endl;
      std::cout << "thin = " << num_thin << std::endl;

      std::cout << "leapfrog steps = " << leapfrog_steps << std::endl;
      std::cout << "epsilon = " << epsilon << std::endl;;
      std::cout << "epsilon_pm = " << epsilon_pm << std::endl;;
      std::cout << "epsilon_adapt_off = " << epsilon_adapt_off << std::endl;;
      std::cout << "delta = " << delta << std::endl;
      std::cout << "gamma = " << gamma << std::endl;

      if (command.has_flag("test_grad")) {
        std::cout << std::endl << "TEST GRADIENT MODE" << std::endl;
        model.test_gradients(params_r,params_i);
        return 0;
      }

      std::fstream sample_file_stream(sample_file.c_str(),
                                      samples_append_mode);

      if (!append_samples) {
        sample_file_stream << "lp__,"; // log probability first
        model.write_csv_header(sample_file_stream);
      }

      if (leapfrog_steps < 0) {
        stan::mcmc::nuts<rng_t> nuts_sampler(model,
                                             epsilon, epsilon_pm, epsilon_adapt,
                                             delta, gamma,
                                             base_rng);
        sample_from(nuts_sampler,epsilon_adapt,refresh,
                    num_iterations,num_warmup,num_thin,
                    sample_file_stream,params_r,params_i,
                    model);
      } else {
        stan::mcmc::adaptive_hmc<rng_t> hmc_sampler(model,
                                                    leapfrog_steps,
                                                    epsilon, epsilon_pm, epsilon_adapt,
                                                    delta, gamma,
                                                    base_rng);
        sample_from(hmc_sampler,epsilon_adapt,refresh,
                    num_iterations,num_warmup,num_thin,
                    sample_file_stream,params_r,params_i,
                    model);
      }

      sample_file_stream.close();
      std::cout << std::endl << std::endl;
      return 0;
    }

  } // namespace prob

} // namespace stan

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 12:07:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#if defined( WIN ) || defined( WNT )
#define HWND    void*
#define HMENU   void*
typedef void*               HDC;
    // was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ModuleRes(FT_DESCRIPTION))
     ,m_aDatasource         (this, ModuleRes(LB_DATASOURCE))
     ,m_aOk                 (this, ModuleRes(PB_OK))
     ,m_aCancel             (this, ModuleRes(PB_CANCEL))
     ,m_aHelp               (this, ModuleRes(PB_HELP))
#ifdef HAVE_ODBC_ADMINISTRATION
     ,m_aManageDatasources  (this, ModuleRes(PB_MANAGE))
#endif
     ,m_aCreateAdabasDB     (this, ModuleRes(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ModuleRes(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ModuleRes(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (size_t i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);
#ifdef HAVE_ODBC_ADMINISTRATION
    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }
#endif
    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
ODatasourceSelectDialog::~ODatasourceSelectDialog()
{
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, /*pButton*/ )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntryPos(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                    {
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                        m_pOutputSet->Put(SfxBoolItem(DSID_PASSWORDREQUIRED, TRUE));
                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}

// -----------------------------------------------------------------------
BOOL ODatasourceSelectDialog::Close()
{
#ifdef HAVE_ODBC_ADMINISTRATION
    if ( m_pODBCManagement.get() && m_pODBCManagement->isRunning() )
        return FALSE;
#endif

    return ModalDialog::Close();
}

// -----------------------------------------------------------------------
#ifdef HAVE_ODBC_ADMINISTRATION
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, EMPTYARG )
{
    if ( !m_pODBCManagement.get() )
        m_pODBCManagement.reset( new OOdbcManagement( LINK( this, ODatasourceSelectDialog, ManageProcessFinished ) ) );

    if ( !m_pODBCManagement->manageDataSources_async() )
    {
        // TODO: error message
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
    }

    m_aDatasource.Disable();
    m_aOk.Disable();
    m_aCancel.Disable();
    m_aManageDatasources.Disable();

    OSL_POSTCOND( m_pODBCManagement->isRunning(), "ODatasourceSelectDialog::ManageClickHdl: success, but not running - you were *fast*!" );
    return 0L;
}

IMPL_LINK( ODatasourceSelectDialog, ManageProcessFinished, void*, /**/ )
{
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames( aOdbcDatasources );
    fillListBox( aOdbcDatasources );

    m_aDatasource.Enable();
    m_aOk.Enable();
    m_aCancel.Enable();
    m_aManageDatasources.Enable();

    return 0L;
}

#endif
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    ::rtl::OUString sSelected;
    if (m_aDatasource.GetEntryCount())
         sSelected = m_aDatasource.GetSelectEntry();
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    if (m_aDatasource.GetEntryCount())
    {
        if (sSelected.getLength())
            m_aDatasource.SelectEntry(sSelected);
        else        // select the first entry
            m_aDatasource.SelectEntryPos(0);
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS macosxquicktime01 (1.21.52); FILE MERGED 2007/10/26 11:09:53 pl 1.21.52.1: #i82621# fixed a copy/paset error<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: vg $ $Date: 2007-12-07 11:47:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ModuleRes(FT_DESCRIPTION))
     ,m_aDatasource         (this, ModuleRes(LB_DATASOURCE))
     ,m_aOk                 (this, ModuleRes(PB_OK))
     ,m_aCancel             (this, ModuleRes(PB_CANCEL))
     ,m_aHelp               (this, ModuleRes(PB_HELP))
#ifdef HAVE_ODBC_ADMINISTRATION
     ,m_aManageDatasources  (this, ModuleRes(PB_MANAGE))
#endif
     ,m_aCreateAdabasDB     (this, ModuleRes(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ModuleRes(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ModuleRes(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (size_t i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);
#ifdef HAVE_ODBC_ADMINISTRATION
    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }
#endif
    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
ODatasourceSelectDialog::~ODatasourceSelectDialog()
{
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, /*pButton*/ )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntryPos(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                    {
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                        m_pOutputSet->Put(SfxBoolItem(DSID_PASSWORDREQUIRED, TRUE));
                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}

// -----------------------------------------------------------------------
BOOL ODatasourceSelectDialog::Close()
{
#ifdef HAVE_ODBC_ADMINISTRATION
    if ( m_pODBCManagement.get() && m_pODBCManagement->isRunning() )
        return FALSE;
#endif

    return ModalDialog::Close();
}

// -----------------------------------------------------------------------
#ifdef HAVE_ODBC_ADMINISTRATION
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, EMPTYARG )
{
    if ( !m_pODBCManagement.get() )
        m_pODBCManagement.reset( new OOdbcManagement( LINK( this, ODatasourceSelectDialog, ManageProcessFinished ) ) );

    if ( !m_pODBCManagement->manageDataSources_async() )
    {
        // TODO: error message
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
    }

    m_aDatasource.Disable();
    m_aOk.Disable();
    m_aCancel.Disable();
    m_aManageDatasources.Disable();

    OSL_POSTCOND( m_pODBCManagement->isRunning(), "ODatasourceSelectDialog::ManageClickHdl: success, but not running - you were *fast*!" );
    return 0L;
}

IMPL_LINK( ODatasourceSelectDialog, ManageProcessFinished, void*, /**/ )
{
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames( aOdbcDatasources );
    fillListBox( aOdbcDatasources );

    m_aDatasource.Enable();
    m_aOk.Enable();
    m_aCancel.Enable();
    m_aManageDatasources.Enable();

    return 0L;
}

#endif
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    ::rtl::OUString sSelected;
    if (m_aDatasource.GetEntryCount())
         sSelected = m_aDatasource.GetSelectEntry();
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    if (m_aDatasource.GetEntryCount())
    {
        if (sSelected.getLength())
            m_aDatasource.SelectEntry(sSelected);
        else        // select the first entry
            m_aDatasource.SelectEntryPos(0);
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>


<commit_before>#include "TreeEvaluator.h"

#include <cmath> // cos

Evaluation eval(Tree * t)
{
	// think this through...

	Enums::SymbolAndValue node = t->getPayload();
	switch (node.symbol)
	{
	case Enums::GrammarSymbol::NUM:
		return Evaluation{ node.ivalue, (float) node.ivalue, true }; // ?

	case Enums::GrammarSymbol::COS:
	}
}
<commit_msg>Started writing the evaluator properly<commit_after>#include "TreeEvaluator.h"

#include <cmath> // cos

Evaluation eval(Tree * t)
{
	Enums::SymbolAndValue node = t->getPayload();
	float farg0, farg1, farg2;
	int iarg0, iarg1, iarg2;
	Evaluation arg0, arg1, arg2;

	switch (node.symbol)
	{

	case Enums::GrammarSymbol::NUM: // LEAF CASE aka RECURSION BASE
		return intEval(node.ivalue);

	case Enums::GrammarSymbol::COS:
		arg0 = eval(t->getChildren()[0]);
		farg0 = arg0.fval;
		return floatEval(cos(farg0));

	case Enums::GrammarSymbol::FAC:
		arg0 = eval(t->getChildren()[0]);
		iarg0 = arg0.ival;
		return intEval(factorial(iarg0));

	case Enums::GrammarSymbol::PLUS:
		arg0 = eval(t->getChildren()[0]);
		arg2 = eval(t->getChildren()[2]);
		if (arg0.itsAnInt)
		{
			iarg0 = arg0.ival;
			iarg2 = arg2.ival;
			return intEval(iarg0 + iarg2);
		}
		else
		{
			farg0 = arg0.fval;
			farg2 = arg2.fval;
			return floatEval(farg0 + farg2);
		}

	case Enums::GrammarSymbol::MUL:
		arg0 = eval(t->getChildren()[0]);
		arg2 = eval(t->getChildren()[2]);
		if (arg0.itsAnInt)
		{
			iarg0 = arg0.ival;
			iarg2 = arg2.ival;
			return intEval(iarg0 * iarg2);
		}
		else
		{
			farg0 = arg0.fval;
			farg2 = arg2.fval;
			return intEval(farg0 * farg2);
		}

	case Enums::GrammarSymbol::MINUS:
		arg0 = eval(t->getChildren()[0]);
		arg2 = eval(t->getChildren()[2]);
		if (arg0.itsAnInt)
		{
			iarg0 = arg0.ival;
			iarg2 = arg2.ival;
			return intEval(iarg0 - iarg2);
		}
		else
		{
			farg0 = arg0.fval;
			farg2 = arg2.fval;
			return intEval(farg0 - farg2);
		}

	case Enums::GrammarSymbol::INT:
		arg0 = eval(t->getChildren()[0]);
		return arg0;

	case Enums::GrammarSymbol::FLOAT:
		//case num.num
		if (t->getChildren()[2]) // ...is not null
		{
			arg0 = eval(t->getChildren()[0]);
			arg2 = eval(t->getChildren()[2]);
			farg0 = arg0.fval;
			farg2 = arg2.fval;
			return floatEval(farg0 + toFraction(farg2));
		}
		//case num.
		else if (t->getChildren()[1]->getPayload().symbol == Enums::GrammarSymbol::DOT)
		{
			arg0 = eval(t->getChildren()[0]);
			farg0 = arg0.fval;
			return floatEval(farg0);
		}
		//case .num
		else
		{
			arg0 = eval(t->getChildren()[0]);
			farg0 = arg0.fval;
			return floatEval(toFraction(farg0));
		}

	// keep going... case Enums::GrammarSymbol::
	}
}

Evaluation floatEval(float f)
{
	return Evaluation{ -69, f, false };
}

Evaluation intEval(int i)
{
	return Evaluation{ i, (float)i, true };
}

int factorial(int i)
{
	int r = 1;
	for (int j = 1; j < i; j++)
		r *= j;
	return r;
}

int toFraction(int t) // takes t and divides it by 10 until it's smaller than 1.
{
	float f = (float)t;
	while (f >= 1.0)
		f /= 10.0;
	return f;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unoadmin.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-18 12:34:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_UNOADMIN_
#define _DBAUI_UNOADMIN_

#ifndef _SVT_GENERICUNODIALOG_HXX_
#include <svtools/genericunodialog.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif

class SfxItemSet;
class SfxItemPool;
class SfxPoolItem;

//.........................................................................
namespace dbaui
{
//.........................................................................

//=========================================================================
typedef ::svt::OGenericUnoDialog ODatabaseAdministrationDialogBase;
class ODatabaseAdministrationDialog
        :public ODatabaseAdministrationDialogBase
        ,public ::comphelper::OPropertyArrayUsageHelper< ODatabaseAdministrationDialog >
        ,public OModuleClient
{
protected:
    SfxItemSet*             m_pDatasourceItems;     // item set for the dialog
    SfxItemPool*            m_pItemPool;            // item pool for the item set for the dialog
    SfxPoolItem**           m_pItemPoolDefaults;    // pool defaults
    ODsnTypeCollection*     m_pCollection;          // datasource type collection

    ::rtl::OUString         m_sInitialSelection;

protected:
    ODatabaseAdministrationDialog(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
    ~ODatabaseAdministrationDialog();

public:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo>  SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

protected:
// OGenericUnoDialog overridables
    virtual Dialog* createDialog(Window* _pParent);
    virtual void destroyDialog();
    virtual void implInitialize(const com::sun::star::uno::Any& _rValue);
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_UNOADMIN_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.4  2001/05/17 09:16:15  fs
 *  #86511# hold the type collection as pointer, not as object - allows construction in createDialog, where it can be guarded by the solar mutex
 *
 *  Revision 1.3  2000/11/01 16:31:30  fs
 *  migrated from awt::XDialog to ui::XExecutableDialog / removed the star* namespace shortcuts
 *
 *  Revision 1.2  2000/10/31 08:07:47  fs
 *  support an initial selection
 *
 *  Revision 1.1  2000/10/25 12:49:14  fs
 *  moved herein from ..\dlg
 *
 *  Revision 1.2  2000/10/11 11:31:03  fs
 *  new implementations - still under construction
 *
 *  Revision 1.1  2000/10/05 10:07:32  fs
 *  initial checkin
 *
 *
 *  Revision 1.0 20.09.00 12:15:14  fs
 ************************************************************************/

<commit_msg>#88530# +implSetOperationMode<commit_after>/*************************************************************************
 *
 *  $RCSfile: unoadmin.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: fs $ $Date: 2001-07-30 11:30:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_UNOADMIN_
#define _DBAUI_UNOADMIN_

#ifndef _SVT_GENERICUNODIALOG_HXX_
#include <svtools/genericunodialog.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif

class SfxItemSet;
class SfxItemPool;
class SfxPoolItem;

//.........................................................................
namespace dbaui
{
//.........................................................................

class ODbAdminDialog;

//=========================================================================
//= ODatabaseAdministrationDialog
//=========================================================================
typedef ::svt::OGenericUnoDialog ODatabaseAdministrationDialogBase;
class ODatabaseAdministrationDialog
        :public ODatabaseAdministrationDialogBase
        ,public ::comphelper::OPropertyArrayUsageHelper< ODatabaseAdministrationDialog >
        ,public OModuleClient
{
protected:
    SfxItemSet*             m_pDatasourceItems;     // item set for the dialog
    SfxItemPool*            m_pItemPool;            // item pool for the item set for the dialog
    SfxPoolItem**           m_pItemPoolDefaults;    // pool defaults
    ODsnTypeCollection*     m_pCollection;          // datasource type collection

    ::rtl::OUString         m_sInitialSelection;
    ::rtl::OUString         m_sOperationMode;

protected:
    ODatabaseAdministrationDialog(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
    ~ODatabaseAdministrationDialog();

public:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo>  SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

protected:
// OGenericUnoDialog overridables
    virtual Dialog* createDialog(Window* _pParent);
    virtual void destroyDialog();
    virtual void implInitialize(const com::sun::star::uno::Any& _rValue);

private:
    void    implSetOperationMode(ODbAdminDialog* _pDialog);
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_UNOADMIN_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.5  2001/06/18 12:34:56  fs
 *  #88389# OGenericUnoDialog moved to svtools
 *
 *  Revision 1.4  2001/05/17 09:16:15  fs
 *  #86511# hold the type collection as pointer, not as object - allows construction in createDialog, where it can be guarded by the solar mutex
 *
 *  Revision 1.3  2000/11/01 16:31:30  fs
 *  migrated from awt::XDialog to ui::XExecutableDialog / removed the star* namespace shortcuts
 *
 *  Revision 1.2  2000/10/31 08:07:47  fs
 *  support an initial selection
 *
 *  Revision 1.1  2000/10/25 12:49:14  fs
 *  moved herein from ..\dlg
 *
 *  Revision 1.2  2000/10/11 11:31:03  fs
 *  new implementations - still under construction
 *
 *  Revision 1.1  2000/10/05 10:07:32  fs
 *  initial checkin
 *
 *
 *  Revision 1.0 20.09.00 12:15:14  fs
 ************************************************************************/

<|endoftext|>