<commit_before>/******************************************************************************\
* File:          svn.cpp
* Purpose:       Implementation of wxExSVN class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/svn.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI

wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;

wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
  : m_Type(GetType(command_id))
  , m_Output()
  , m_FullPath(fullpath)
  , m_ReturnCode(-2)
{
  Initialize();
}

wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
  : m_Type(type)
  , m_Output()
  , m_FullPath(fullpath)
  , m_ReturnCode(-2)
{
  Initialize();
}

int wxExSVN::Execute(bool show_dialog)
{
  if (show_dialog)
  {
    std::vector<wxExConfigItem> v;

    if (m_Type == SVN_COMMIT)
    {
      v.push_back(wxExConfigItem(_("Revision comment"), CONFIG_COMBOBOX));
    }

    if (m_FullPath.empty())
    {
      v.push_back(wxExConfigItem(_("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true));
    }

    // SVN_UPDATE has no flags to ask for.
    if (m_Type != SVN_UPDATE)
    {
      v.push_back(wxExConfigItem(_("Flags")));
    }

    if (wxExConfigDialog(wxTheApp->GetTopWindow(),
      wxExApp::GetConfig(),
      v,
      m_Caption).ShowModal() == wxID_CANCEL)
    {
      m_ReturnCode = -1;
      return m_ReturnCode;
    }
  }

  const wxString cwd = wxGetCwd();

  wxString file;

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(wxExApp::GetConfig(_("Base folder")));
  }
  else
  {
    file = " \"" + m_FullPath + "\"";
  }

  wxString arg;

  if (m_Type == SVN_COMMIT)
  {
    arg = " -m \"" + wxExApp::GetConfig(_("Revision comment")) + "\"";
  }

  wxString flags = wxExApp::GetConfig(_("Flags"));

  if (!flags.empty())
  {
    flags += " ";
  }

  const wxString command = "svn " + flags + m_Command + arg + file;

  wxArrayString output;
  wxArrayString errors;

  if (wxExecute(
    command,
    output,
    errors) == -1)
  {
    m_ReturnCode = -1;
    return m_ReturnCode;
  }

  if (errors.GetCount() == 0)
  {
    wxExApp::Log(command);
  }

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  m_Output.clear();

  // First output the errors.
  for (size_t i = 0; i < errors.GetCount(); i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (size_t j = 0; j < output.GetCount(); j++)
  {
    m_Output += output[j] + "\n";
  }

  m_ReturnCode = errors.GetCount();

  return m_ReturnCode;
}

int wxExSVN::ExecuteAndShowOutput()
{
  if (Execute() >= 0)
  {
    ShowOutput();
  }

  return m_ReturnCode;
}

wxExSVNType wxExSVN::GetType(int command_id) const
{
  switch (command_id)
  {
    case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
    case ID_EDIT_SVN_CAT: return SVN_CAT; break;
    case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
    case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
    case ID_EDIT_SVN_LOG: return SVN_LOG; break;
    default:
      wxFAIL;
      break;
  }
}

void wxExSVN::Initialize()
{
  switch (m_Type)
  {
    case SVN_BLAME:  m_Caption = "SVN Blame"; break;
    case SVN_CAT:    m_Caption = "SVN Cat"; break;
    case SVN_COMMIT: m_Caption = "SVN Commit"; break;
    case SVN_DIFF:   m_Caption = "SVN Diff"; break;
    case SVN_INFO:   m_Caption = "SVN Info"; break;
    case SVN_LOG:    m_Caption = "SVN Log"; break;
    case SVN_STAT:   m_Caption = "SVN Stat"; break;
    case SVN_UPDATE: m_Caption = "SVN Update"; break;
    default:
      wxFAIL;
      break;
  }

  m_Command = m_Caption.AfterFirst(' ').Lower();
}

void wxExSVN::ShowOutput() const
{
  // If we did not yet ask Execute, or cancelled, return.
  if (m_ReturnCode < 0)
  {
    return;
  }

  const wxString caption = m_Caption +
    (!m_FullPath.empty() ? " " + wxFileName(m_FullPath).GetFullName(): wxString(wxEmptyString));

  // Create a dialog for contents.
  if (m_STCEntryDialog == NULL)
  {
    m_STCEntryDialog = new wxExSTCEntryDialog(
      wxTheApp->GetTopWindow(),
      caption,
      m_Output,
      wxEmptyString,
      wxOK,
      wxID_ANY,
      wxDefaultPosition, wxSize(575, 250));
  }
  else
  {
    m_STCEntryDialog->SetText(m_Output);
    m_STCEntryDialog->SetTitle(caption);
  }

  // Add a lexer if we specified a path, asked for cat or blame and there were no errors.
  if (
    !m_FullPath.empty() &&
    (m_Type == SVN_CAT || m_Type == SVN_BLAME) &&
     m_ReturnCode == 0)
  {
    const wxExFileName fn(m_FullPath);
    m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
  }

  m_STCEntryDialog->Show();
}

#endif
<commit_msg>fixed warning<commit_after>/******************************************************************************\
* File:          svn.cpp
* Purpose:       Implementation of wxExSVN class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/svn.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI

wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;

wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
  : m_Type(GetType(command_id))
  , m_Output()
  , m_FullPath(fullpath)
  , m_ReturnCode(-2)
{
  Initialize();
}

wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
  : m_Type(type)
  , m_Output()
  , m_FullPath(fullpath)
  , m_ReturnCode(-2)
{
  Initialize();
}

int wxExSVN::Execute(bool show_dialog)
{
  if (show_dialog)
  {
    std::vector<wxExConfigItem> v;

    if (m_Type == SVN_COMMIT)
    {
      v.push_back(wxExConfigItem(_("Revision comment"), CONFIG_COMBOBOX));
    }

    if (m_FullPath.empty())
    {
      v.push_back(wxExConfigItem(_("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true));
    }

    // SVN_UPDATE has no flags to ask for.
    if (m_Type != SVN_UPDATE)
    {
      v.push_back(wxExConfigItem(_("Flags")));
    }

    if (wxExConfigDialog(wxTheApp->GetTopWindow(),
      wxExApp::GetConfig(),
      v,
      m_Caption).ShowModal() == wxID_CANCEL)
    {
      m_ReturnCode = -1;
      return m_ReturnCode;
    }
  }

  const wxString cwd = wxGetCwd();

  wxString file;

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(wxExApp::GetConfig(_("Base folder")));
  }
  else
  {
    file = " \"" + m_FullPath + "\"";
  }

  wxString arg;

  if (m_Type == SVN_COMMIT)
  {
    arg = " -m \"" + wxExApp::GetConfig(_("Revision comment")) + "\"";
  }

  wxString flags = wxExApp::GetConfig(_("Flags"));

  if (!flags.empty())
  {
    flags += " ";
  }

  const wxString command = "svn " + flags + m_Command + arg + file;

  wxArrayString output;
  wxArrayString errors;

  if (wxExecute(
    command,
    output,
    errors) == -1)
  {
    m_ReturnCode = -1;
    return m_ReturnCode;
  }

  if (errors.GetCount() == 0)
  {
    wxExApp::Log(command);
  }

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  m_Output.clear();

  // First output the errors.
  for (size_t i = 0; i < errors.GetCount(); i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (size_t j = 0; j < output.GetCount(); j++)
  {
    m_Output += output[j] + "\n";
  }

  m_ReturnCode = errors.GetCount();

  return m_ReturnCode;
}

int wxExSVN::ExecuteAndShowOutput()
{
  if (Execute() >= 0)
  {
    ShowOutput();
  }

  return m_ReturnCode;
}

wxExSVNType wxExSVN::GetType(int command_id) const
{
  switch (command_id)
  {
    case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
    case ID_EDIT_SVN_CAT: return SVN_CAT; break;
    case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
    case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
    case ID_EDIT_SVN_LOG: return SVN_LOG; break;
    default:
      wxFAIL;
      break;
  }

  return SVN_STAT;
}

void wxExSVN::Initialize()
{
  switch (m_Type)
  {
    case SVN_BLAME:  m_Caption = "SVN Blame"; break;
    case SVN_CAT:    m_Caption = "SVN Cat"; break;
    case SVN_COMMIT: m_Caption = "SVN Commit"; break;
    case SVN_DIFF:   m_Caption = "SVN Diff"; break;
    case SVN_INFO:   m_Caption = "SVN Info"; break;
    case SVN_LOG:    m_Caption = "SVN Log"; break;
    case SVN_STAT:   m_Caption = "SVN Stat"; break;
    case SVN_UPDATE: m_Caption = "SVN Update"; break;
    default:
      wxFAIL;
      break;
  }

  m_Command = m_Caption.AfterFirst(' ').Lower();
}

void wxExSVN::ShowOutput() const
{
  // If we did not yet ask Execute, or cancelled, return.
  if (m_ReturnCode < 0)
  {
    return;
  }

  const wxString caption = m_Caption +
    (!m_FullPath.empty() ? " " + wxFileName(m_FullPath).GetFullName(): wxString(wxEmptyString));

  // Create a dialog for contents.
  if (m_STCEntryDialog == NULL)
  {
    m_STCEntryDialog = new wxExSTCEntryDialog(
      wxTheApp->GetTopWindow(),
      caption,
      m_Output,
      wxEmptyString,
      wxOK,
      wxID_ANY,
      wxDefaultPosition, wxSize(575, 250));
  }
  else
  {
    m_STCEntryDialog->SetText(m_Output);
    m_STCEntryDialog->SetTitle(caption);
  }

  // Add a lexer if we specified a path, asked for cat or blame and there were no errors.
  if (
    !m_FullPath.empty() &&
    (m_Type == SVN_CAT || m_Type == SVN_BLAME) &&
     m_ReturnCode == 0)
  {
    const wxExFileName fn(m_FullPath);
    m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
  }

  m_STCEntryDialog->Show();
}

#endif
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <tsdb/SQLEngine.h>
#include <tsdb/TSDBNode.h>
#include <tsdb/TimeWindowPartitioner.h>
#include <chartsql/defaults.h>

namespace tsdb {

SQLEngine::SQLEngine(TSDBNode* tsdb_node) : tsdb_node_(tsdb_node) {
  installDefaultSymbols(&sql_runtime_);
}

void SQLEngine::executeQuery(
    const String& tsdb_namespace,
    const String& query,
    RefPtr<csql::ResultFormat> result_format) {
  auto qplan = parseAndBuildQueryPlan(tsdb_namespace, query);
  sql_runtime_.executeQuery(qplan, result_format);
}

RefPtr<csql::QueryPlan> SQLEngine::parseAndBuildQueryPlan(
    const String& tsdb_namespace,
    const String& query) {
  return sql_runtime_.parseAndBuildQueryPlan(
      query,
      tableProviderForNamespace(tsdb_namespace),
      std::bind(
          &SQLEngine::rewriteQuery,
          this,
          tsdb_namespace,
          std::placeholders::_1));
}

RefPtr<csql::QueryTreeNode> SQLEngine::rewriteQuery(
    const String& tsdb_namespace,
    RefPtr<csql::QueryTreeNode> query) {
  if (dynamic_cast<csql::TableExpressionNode*>(query.get())) {
    auto tbl_expr = query.asInstanceOf<csql::TableExpressionNode>();
    replaceAllSequentialScansWithUnions(tsdb_namespace, &tbl_expr);
    return tbl_expr.get();
  }

  return query;
}

RefPtr<csql::TableProvider> SQLEngine::tableProviderForNamespace(
    const String& tsdb_namespace) {
  return new TSDBTableProvider(tsdb_namespace, tsdb_node_);
}

void SQLEngine::replaceAllSequentialScansWithUnions(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  if (dynamic_cast<csql::SequentialScanNode*>(node->get())) {
    replaceSequentialScanWithUnion(tsdb_namespace, node);
    return;
  }

  auto ntables = node->get()->numInputTables();
  for (int i = 0; i < ntables; ++i) {
    replaceAllSequentialScansWithUnions(
        tsdb_namespace,
        node->get()->mutableInputTable(i));
  }
}

void SQLEngine::replaceSequentialScanWithUnion(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  auto seqscan = node->asInstanceOf<csql::SequentialScanNode>();

  auto table_ref = TSDBTableRef::parse(seqscan->tableName());
  if (!table_ref.partition_key.isEmpty()) {
    return;
  }

  if (table_ref.timerange_begin.isEmpty() ||
      table_ref.timerange_limit.isEmpty()) {
    RAISE(
        kRuntimeError,
        "invalid reference to timeseries table without timerange. " \
        "try appending .last30days to the table name");
  }

  auto partitions = TimeWindowPartitioner::partitionKeysFor(
      table_ref.table_key,
      table_ref.timerange_begin.get(),
      table_ref.timerange_limit.get(),
      4 * kMicrosPerHour);

  Vector<RefPtr<csql::TableExpressionNode>> union_tables;
  for (const auto& partition : partitions) {
    auto table_name = StringUtil::format(
        "tsdb://localhost/$0/$1",
        URI::urlEncode(table_ref.table_key),
        partition.toString());

    auto copy = seqscan->deepCopyAs<csql::SequentialScanNode>();
    copy->setTableName(table_name);
    union_tables.emplace_back(copy.get());
  }

  *node = RefPtr<csql::TableExpressionNode>(new csql::UnionNode(union_tables));
}

}
<commit_msg>better error handling<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <tsdb/SQLEngine.h>
#include <tsdb/TSDBNode.h>
#include <tsdb/TimeWindowPartitioner.h>
#include <chartsql/defaults.h>

namespace tsdb {

SQLEngine::SQLEngine(TSDBNode* tsdb_node) : tsdb_node_(tsdb_node) {
  installDefaultSymbols(&sql_runtime_);
}

void SQLEngine::executeQuery(
    const String& tsdb_namespace,
    const String& query,
    RefPtr<csql::ResultFormat> result_format) {
  auto qplan = parseAndBuildQueryPlan(tsdb_namespace, query);
  sql_runtime_.executeQuery(qplan, result_format);
}

RefPtr<csql::QueryPlan> SQLEngine::parseAndBuildQueryPlan(
    const String& tsdb_namespace,
    const String& query) {
  return sql_runtime_.parseAndBuildQueryPlan(
      query,
      tableProviderForNamespace(tsdb_namespace),
      std::bind(
          &SQLEngine::rewriteQuery,
          this,
          tsdb_namespace,
          std::placeholders::_1));
}

RefPtr<csql::QueryTreeNode> SQLEngine::rewriteQuery(
    const String& tsdb_namespace,
    RefPtr<csql::QueryTreeNode> query) {
  if (dynamic_cast<csql::TableExpressionNode*>(query.get())) {
    auto tbl_expr = query.asInstanceOf<csql::TableExpressionNode>();
    replaceAllSequentialScansWithUnions(tsdb_namespace, &tbl_expr);
    return tbl_expr.get();
  }

  return query;
}

RefPtr<csql::TableProvider> SQLEngine::tableProviderForNamespace(
    const String& tsdb_namespace) {
  return new TSDBTableProvider(tsdb_namespace, tsdb_node_);
}

void SQLEngine::replaceAllSequentialScansWithUnions(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  if (dynamic_cast<csql::SequentialScanNode*>(node->get())) {
    replaceSequentialScanWithUnion(tsdb_namespace, node);
    return;
  }

  auto ntables = node->get()->numInputTables();
  for (int i = 0; i < ntables; ++i) {
    replaceAllSequentialScansWithUnions(
        tsdb_namespace,
        node->get()->mutableInputTable(i));
  }
}

void SQLEngine::replaceSequentialScanWithUnion(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  auto seqscan = node->asInstanceOf<csql::SequentialScanNode>();

  auto table_ref = TSDBTableRef::parse(seqscan->tableName());
  if (!table_ref.partition_key.isEmpty()) {
    return;
  }

  if (table_ref.timerange_begin.isEmpty() ||
      table_ref.timerange_limit.isEmpty()) {
    RAISEF(
        kRuntimeError,
        "invalid reference to timeseries table '$0' without timerange. " \
        "try appending .last30days to the table name",
        table_ref.table_key);
  }

  auto partitions = TimeWindowPartitioner::partitionKeysFor(
      table_ref.table_key,
      table_ref.timerange_begin.get(),
      table_ref.timerange_limit.get(),
      4 * kMicrosPerHour);

  Vector<RefPtr<csql::TableExpressionNode>> union_tables;
  for (const auto& partition : partitions) {
    auto table_name = StringUtil::format(
        "tsdb://localhost/$0/$1",
        URI::urlEncode(table_ref.table_key),
        partition.toString());

    auto copy = seqscan->deepCopyAs<csql::SequentialScanNode>();
    copy->setTableName(table_name);
    union_tables.emplace_back(copy.get());
  }

  *node = RefPtr<csql::TableExpressionNode>(new csql::UnionNode(union_tables));
}

}
<|endoftext|>


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

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <signal.h>
#include <termios.h>
#include <stdio.h>
#include "boost/thread/mutex.hpp"
#include "boost/thread/thread.hpp"

#define KEYCODE_R 0x43
#define KEYCODE_L 0x44
#define KEYCODE_U 0x41
#define KEYCODE_D 0x42
#define KEYCODE_Q 0x71

class TurtlebotTeleop
{
public:
  TurtlebotTeleop();
  void keyLoop();
  void watchdog();

private:

  ros::NodeHandle nh_,ph_;
  double linear_, angular_;
  ros::Time last_publish_;
  double l_scale_, a_scale_;
  ros::Publisher vel_pub_;
  void publish(double, double);
  boost::mutex publish_mutex_;

};

TurtlebotTeleop::TurtlebotTeleop():
  linear_(0),
  angular_(0),
  l_scale_(1.0),
  a_scale_(1.0)
{
  ph_.param("scale_angular", a_scale_, a_scale_);
  ph_.param("scale_linear", l_scale_, l_scale_);

  vel_pub_ = nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1);
}

int kfd = 0;
struct termios cooked, raw;

void quit(int sig)
{
  tcsetattr(kfd, TCSANOW, &cooked);
  ros::shutdown();
  exit(0);
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "turtlebot_teleop");
  TurtlebotTeleop turtlebot_teleop;
  ros::NodeHandle n;

  signal(SIGINT,quit);

  boost::thread my_thread(boost::bind(&TurtlebotTeleop::keyLoop, &turtlebot_teleop));

  ros::Timer timer = n.createTimer(ros::Duration(0.1), boost::bind(&TurtlebotTeleop::watchdog, &turtlebot_teleop));

  ros::spin();

  my_thread.interrupt() ;
  my_thread.join() ;

  return(0);
}

void TurtlebotTeleop::watchdog()
{
  boost::mutex::scoped_lock lock(publish_mutex_);
  if (ros::Time::now() > last_publish_ + ros::Duration(0.15))
    publish(0, 0);
}

void TurtlebotTeleop::keyLoop()
{
  char c;

  // get the console in raw mode
  tcgetattr(kfd, &cooked);
  memcpy(&raw, &cooked, sizeof(struct termios));
  raw.c_lflag &=~ (ICANON | ECHO);
  // Setting a new line, then end of file
  raw.c_cc[VEOL] = 1;
  raw.c_cc[VEOF] = 2;
  tcsetattr(kfd, TCSANOW, &raw);

  puts("Reading from keyboard");
  puts("---------------------------");
  puts("Use arrow keys to move the turtlebot.");

  for(;;)
  {
    // get the next event from the keyboard
    if(read(kfd, &c, 1) < 0)
    {
      perror("read():");
      exit(-1);
    }

    linear_=angular_=0;
    ROS_DEBUG("value: 0x%02X\n", c);

    switch(c)
    {
      case KEYCODE_L:
        ROS_DEBUG("LEFT");
        angular_ = 1.0;
        break;
      case KEYCODE_R:
        ROS_DEBUG("RIGHT");
        angular_ = -1.0;
        break;
      case KEYCODE_U:
        ROS_DEBUG("UP");
        linear_ = 1.0;
        break;
      case KEYCODE_D:
        ROS_DEBUG("DOWN");
        linear_ = -1.0;
        break;
    }
    boost::mutex::scoped_lock lock(publish_mutex_);
    last_publish_ = ros::Time::now();
    publish(angular_, linear_);
  }

  return;
}

void TurtlebotTeleop::publish(double angular, double linear)
{
    geometry_msgs::Twist vel;
    vel.angular.z = a_scale_*angular;
    vel.linear.x = l_scale_*linear;

    vel_pub_.publish(vel);

  return;
}

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

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <signal.h>
#include <termios.h>
#include <stdio.h>
#include "boost/thread/mutex.hpp"
#include "boost/thread/thread.hpp"

#define KEYCODE_R 0x43
#define KEYCODE_L 0x44
#define KEYCODE_U 0x41
#define KEYCODE_D 0x42
#define KEYCODE_Q 0x71

class TurtlebotTeleop
{
public:
  TurtlebotTeleop();
  void keyLoop();
  void watchdog();

private:

  ros::NodeHandle nh_,ph_;
  double linear_, angular_;
  ros::Time last_publish_;
  double l_scale_, a_scale_;
  ros::Publisher vel_pub_;
  void publish(double, double);
  boost::mutex publish_mutex_;

};

TurtlebotTeleop::TurtlebotTeleop():
  ph_("~"),
  linear_(0),
  angular_(0),
  l_scale_(1.0),
  a_scale_(1.0)
{
  ph_.param("scale_angular", a_scale_, a_scale_);
  ph_.param("scale_linear", l_scale_, l_scale_);

  vel_pub_ = nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1);
}

int kfd = 0;
struct termios cooked, raw;

void quit(int sig)
{
  tcsetattr(kfd, TCSANOW, &cooked);
  ros::shutdown();
  exit(0);
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "turtlebot_teleop");
  TurtlebotTeleop turtlebot_teleop;
  ros::NodeHandle n;

  signal(SIGINT,quit);

  boost::thread my_thread(boost::bind(&TurtlebotTeleop::keyLoop, &turtlebot_teleop));

  ros::Timer timer = n.createTimer(ros::Duration(0.1), boost::bind(&TurtlebotTeleop::watchdog, &turtlebot_teleop));

  ros::spin();

  my_thread.interrupt() ;
  my_thread.join() ;

  return(0);
}

void TurtlebotTeleop::watchdog()
{
  boost::mutex::scoped_lock lock(publish_mutex_);
  if (ros::Time::now() > last_publish_ + ros::Duration(0.15))
    publish(0, 0);
}

void TurtlebotTeleop::keyLoop()
{
  char c;

  // get the console in raw mode
  tcgetattr(kfd, &cooked);
  memcpy(&raw, &cooked, sizeof(struct termios));
  raw.c_lflag &=~ (ICANON | ECHO);
  // Setting a new line, then end of file
  raw.c_cc[VEOL] = 1;
  raw.c_cc[VEOF] = 2;
  tcsetattr(kfd, TCSANOW, &raw);

  puts("Reading from keyboard");
  puts("---------------------------");
  puts("Use arrow keys to move the turtlebot.");

  for(;;)
  {
    // get the next event from the keyboard
    if(read(kfd, &c, 1) < 0)
    {
      perror("read():");
      exit(-1);
    }

    linear_=angular_=0;
    ROS_DEBUG("value: 0x%02X\n", c);

    switch(c)
    {
      case KEYCODE_L:
        ROS_DEBUG("LEFT");
        angular_ = 1.0;
        break;
      case KEYCODE_R:
        ROS_DEBUG("RIGHT");
        angular_ = -1.0;
        break;
      case KEYCODE_U:
        ROS_DEBUG("UP");
        linear_ = 1.0;
        break;
      case KEYCODE_D:
        ROS_DEBUG("DOWN");
        linear_ = -1.0;
        break;
    }
    boost::mutex::scoped_lock lock(publish_mutex_);
    last_publish_ = ros::Time::now();
    publish(angular_, linear_);
  }

  return;
}

void TurtlebotTeleop::publish(double angular, double linear)
{
    geometry_msgs::Twist vel;
    vel.angular.z = a_scale_*angular;
    vel.linear.x = l_scale_*linear;

    vel_pub_.publish(vel);

  return;
}

<|endoftext|>


<commit_before>#include <fstream>
#include <cstring>

#include <urlreader.h>
#include <utils.h>
#include <logger.h>
#include <sys/utsname.h>
#include <config.h>

namespace newsbeuter {

urlreader::urlreader() : offline(false) { }
urlreader::~urlreader() { }

std::vector<std::string>& urlreader::get_urls() {
	return urls;
}

std::vector<std::string>& urlreader::get_tags(const std::string& url) {
	return tags[url];
}

std::vector<std::string> urlreader::get_alltags() {
	std::vector<std::string> tmptags;
	for (std::set<std::string>::iterator it=alltags.begin();it!=alltags.end();++it) {
		if (it->substr(0,1) != "~")
			tmptags.push_back(*it);
	}
	return tmptags;
}

file_urlreader::file_urlreader(const std::string& file) : filename(file) { }
file_urlreader::~file_urlreader() { }

std::string file_urlreader::get_source() {
	return filename;
}

void file_urlreader::reload() {
	if (offline)
		return;

	urls.clear();
	tags.clear();
	alltags.clear();

	std::fstream f;
	f.open(filename.c_str(),std::fstream::in);
	if (f.is_open()) {
		std::string line;
		do {
			getline(f,line);
			if (!f.eof() && line.length() > 0 && line[0] != '#') {
				std::vector<std::string> tokens = utils::tokenize_quoted(line);
				if (tokens.size() > 0) {
					std::string url = tokens[0];
					urls.push_back(url);
					tokens.erase(tokens.begin());
					if (tokens.size() > 0) {
						tags[url] = tokens;
						for (std::vector<std::string>::iterator it=tokens.begin();it!=tokens.end();++it) {
							alltags.insert(*it);
						}
					}
				}
			}
		} while (!f.eof());
	}
}

void file_urlreader::load_config(const std::string& file) {
	filename = file;
	reload();
}

void file_urlreader::write_config() {
	std::fstream f;
	f.open(filename.c_str(),std::fstream::out);
	if (f.is_open()) {
		for (std::vector<std::string>::iterator it=urls.begin(); it != urls.end(); ++it) {
			f << *it;
			if (tags[*it].size() > 0) {
				for (std::vector<std::string>::iterator jt=tags[*it].begin();jt!=tags[*it].end();++jt) {
					f << " \"" << *jt << "\"";
				}
			}
			f << std::endl;
		}
	}
}

opml_urlreader::opml_urlreader(configcontainer * c) : cfg(c) { }
opml_urlreader::~opml_urlreader() { }

void opml_urlreader::write_config() {
	// do nothing.
}

void opml_urlreader::reload() {
	if (offline)
		return;

	urls.clear();
	tags.clear();
	alltags.clear();

	std::string user_agent = utils::get_useragent(cfg);

	std::vector<std::string> urls = utils::tokenize_quoted(this->get_source(), " ");

	for (std::vector<std::string>::iterator it=urls.begin();it!=urls.end();it++) {
		LOG(LOG_DEBUG, "opml_urlreader::reload: downloading `%s'", it->c_str());
		std::string urlcontent = utils::retrieve_url(*it, cfg, this->get_auth());

		xmlDoc * doc = xmlParseMemory(urlcontent.c_str(), urlcontent.length());

		if (doc == NULL) {
			LOG(LOG_ERROR, "opml_urlreader::reload: parsing XML file failed");
			continue;
		}

		xmlNode * root = xmlDocGetRootElement(doc);

		if (root) {
			for (xmlNode * node = root->children; node != NULL; node = node->next) {
				if (strcmp((const char *)node->name, "body")==0) {
					LOG(LOG_DEBUG, "opml_urlreader::reload: found body");
					rec_find_rss_outlines(node->children, "");
				}
			}
		}

		xmlFreeDoc(doc);
	}
}

void opml_urlreader::handle_node(xmlNode * node, const std::string& tag) {
	if (node) {
		char * rssurl = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl");
		if (rssurl && strlen(rssurl) > 0) {
			std::string theurl(rssurl);
			urls.push_back(theurl);
			if (tag.length() > 0) {
				std::vector<std::string> tmptags;
				tmptags.push_back(tag);
				tags[theurl] = tmptags;
				alltags.insert(tag);
			}
		}
		if (rssurl)
			xmlFree(rssurl);
	}
}

std::string opml_urlreader::get_source() {
	return cfg->get_configvalue("opml-url");
}

const char * opml_urlreader::get_auth() {
	return NULL;
}

}
<commit_msg>oops, removed one method that shouldn't have been removed.<commit_after>#include <fstream>
#include <cstring>

#include <urlreader.h>
#include <utils.h>
#include <logger.h>
#include <sys/utsname.h>
#include <config.h>

namespace newsbeuter {

urlreader::urlreader() : offline(false) { }
urlreader::~urlreader() { }

std::vector<std::string>& urlreader::get_urls() {
	return urls;
}

std::vector<std::string>& urlreader::get_tags(const std::string& url) {
	return tags[url];
}

std::vector<std::string> urlreader::get_alltags() {
	std::vector<std::string> tmptags;
	for (std::set<std::string>::iterator it=alltags.begin();it!=alltags.end();++it) {
		if (it->substr(0,1) != "~")
			tmptags.push_back(*it);
	}
	return tmptags;
}

file_urlreader::file_urlreader(const std::string& file) : filename(file) { }
file_urlreader::~file_urlreader() { }

std::string file_urlreader::get_source() {
	return filename;
}

void file_urlreader::reload() {
	if (offline)
		return;

	urls.clear();
	tags.clear();
	alltags.clear();

	std::fstream f;
	f.open(filename.c_str(),std::fstream::in);
	if (f.is_open()) {
		std::string line;
		do {
			getline(f,line);
			if (!f.eof() && line.length() > 0 && line[0] != '#') {
				std::vector<std::string> tokens = utils::tokenize_quoted(line);
				if (tokens.size() > 0) {
					std::string url = tokens[0];
					urls.push_back(url);
					tokens.erase(tokens.begin());
					if (tokens.size() > 0) {
						tags[url] = tokens;
						for (std::vector<std::string>::iterator it=tokens.begin();it!=tokens.end();++it) {
							alltags.insert(*it);
						}
					}
				}
			}
		} while (!f.eof());
	}
}

void file_urlreader::load_config(const std::string& file) {
	filename = file;
	reload();
}

void file_urlreader::write_config() {
	std::fstream f;
	f.open(filename.c_str(),std::fstream::out);
	if (f.is_open()) {
		for (std::vector<std::string>::iterator it=urls.begin(); it != urls.end(); ++it) {
			f << *it;
			if (tags[*it].size() > 0) {
				for (std::vector<std::string>::iterator jt=tags[*it].begin();jt!=tags[*it].end();++jt) {
					f << " \"" << *jt << "\"";
				}
			}
			f << std::endl;
		}
	}
}

opml_urlreader::opml_urlreader(configcontainer * c) : cfg(c) { }
opml_urlreader::~opml_urlreader() { }

void opml_urlreader::write_config() {
	// do nothing.
}

void opml_urlreader::reload() {
	if (offline)
		return;

	urls.clear();
	tags.clear();
	alltags.clear();

	std::string user_agent = utils::get_useragent(cfg);

	std::vector<std::string> urls = utils::tokenize_quoted(this->get_source(), " ");

	for (std::vector<std::string>::iterator it=urls.begin();it!=urls.end();it++) {
		LOG(LOG_DEBUG, "opml_urlreader::reload: downloading `%s'", it->c_str());
		std::string urlcontent = utils::retrieve_url(*it, cfg, this->get_auth());

		xmlDoc * doc = xmlParseMemory(urlcontent.c_str(), urlcontent.length());

		if (doc == NULL) {
			LOG(LOG_ERROR, "opml_urlreader::reload: parsing XML file failed");
			continue;
		}

		xmlNode * root = xmlDocGetRootElement(doc);

		if (root) {
			for (xmlNode * node = root->children; node != NULL; node = node->next) {
				if (strcmp((const char *)node->name, "body")==0) {
					LOG(LOG_DEBUG, "opml_urlreader::reload: found body");
					rec_find_rss_outlines(node->children, "");
				}
			}
		}

		xmlFreeDoc(doc);
	}
}

void opml_urlreader::handle_node(xmlNode * node, const std::string& tag) {
	if (node) {
		char * rssurl = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl");
		if (rssurl && strlen(rssurl) > 0) {
			std::string theurl(rssurl);
			urls.push_back(theurl);
			if (tag.length() > 0) {
				std::vector<std::string> tmptags;
				tmptags.push_back(tag);
				tags[theurl] = tmptags;
				alltags.insert(tag);
			}
		}
		if (rssurl)
			xmlFree(rssurl);
	}
}

void opml_urlreader::rec_find_rss_outlines(xmlNode * node, std::string tag) {
	while (node) {
		char * type = (char *)xmlGetProp(node, (const xmlChar *)"type");

		std::string newtag = tag;

		if (strcmp((const char *)node->name, "outline")==0) {
			 if (type && strcmp(type,"rss")==0) {
				 handle_node(node, tag);
			  } else {
				char * text = (char *)xmlGetProp(node, (const xmlChar *)"title");
				if (text) {
					if (newtag.length() > 0) {
						newtag.append("/");
					}
					newtag.append(text);
					xmlFree(text);
				}
			}
		}
		rec_find_rss_outlines(node->children, newtag);
		node = node->next;
	}
}

std::string opml_urlreader::get_source() {
	return cfg->get_configvalue("opml-url");
}

const char * opml_urlreader::get_auth() {
	return NULL;
}

}
<|endoftext|>


<commit_before>/* Copyright (c) 2017 Nguyen Viet Giang. All rights reserved. */
#ifdef ANY_TOOL

#include <catch.hpp>

#include <stdlib.h>
#include <string.h>
#include <any/asm.h>
#include <any/string_table.h>

#define REQUIRE_STR_EQUALS(a, b) REQUIRE(strcmp(a, b) == 0)

static void* myalloc(void*, void* old, int32_t sz)
{
    return realloc(old, sz);
}

static void num_vs_capacity_check(aasm_prototype_t* p)
{
    REQUIRE(p->num_instructions <= p->max_instructions);
    REQUIRE(p->num_constants <= p->max_constants);
    REQUIRE(p->num_imports <= p->max_imports);
    REQUIRE(p->num_nesteds <= p->max_nesteds);
}

typedef struct {
    ainstruction_t pop;
    ainstruction_t ldk;
    ainstruction_t llv;
    ainstruction_t slv;
    ainstruction_t imp;
    ainstruction_t jmp;
    ainstruction_t jin;
    ainstruction_t ivk;

    aconstant_t cinteger;
    aconstant_t cstring;
    aconstant_t creal;
} basic_test_ctx;

static void basic_add(aasm_t* a, basic_test_ctx& t)
{
    t.pop = ai_pop(rand());
    t.ldk = ai_ldk(rand());
    t.llv = ai_llv(rand());
    t.slv = ai_slv(rand());
    t.imp = ai_imp(rand());
    t.jmp = ai_jmp(rand());
    t.jin = ai_jin(rand());
    t.ivk = ai_ivk(rand());

    REQUIRE(0 == aasm_emit(a, ai_nop()));
    REQUIRE(1 == aasm_emit(a, t.pop));
    REQUIRE(2 == aasm_emit(a, t.ldk));
    REQUIRE(3 == aasm_emit(a, ai_nil()));
    REQUIRE(4 == aasm_emit(a, ai_ldb(TRUE)));
    REQUIRE(5 == aasm_emit(a, ai_ldb(FALSE)));
    REQUIRE(6 == aasm_emit(a, t.llv));
    REQUIRE(7 == aasm_emit(a, t.slv));
    REQUIRE(8 == aasm_emit(a, t.imp));
    REQUIRE(9 == aasm_emit(a, t.jmp));
    REQUIRE(10 == aasm_emit(a, t.jin));
    REQUIRE(11 == aasm_emit(a, t.ivk));
    REQUIRE(12 == aasm_emit(a, ai_ret()));

    t.cinteger = ac_integer(rand());
    t.cstring = ac_string(aasm_string_to_ref(a, "test_const"));
    t.creal = ac_real((areal_t)rand());

    REQUIRE(0 == aasm_add_constant(a, t.cinteger));
    REQUIRE(1 == aasm_add_constant(a, t.cstring));
    REQUIRE(2 == aasm_add_constant(a, t.creal));

    REQUIRE(0 == aasm_add_import(a, "tim0", "tin0"));
    REQUIRE(1 == aasm_add_import(a, "tim1", "tin1"));
    REQUIRE(2 == aasm_add_import(a, "tim2", "tin2"));
};

static void basic_check(aasm_t* a, basic_test_ctx& t)
{
    aasm_prototype_t* p = aasm_prototype(a);
    aasm_current_t c = aasm_resolve(a);

    num_vs_capacity_check(p);

    REQUIRE(p->num_instructions == 13);
    REQUIRE(c.instructions[0].b.opcode == AOC_NOP);
    REQUIRE(c.instructions[1].b.opcode == AOC_POP);
    REQUIRE(c.instructions[1].pop.n == t.pop.pop.n);
    REQUIRE(c.instructions[2].b.opcode == AOC_LDK);
    REQUIRE(c.instructions[2].ldk.idx == t.ldk.ldk.idx);
    REQUIRE(c.instructions[3].b.opcode == AOC_NIL);
    REQUIRE(c.instructions[4].b.opcode == AOC_LDB);
    REQUIRE(c.instructions[4].ldb.val == TRUE);
    REQUIRE(c.instructions[5].b.opcode == AOC_LDB);
    REQUIRE(c.instructions[5].ldb.val == FALSE);
    REQUIRE(c.instructions[6].b.opcode == AOC_LLV);
    REQUIRE(c.instructions[6].llv.idx == t.llv.llv.idx);
    REQUIRE(c.instructions[7].b.opcode == AOC_SLV);
    REQUIRE(c.instructions[7].slv.idx == t.slv.slv.idx);
    REQUIRE(c.instructions[8].b.opcode == AOC_IMP);
    REQUIRE(c.instructions[8].imp.idx == t.imp.imp.idx);
    REQUIRE(c.instructions[9].b.opcode == AOC_JMP);
    REQUIRE(c.instructions[9].jmp.displacement == t.jmp.jmp.displacement);
    REQUIRE(c.instructions[10].b.opcode == AOC_JIN);
    REQUIRE(c.instructions[10].jin.displacement == t.jin.jin.displacement);
    REQUIRE(c.instructions[11].b.opcode == AOC_IVK);
    REQUIRE(c.instructions[11].ivk.nargs == t.ivk.ivk.nargs);
    REQUIRE(c.instructions[12].b.opcode == AOC_RET);

    REQUIRE(p->num_constants == 3);
    REQUIRE(c.constants[0].b.type == ACT_INTEGER);
    REQUIRE(c.constants[0].integer.val == t.cinteger.integer.val);
    REQUIRE(c.constants[1].b.type == ACT_STRING);
    REQUIRE(c.constants[1].string.ref == t.cstring.string.ref);
    REQUIRE(c.constants[2].b.type == ACT_REAL);
    REQUIRE(c.constants[2].real.val == t.creal.real.val);

    REQUIRE(p->num_imports == 3);
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[0].module), "tim0");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[0].name), "tin0");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[1].module), "tim1");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[1].name), "tin1");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[2].module), "tim2");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[2].name), "tin2");
}

static void require_equals(aasm_t* a1, aasm_t* a2)
{
    aasm_prototype_t* p1 = aasm_prototype(a1);
    aasm_prototype_t* p2 = aasm_prototype(a2);
    aasm_current_t c1 = aasm_resolve(a1);
    aasm_current_t c2 = aasm_resolve(a2);

    REQUIRE_STR_EQUALS(
        astring_table_to_string(a1->st, p1->source),
        astring_table_to_string(a2->st, p2->source));
    REQUIRE_STR_EQUALS(
        astring_table_to_string(a1->st, p1->symbol),
        astring_table_to_string(a2->st, p2->symbol));

    REQUIRE(p1->num_upvalues == p2->num_upvalues);
    REQUIRE(p1->num_arguments == p2->num_arguments);
    REQUIRE(p1->num_local_vars == p2->num_local_vars);
    REQUIRE(p1->num_nesteds == p2->num_nesteds);

    REQUIRE(p1->num_instructions == p2->num_instructions);
    REQUIRE(
        memcmp(
            c1.instructions,
            c2.instructions,
            p1->num_instructions*sizeof(ainstruction_t)) == 0);

    REQUIRE(p1->num_constants == p2->num_constants);
    for (int32_t i = 0; i < p1->num_constants; ++i) {
        REQUIRE(c1.constants[i].b.type == c2.constants[i].b.type);
        switch (c1.constants[i].b.type) {
        case ACT_INTEGER:
            REQUIRE(c1.constants[i].integer.val == c2.constants[i].integer.val);
            break;
        case ACT_STRING:
            REQUIRE_STR_EQUALS(
                astring_table_to_string(a1->st, c1.constants[i].string.ref),
                astring_table_to_string(a2->st, c2.constants[i].string.ref));
            break;
        case ACT_REAL:
            REQUIRE(c1.constants[i].real.val == c2.constants[i].real.val);
            break;
        }
    }

    REQUIRE(p1->num_imports == p2->num_imports);
    for (int32_t i = 0; i < p2->num_imports; ++i) {
        REQUIRE_STR_EQUALS(
            astring_table_to_string(a1->st, c1.imports[i].module),
            astring_table_to_string(a2->st, c2.imports[i].module));
        REQUIRE_STR_EQUALS(
            astring_table_to_string(a1->st, c1.imports[i].name),
            astring_table_to_string(a2->st, c2.imports[i].name));
    }
}

TEST_CASE("asm_module")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);
    aasm_prototype_t* p = aasm_prototype(&a);

    REQUIRE(p->source == 0);
    REQUIRE(p->symbol == 0);
    REQUIRE(p->num_instructions == 0);
    REQUIRE(p->num_upvalues == 0);
    REQUIRE(p->num_arguments == 0);
    REQUIRE(p->num_local_vars == 0);
    REQUIRE(p->num_constants == 0);
    REQUIRE(p->num_imports == 0);
    REQUIRE(p->num_nesteds == 0);

    num_vs_capacity_check(p);

    aasm_cleanup(&a);
}

TEST_CASE("asm_basic")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);

    basic_test_ctx t;
    basic_add(&a, t);
    basic_check(&a, t);

    aasm_cleanup(&a);
}

TEST_CASE("asm_nested")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);

    enum { PUSH_COUNT = 25 };

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            REQUIRE(j == aasm_push(&a));
            basic_test_ctx t;
            basic_add(&a, t);
            basic_check(&a, t);
            REQUIRE(j == aasm_pop(&a));
            aasm_open(&a, j);
            basic_check(&a, t);
            REQUIRE(j == aasm_pop(&a));
        }
        if (i == 0) {
            REQUIRE(PUSH_COUNT == aasm_module_push(&a, "symbol"));
            const aasm_prototype_t* p = aasm_prototype(&a);
            REQUIRE_STR_EQUALS(astring_table_to_string(a.st, p->symbol), "symbol");
        } else {
            REQUIRE(PUSH_COUNT == aasm_push(&a));
        }
    }

    for (int32_t i = ANY_ASM_MAX_NESTED_LEVEL - 1; i >= 0; --i) {
        REQUIRE(PUSH_COUNT == aasm_pop(&a));
    }

    aasm_cleanup(&a);
}

TEST_CASE("asm_save_load")
{
    aasm_t a1;
    aasm_init(&a1, &myalloc, NULL);
    REQUIRE(aasm_load(&a1, NULL) == AERR_NONE);

    enum { PUSH_COUNT = 5 };

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            REQUIRE(j == aasm_push(&a1));
            basic_test_ctx t;
            basic_add(&a1, t);
            basic_check(&a1, t);
            REQUIRE(j == aasm_pop(&a1));
        }
        REQUIRE(PUSH_COUNT == aasm_push(&a1));
    }

    aasm_save(&a1);

    for (int32_t i = ANY_ASM_MAX_NESTED_LEVEL - 1; i >= 0; --i) {
        REQUIRE(PUSH_COUNT == aasm_pop(&a1));
    }

    aasm_t a2;
    aasm_init(&a2, &myalloc, NULL);
    REQUIRE(aasm_load(&a2, a1.chunk) == AERR_NONE);

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            aasm_open(&a1, j);
            aasm_open(&a2, j);
            require_equals(&a1, &a2);
            REQUIRE(j == aasm_pop(&a1));
            REQUIRE(j == aasm_pop(&a2));
        }
        aasm_open(&a1, PUSH_COUNT);
        aasm_open(&a2, PUSH_COUNT);
    }

    aasm_cleanup(&a1);
    aasm_cleanup(&a2);
}

#endif // ANY_TOOL
<commit_msg>fix CI<commit_after>/* Copyright (c) 2017 Nguyen Viet Giang. All rights reserved. */
#ifdef ANY_TOOL

#include <catch.hpp>

#include <stdlib.h>
#include <string.h>
#include <any/asm.h>
#include <any/string_table.h>

#define REQUIRE_STR_EQUALS(a, b) REQUIRE(strcmp(a, b) == 0)

static void* myalloc(void*, void* old, int32_t sz)
{
    return realloc(old, sz);
}

static void num_vs_capacity_check(aasm_prototype_t* p)
{
    REQUIRE(p->num_instructions <= p->max_instructions);
    REQUIRE(p->num_constants <= p->max_constants);
    REQUIRE(p->num_imports <= p->max_imports);
    REQUIRE(p->num_nesteds <= p->max_nesteds);
}

typedef struct {
    ainstruction_t pop;
    ainstruction_t ldk;
    ainstruction_t llv;
    ainstruction_t slv;
    ainstruction_t imp;
    ainstruction_t jmp;
    ainstruction_t jin;
    ainstruction_t ivk;

    aconstant_t cinteger;
    aconstant_t cstring;
    aconstant_t creal;
} basic_test_ctx;

static void basic_add(aasm_t* a, basic_test_ctx& t)
{
    t.pop = ai_pop(rand());
    t.ldk = ai_ldk(rand());
    t.llv = ai_llv(rand());
    t.slv = ai_slv(rand());
    t.imp = ai_imp(rand());
    t.jmp = ai_jmp(rand());
    t.jin = ai_jin(rand());
    t.ivk = ai_ivk(rand());

    REQUIRE(0 == aasm_emit(a, ai_nop()));
    REQUIRE(1 == aasm_emit(a, t.pop));
    REQUIRE(2 == aasm_emit(a, t.ldk));
    REQUIRE(3 == aasm_emit(a, ai_nil()));
    REQUIRE(4 == aasm_emit(a, ai_ldb(TRUE)));
    REQUIRE(5 == aasm_emit(a, ai_ldb(FALSE)));
    REQUIRE(6 == aasm_emit(a, t.llv));
    REQUIRE(7 == aasm_emit(a, t.slv));
    REQUIRE(8 == aasm_emit(a, t.imp));
    REQUIRE(9 == aasm_emit(a, t.jmp));
    REQUIRE(10 == aasm_emit(a, t.jin));
    REQUIRE(11 == aasm_emit(a, t.ivk));
    REQUIRE(12 == aasm_emit(a, ai_ret()));

    t.cinteger = ac_integer(rand());
    t.cstring = ac_string(aasm_string_to_ref(a, "test_const"));
    t.creal = ac_real((areal_t)rand());

    REQUIRE(0 == aasm_add_constant(a, t.cinteger));
    REQUIRE(1 == aasm_add_constant(a, t.cstring));
    REQUIRE(2 == aasm_add_constant(a, t.creal));

    REQUIRE(0 == aasm_add_import(a, "tim0", "tin0"));
    REQUIRE(1 == aasm_add_import(a, "tim1", "tin1"));
    REQUIRE(2 == aasm_add_import(a, "tim2", "tin2"));
};

static void basic_check(aasm_t* a, basic_test_ctx& t)
{
    aasm_prototype_t* p = aasm_prototype(a);
    aasm_current_t c = aasm_resolve(a);

    num_vs_capacity_check(p);

    REQUIRE(p->num_instructions == 13);
    REQUIRE(c.instructions[0].b.opcode == AOC_NOP);
    REQUIRE(c.instructions[1].b.opcode == AOC_POP);
    REQUIRE(c.instructions[1].pop.n == t.pop.pop.n);
    REQUIRE(c.instructions[2].b.opcode == AOC_LDK);
    REQUIRE(c.instructions[2].ldk.idx == t.ldk.ldk.idx);
    REQUIRE(c.instructions[3].b.opcode == AOC_NIL);
    REQUIRE(c.instructions[4].b.opcode == AOC_LDB);
    REQUIRE(c.instructions[4].ldb.val == TRUE);
    REQUIRE(c.instructions[5].b.opcode == AOC_LDB);
    REQUIRE(c.instructions[5].ldb.val == FALSE);
    REQUIRE(c.instructions[6].b.opcode == AOC_LLV);
    REQUIRE(c.instructions[6].llv.idx == t.llv.llv.idx);
    REQUIRE(c.instructions[7].b.opcode == AOC_SLV);
    REQUIRE(c.instructions[7].slv.idx == t.slv.slv.idx);
    REQUIRE(c.instructions[8].b.opcode == AOC_IMP);
    REQUIRE(c.instructions[8].imp.idx == t.imp.imp.idx);
    REQUIRE(c.instructions[9].b.opcode == AOC_JMP);
    REQUIRE(c.instructions[9].jmp.displacement == t.jmp.jmp.displacement);
    REQUIRE(c.instructions[10].b.opcode == AOC_JIN);
    REQUIRE(c.instructions[10].jin.displacement == t.jin.jin.displacement);
    REQUIRE(c.instructions[11].b.opcode == AOC_IVK);
    REQUIRE(c.instructions[11].ivk.nargs == t.ivk.ivk.nargs);
    REQUIRE(c.instructions[12].b.opcode == AOC_RET);

    REQUIRE(p->num_constants == 3);
    REQUIRE(c.constants[0].b.type == ACT_INTEGER);
    REQUIRE(c.constants[0].integer.val == t.cinteger.integer.val);
    REQUIRE(c.constants[1].b.type == ACT_STRING);
    REQUIRE(c.constants[1].string.ref == t.cstring.string.ref);
    REQUIRE(c.constants[2].b.type == ACT_REAL);
    REQUIRE(c.constants[2].real.val == t.creal.real.val);

    REQUIRE(p->num_imports == 3);
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[0].module), "tim0");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[0].name), "tin0");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[1].module), "tim1");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[1].name), "tin1");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[2].module), "tim2");
    REQUIRE_STR_EQUALS(astring_table_to_string(a->st, c.imports[2].name), "tin2");
}

static void require_equals(aasm_t* a1, aasm_t* a2)
{
    aasm_prototype_t* p1 = aasm_prototype(a1);
    aasm_prototype_t* p2 = aasm_prototype(a2);
    aasm_current_t c1 = aasm_resolve(a1);
    aasm_current_t c2 = aasm_resolve(a2);

    REQUIRE_STR_EQUALS(
        astring_table_to_string(a1->st, p1->source),
        astring_table_to_string(a2->st, p2->source));
    REQUIRE_STR_EQUALS(
        astring_table_to_string(a1->st, p1->symbol),
        astring_table_to_string(a2->st, p2->symbol));

    REQUIRE(p1->num_upvalues == p2->num_upvalues);
    REQUIRE(p1->num_arguments == p2->num_arguments);
    REQUIRE(p1->num_local_vars == p2->num_local_vars);
    REQUIRE(p1->num_nesteds == p2->num_nesteds);

    REQUIRE(p1->num_instructions == p2->num_instructions);
    REQUIRE(
        memcmp(
            c1.instructions,
            c2.instructions,
            p1->num_instructions*sizeof(ainstruction_t)) == 0);

    REQUIRE(p1->num_constants == p2->num_constants);
    for (int32_t i = 0; i < p1->num_constants; ++i) {
        REQUIRE(c1.constants[i].b.type == c2.constants[i].b.type);
        switch (c1.constants[i].b.type) {
        case ACT_INTEGER:
            REQUIRE(c1.constants[i].integer.val == c2.constants[i].integer.val);
            break;
        case ACT_STRING:
            REQUIRE_STR_EQUALS(
                astring_table_to_string(a1->st, c1.constants[i].string.ref),
                astring_table_to_string(a2->st, c2.constants[i].string.ref));
            break;
        case ACT_REAL:
            REQUIRE(c1.constants[i].real.val == c2.constants[i].real.val);
            break;
        }
    }

    REQUIRE(p1->num_imports == p2->num_imports);
    for (int32_t i = 0; i < p2->num_imports; ++i) {
        REQUIRE_STR_EQUALS(
            astring_table_to_string(a1->st, c1.imports[i].module),
            astring_table_to_string(a2->st, c2.imports[i].module));
        REQUIRE_STR_EQUALS(
            astring_table_to_string(a1->st, c1.imports[i].name),
            astring_table_to_string(a2->st, c2.imports[i].name));
    }
}

TEST_CASE("asm_module")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);
    aasm_prototype_t* p = aasm_prototype(&a);

    REQUIRE(p->source == 0);
    REQUIRE(p->symbol == 0);
    REQUIRE(p->num_instructions == 0);
    REQUIRE(p->num_upvalues == 0);
    REQUIRE(p->num_arguments == 0);
    REQUIRE(p->num_local_vars == 0);
    REQUIRE(p->num_constants == 0);
    REQUIRE(p->num_imports == 0);
    REQUIRE(p->num_nesteds == 0);

    num_vs_capacity_check(p);

    aasm_cleanup(&a);
}

TEST_CASE("asm_basic")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);

    basic_test_ctx t;
    basic_add(&a, t);
    basic_check(&a, t);

    aasm_cleanup(&a);
}

TEST_CASE("asm_nested")
{
    aasm_t a;
    aasm_init(&a, &myalloc, NULL);
    REQUIRE(aasm_load(&a, NULL) == AERR_NONE);

    static int32_t PUSH_COUNT = 25;

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            REQUIRE(j == aasm_push(&a));
            basic_test_ctx t;
            basic_add(&a, t);
            basic_check(&a, t);
            REQUIRE(j == aasm_pop(&a));
            aasm_open(&a, j);
            basic_check(&a, t);
            REQUIRE(j == aasm_pop(&a));
        }
        if (i == 0) {
            REQUIRE(PUSH_COUNT == aasm_module_push(&a, "symbol"));
            const aasm_prototype_t* p = aasm_prototype(&a);
            REQUIRE_STR_EQUALS(astring_table_to_string(a.st, p->symbol), "symbol");
        } else {
            REQUIRE(PUSH_COUNT == aasm_push(&a));
        }
    }

    for (int32_t i = ANY_ASM_MAX_NESTED_LEVEL - 1; i >= 0; --i) {
        REQUIRE(PUSH_COUNT == aasm_pop(&a));
    }

    aasm_cleanup(&a);
}

TEST_CASE("asm_save_load")
{
    aasm_t a1;
    aasm_init(&a1, &myalloc, NULL);
    REQUIRE(aasm_load(&a1, NULL) == AERR_NONE);

    static int32_t PUSH_COUNT = 5;

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            REQUIRE(j == aasm_push(&a1));
            basic_test_ctx t;
            basic_add(&a1, t);
            basic_check(&a1, t);
            REQUIRE(j == aasm_pop(&a1));
        }
        REQUIRE(PUSH_COUNT == aasm_push(&a1));
    }

    aasm_save(&a1);

    for (int32_t i = ANY_ASM_MAX_NESTED_LEVEL - 1; i >= 0; --i) {
        REQUIRE(PUSH_COUNT == aasm_pop(&a1));
    }

    aasm_t a2;
    aasm_init(&a2, &myalloc, NULL);
    REQUIRE(aasm_load(&a2, a1.chunk) == AERR_NONE);

    for (int32_t i = 0; i < ANY_ASM_MAX_NESTED_LEVEL; ++i) {
        for (int32_t j = 0; j < PUSH_COUNT; ++j) {
            aasm_open(&a1, j);
            aasm_open(&a2, j);
            require_equals(&a1, &a2);
            REQUIRE(j == aasm_pop(&a1));
            REQUIRE(j == aasm_pop(&a2));
        }
        aasm_open(&a1, PUSH_COUNT);
        aasm_open(&a2, PUSH_COUNT);
    }

    aasm_cleanup(&a1);
    aasm_cleanup(&a2);
}

#endif // ANY_TOOL
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
namespace lean {

void mix(unsigned & a, unsigned & b, unsigned & c) {
    a -= b; a -= c; a ^= (c >> 13);
    b -= c; b -= a; b ^= (a << 8);
    c -= a; c -= b; c ^= (b >> 13);
    a -= b; a -= c; a ^= (c >> 12);
    b -= c; b -= a; b ^= (a << 16);
    c -= a; c -= b; c ^= (b >> 5);
    a -= b; a -= c; a ^= (c >> 3);
    b -= c; b -= a; b ^= (a << 10);
    c -= a; c -= b; c ^= (b >> 15);
}

// Bob Jenkin's hash function.
// http://burtleburtle.net/bob/hash/doobs.html
unsigned hash_str(unsigned length, char const * str, unsigned init_value) {
    unsigned a, b, c, len;

    /* Set up the internal state */
    len = length;
    a = b = 0x9e3779b9;  /* the golden ratio; an arbitrary value */
    c = init_value;      /* the previous hash value */

    /*---------------------------------------- handle most of the key */
    while (len >= 12) {
        a += reinterpret_cast<unsigned const *>(str)[0];
        b += reinterpret_cast<unsigned const *>(str)[1];
        c += reinterpret_cast<unsigned const *>(str)[2];
        mix(a, b, c);
        str += 12; len -= 12;
    }

    /*------------------------------------- handle the last 11 bytes */
    c += length;
    switch (len) {
        /* all the case statements fall through */
    case 11:  c+=((unsigned)str[10] << 24);  /* fall-thru */
    case 10:  c+=((unsigned)str[9] << 16);   /* fall-thru */
    case 9 :  c+=((unsigned)str[8] << 8);    /* fall-thru */
        /* the first byte of c is reserved for the length */
    case 8 :  b+=((unsigned)str[7] << 24);   /* fall-thru */
    case 7 :  b+=((unsigned)str[6] << 16);   /* fall-thru */
    case 6 :  b+=((unsigned)str[5] << 8);    /* fall-thru */
    case 5 :  b+=str[4];                     /* fall-thru */
    case 4 :  a+=((unsigned)str[3] << 24);   /* fall-thru */
    case 3 :  a+=((unsigned)str[2] << 16);   /* fall-thru */
    case 2 :  a+=((unsigned)str[1] << 8);    /* fall-thru */
    case 1 :  a+=str[0];
        /* case 0: nothing left to add */
    }
    mix(a, b, c);
    /*-------------------------------------------- report the result */
    return c;
}

}
<commit_msg>fix(util/hash): add missing cast to unsigned<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
namespace lean {

void mix(unsigned & a, unsigned & b, unsigned & c) {
    a -= b; a -= c; a ^= (c >> 13);
    b -= c; b -= a; b ^= (a << 8);
    c -= a; c -= b; c ^= (b >> 13);
    a -= b; a -= c; a ^= (c >> 12);
    b -= c; b -= a; b ^= (a << 16);
    c -= a; c -= b; c ^= (b >> 5);
    a -= b; a -= c; a ^= (c >> 3);
    b -= c; b -= a; b ^= (a << 10);
    c -= a; c -= b; c ^= (b >> 15);
}

// Bob Jenkin's hash function.
// http://burtleburtle.net/bob/hash/doobs.html
unsigned hash_str(unsigned length, char const * str, unsigned init_value) {
    unsigned a, b, c, len;

    /* Set up the internal state */
    len = length;
    a = b = 0x9e3779b9;  /* the golden ratio; an arbitrary value */
    c = init_value;      /* the previous hash value */

    /*---------------------------------------- handle most of the key */
    while (len >= 12) {
        a += reinterpret_cast<unsigned const *>(str)[0];
        b += reinterpret_cast<unsigned const *>(str)[1];
        c += reinterpret_cast<unsigned const *>(str)[2];
        mix(a, b, c);
        str += 12; len -= 12;
    }

    /*------------------------------------- handle the last 11 bytes */
    c += length;
    switch (len) {
        /* all the case statements fall through */
    case 11:  c+=((unsigned)str[10] << 24);  /* fall-thru */
    case 10:  c+=((unsigned)str[9] << 16);   /* fall-thru */
    case 9 :  c+=((unsigned)str[8] << 8);    /* fall-thru */
        /* the first byte of c is reserved for the length */
    case 8 :  b+=((unsigned)str[7] << 24);   /* fall-thru */
    case 7 :  b+=((unsigned)str[6] << 16);   /* fall-thru */
    case 6 :  b+=((unsigned)str[5] << 8);    /* fall-thru */
    case 5 :  b+=(unsigned)str[4];           /* fall-thru */
    case 4 :  a+=((unsigned)str[3] << 24);   /* fall-thru */
    case 3 :  a+=((unsigned)str[2] << 16);   /* fall-thru */
    case 2 :  a+=((unsigned)str[1] << 8);    /* fall-thru */
    case 1 :  a+=(unsigned)str[0];
        /* case 0: nothing left to add */
    }
    mix(a, b, c);
    /*-------------------------------------------- report the result */
    return c;
}

}
<|endoftext|>


<commit_before>//===- JSONBench - Benchmark the JSONParser implementation ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program executes the JSONParser on differntly sized JSON texts and
// outputs the run time.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/Twine.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/JSONParser.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"

static llvm::cl::opt<bool>
Verify("verify", llvm::cl::desc(
         "Run a quick verification useful for regression testing"),
       llvm::cl::init(false));

static llvm::cl::opt<unsigned>
MemoryLimitMB("memory-limit", llvm::cl::desc(
                "Do not use more megabytes of memory"),
	          llvm::cl::init(1000));

void benchmark(llvm::TimerGroup &Group, llvm::StringRef Name,
               llvm::StringRef JSONText) {
  llvm::Timer BaseLine((Name + ": Loop").str(), Group);
  BaseLine.startTimer();
  char C = 0;
  for (llvm::StringRef::iterator I = JSONText.begin(),
                                 E = JSONText.end();
       I != E; ++I) { C += *I; }
  BaseLine.stopTimer();
  volatile char DontOptimizeOut = C; (void)DontOptimizeOut;

  llvm::Timer Parsing((Name + ": Parsing").str(), Group);
  Parsing.startTimer();
  llvm::JSONParser Parser(JSONText);
  if (!Parser.validate()) {
    llvm::errs() << "Parsing error in JSON parser benchmark.\n";
    exit(1);
  }
  Parsing.stopTimer();
}

std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
  std::string JSONText;
  llvm::raw_string_ostream Stream(JSONText);
  Stream << "[\n";
  size_t MemoryBytes = MemoryMB * 1024 * 1024;
  while (JSONText.size() < MemoryBytes) {
    Stream << " {\n"
           << "  \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
           << "  \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
           << "  \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
           << " }";
    Stream.flush();
    if (JSONText.size() < MemoryBytes) Stream << ",";
    Stream << "\n";
  }
  Stream << "]\n";
  Stream.flush();
  return JSONText;
}

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv);
  llvm::TimerGroup Group("JSON parser benchmark");
  if (Verify) {
    benchmark(Group, "Fast", createJSONText(10, 500));
  } else {
    benchmark(Group, "Small Values", createJSONText(MemoryLimitMB, 5));
    benchmark(Group, "Medium Values", createJSONText(MemoryLimitMB, 500));
    benchmark(Group, "Large Values", createJSONText(MemoryLimitMB, 50000));
  }
  return 0;
}

<commit_msg>Changes the JSON parser to use the SourceMgr.<commit_after>//===- JSONBench - Benchmark the JSONParser implementation ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program executes the JSONParser on differntly sized JSON texts and
// outputs the run time.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/Twine.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/JSONParser.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"

static llvm::cl::opt<bool>
Verify("verify", llvm::cl::desc(
         "Run a quick verification useful for regression testing"),
       llvm::cl::init(false));

static llvm::cl::opt<unsigned>
MemoryLimitMB("memory-limit", llvm::cl::desc(
                "Do not use more megabytes of memory"),
	          llvm::cl::init(1000));

void benchmark(llvm::TimerGroup &Group, llvm::StringRef Name,
               llvm::StringRef JSONText) {
  llvm::Timer BaseLine((Name + ": Loop").str(), Group);
  BaseLine.startTimer();
  char C = 0;
  for (llvm::StringRef::iterator I = JSONText.begin(),
                                 E = JSONText.end();
       I != E; ++I) { C += *I; }
  BaseLine.stopTimer();
  volatile char DontOptimizeOut = C; (void)DontOptimizeOut;

  llvm::Timer Parsing((Name + ": Parsing").str(), Group);
  Parsing.startTimer();
  llvm::SourceMgr SM;
  llvm::JSONParser Parser(JSONText, &SM);
  if (!Parser.validate()) {
    llvm::errs() << "Parsing error in JSON parser benchmark.\n";
    exit(1);
  }
  Parsing.stopTimer();
}

std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
  std::string JSONText;
  llvm::raw_string_ostream Stream(JSONText);
  Stream << "[\n";
  size_t MemoryBytes = MemoryMB * 1024 * 1024;
  while (JSONText.size() < MemoryBytes) {
    Stream << " {\n"
           << "  \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
           << "  \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
           << "  \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
           << " }";
    Stream.flush();
    if (JSONText.size() < MemoryBytes) Stream << ",";
    Stream << "\n";
  }
  Stream << "]\n";
  Stream.flush();
  return JSONText;
}

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv);
  llvm::TimerGroup Group("JSON parser benchmark");
  if (Verify) {
    benchmark(Group, "Fast", createJSONText(10, 500));
  } else {
    benchmark(Group, "Small Values", createJSONText(MemoryLimitMB, 5));
    benchmark(Group, "Medium Values", createJSONText(MemoryLimitMB, 500));
    benchmark(Group, "Large Values", createJSONText(MemoryLimitMB, 50000));
  }
  return 0;
}

<|endoftext|>


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

#include <openspace/util/time.h>

#include <openspace/engine/globals.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/syncbuffer.h>
#include <openspace/util/timemanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/misc/assert.h>
#include <ghoul/misc/profiling.h>
#include <mutex>
#include <string_view>

#include "time_lua.inl"

namespace openspace {

double Time::convertTime(const std::string& time) {
    ghoul_assert(!time.empty(), "timeString must not be empty");
    return SpiceManager::ref().ephemerisTimeFromDate(time);
}

double Time::convertTime(const char* time) {
    return SpiceManager::ref().ephemerisTimeFromDate(time);
}

Time::Time(double secondsJ2000) : _time(secondsJ2000) {}

Time::Time(const std::string& time) :
    _time(SpiceManager::ref().ephemerisTimeFromDate(time))
{}

Time Time::now() {
    Time now;
    time_t secondsSince1970;
    secondsSince1970 = time(nullptr);

    const time_t secondsInAYear = static_cast<time_t>(365.25 * 24 * 60 * 60);
    const double secondsSince2000 = static_cast<double>(
        secondsSince1970 - 30 * secondsInAYear
    );
    now.setTime(secondsSince2000);
    return now;
}

void Time::setTime(double value) {
    _time = value;
}

double Time::j2000Seconds() const {
    return _time;
}

double Time::advanceTime(double delta) {
    _time += delta;
    return _time;
}

void Time::setTime(const std::string& time) {
    _time = SpiceManager::ref().ephemerisTimeFromDate(time);
}

void Time::setTime(const char* time) {
    _time = SpiceManager::ref().ephemerisTimeFromDate(time);
}

std::string_view Time::UTC() const {
    constexpr const char Format[] = "YYYY MON DDTHR:MN:SC.### ::RND";
    char* b = reinterpret_cast<char*>(
        global::memoryManager->TemporaryMemory.allocate(32)
    );
    std::memset(b, 0, 32);

    SpiceManager::ref().dateFromEphemerisTime(_time, b, 32, Format);
    return std::string_view(b);
}

std::string_view Time::ISO8601() const {
    ZoneScoped

    constexpr const char Format[] = "YYYY-MM-DDTHR:MN:SC.###";
    constexpr const int S = sizeof(Format);
    char* b = reinterpret_cast<char*>(
        global::memoryManager->TemporaryMemory.allocate(S)
    );
    std::memset(b, 0, S);

    SpiceManager::ref().dateFromEphemerisTime(_time, b, S, Format);
    return std::string_view(b, S - 1);
}

void Time::ISO8601(char* buffer) const {
    constexpr const char Format[] = "YYYY-MM-DDTHR:MN:SC.###";
    constexpr const int S = sizeof(Format) + 1;
    std::memset(buffer, 0, S);
    SpiceManager::ref().dateFromEphemerisTime(_time, buffer, S, Format);
}

scripting::LuaLibrary Time::luaLibrary() {
    return {
        "time",
        {
            {
                "setTime",
                &luascriptfunctions::time_setTime,
                {},
                "{number, string}",
                "Sets the current simulation time to the "
                "specified value. If the parameter is a number, the value is the number "
                "of seconds past the J2000 epoch. If it is a string, it has to be a "
                "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. "
                "Note: providing time zone using the Z format is not supported. UTC is "
                "assumed."
            },
            {
                "setDeltaTime",
                &luascriptfunctions::time_setDeltaTime,
                {},
                "number",
                "Sets the amount of simulation time that happens "
                "in one second of real time"
            },
            {
                "setDeltaTimeSteps",
                &luascriptfunctions::time_setDeltaTimeSteps,
                {},
                "List of numbers",
                "Sets the list of discrete delta time steps for the simulation speed "
                "that can be quickly jumped between. The list will be sorted to be in "
                "increasing order. A negative verison of each specified time step will "
                "be added per default as well."
            },
            {
                "deltaTime",
                &luascriptfunctions::time_deltaTime,
                {},
                "",
                "Returns the amount of simulated time that passes in one "
                "second of real time"
            },
            {
                "setPause",
                &luascriptfunctions::time_setPause,
                {},
                "bool",
                "Pauses the simulation time or restores the delta time"
            },
            {
                "togglePause",
                &luascriptfunctions::time_togglePause,
                {},
                "",
                "Toggles the pause function, i.e. temporarily setting the delta time to 0"
                " and restoring it afterwards"
            },
            {
                "interpolateTime",
                &luascriptfunctions::time_interpolateTime,
                {},
                "{number, string} [, number]",
                "Sets the current simulation time to the "
                "specified value. If the parameter is a number, the value is the number "
                "of seconds past the J2000 epoch. If it is a string, it has to be a "
                "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. "
                "Note: providing time zone using the Z format is not supported. UTC is "
                "assumed."
            },
            {
                "interpolateTimeRelative",
                &luascriptfunctions::time_interpolateTimeRelative,
                {},
                "number [, number]",
                "Increments the current simulation time by the specified number of "
                "seconds. If a second input value is given, the interpolation is done "
                "over the specified number of seconds."
            },
            {
                "interpolateDeltaTime",
                &luascriptfunctions::time_interpolateDeltaTime,
                {},
                "number [, number]",
                "Sets the amount of simulation time that happens in one second of real "
                "time. If a second input value is given, the interpolation is done "
                "over the specified number of seconds."
            },
            {
                "setNextDeltaTimeStep",
                &luascriptfunctions::time_setNextDeltaTimeStep,
                {},
                "",
                "Immediately set the simulation speed to the first delta time step in "
                "the list that is larger than the current choice of simulation speed, "
                "if any."
            },
            {
                "setPreviousDeltaTimeStep",
                &luascriptfunctions::time_setPreviousDeltaTimeStep,
                {},
                "",
                "Immediately set the simulation speed to the first delta time step in "
                "the list that is smaller than the current choice of simulation speed. "
                "if any."
            },
            {
                "interpolateNextDeltaTimeStep",
                &luascriptfunctions::time_interpolateNextDeltaTimeStep,
                {},
                "[number]",
                "Interpolate the simulation speed to the first delta time step in the "
                "list that is larger than the current simulation speed, if any. If an "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolatePreviousDeltaTimeStep",
                &luascriptfunctions::time_interpolatePreviousDeltaTimeStep,
                {},
                "[number]",
                "Interpolate the simulation speed to the first delta time step in the "
                "list that is smaller than the current simulation speed, if any. If an "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolatePause",
                &luascriptfunctions::time_interpolatePause,
                {},
                "bool [, number]",
                "Pauses the simulation time or restores the delta time. If a second "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolateTogglePause",
                &luascriptfunctions::time_interpolateTogglePause,
                {},
                "[number]",
                "Toggles the pause function, i.e. temporarily setting the delta time to 0"
                " and restoring it afterwards. If an input value is given, the "
                "interpolation is done over the specified number of seconds."
            },
            {
                "currentTime",
                &luascriptfunctions::time_currentTime,
                {},
                "",
                "Returns the current time as the number of seconds since "
                "the J2000 epoch"
            },
            {
                "UTC",
                &luascriptfunctions::time_currentTimeUTC,
                {},
                "",
                "Returns the current time as an ISO 8601 date string "
                "(YYYY-MM-DDTHH:MN:SS)"
            },
            {
                "currentWallTime",
                &luascriptfunctions::time_currentWallTime,
                {},
                "",
                "Returns the current wall time as an ISO 8601 date string "
                "(YYYY-MM-DDTHH-MN-SS) in the UTC timezone"
            },
            {
                "advancedTime",
                &luascriptfunctions::time_advancedTime,
                {},
                "string or number, string or number",
                "Modifies the passed time (first argument) by the delta time (second "
                "argument). The first argument can either be an ISO 8601 date string or "
                "the number of seconds past the J2000 epoch. The second argument can "
                "either be a string of the form [-]XX(s,m,h,d,M,y] with (s)econds, "
                "(m)inutes, (h)ours, (d)ays, (M)onths, and (y)ears as units and an "
                "optional - sign to move backwards in time. If the second argument is a "
                "number, it is interpreted as a number of seconds. The return value is "
                "of the same type as the first argument."
            }
        }
    };
}

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

#include <openspace/util/time.h>

#include <openspace/engine/globals.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/syncbuffer.h>
#include <openspace/util/timemanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/misc/assert.h>
#include <ghoul/misc/profiling.h>
#include <mutex>
#include <string_view>

#include "time_lua.inl"

namespace openspace {

double Time::convertTime(const std::string& time) {
    ghoul_assert(!time.empty(), "timeString must not be empty");
    return SpiceManager::ref().ephemerisTimeFromDate(time);
}

double Time::convertTime(const char* time) {
    return SpiceManager::ref().ephemerisTimeFromDate(time);
}

Time::Time(double secondsJ2000) : _time(secondsJ2000) {}

Time::Time(const std::string& time) :
    _time(SpiceManager::ref().ephemerisTimeFromDate(time))
{}

Time Time::now() {
    Time now;
    time_t secondsSince1970;
    secondsSince1970 = time(nullptr);

    const time_t secondsInAYear = static_cast<time_t>(365.25 * 24 * 60 * 60);
    const double secondsSince2000 = static_cast<double>(
        secondsSince1970 - 30 * secondsInAYear
    );
    now.setTime(secondsSince2000);
    return now;
}

void Time::setTime(double value) {
    _time = value;
}

double Time::j2000Seconds() const {
    return _time;
}

double Time::advanceTime(double delta) {
    _time += delta;
    return _time;
}

void Time::setTime(const std::string& time) {
    _time = SpiceManager::ref().ephemerisTimeFromDate(time);
}

void Time::setTime(const char* time) {
    _time = SpiceManager::ref().ephemerisTimeFromDate(time);
}

std::string_view Time::UTC() const {
    constexpr const char Format[] = "YYYY MON DDTHR:MN:SC.### ::RND";
    char* b = reinterpret_cast<char*>(
        global::memoryManager->TemporaryMemory.allocate(32)
    );
    std::memset(b, 0, 32);

    SpiceManager::ref().dateFromEphemerisTime(_time, b, 32, Format);
    return std::string_view(b);
}

std::string_view Time::ISO8601() const {
    ZoneScoped

    constexpr const char Format[] = "YYYY-MM-DDTHR:MN:SC.###";
    constexpr const int S = sizeof(Format);
    char* b = reinterpret_cast<char*>(
        global::memoryManager->TemporaryMemory.allocate(S)
    );
    std::memset(b, 0, S);

    SpiceManager::ref().dateFromEphemerisTime(_time, b, S, Format);
    return std::string_view(b, S - 1);
}

void Time::ISO8601(char* buffer) const {
    constexpr const char Format[] = "YYYY-MM-DDTHR:MN:SC.###";
    constexpr const int S = sizeof(Format) + 1;
    std::memset(buffer, 0, S);
    SpiceManager::ref().dateFromEphemerisTime(_time, buffer, S, Format);
}

scripting::LuaLibrary Time::luaLibrary() {
    return {
        "time",
        {
            {
                "setTime",
                &luascriptfunctions::time_setTime,
                {},
                "{number, string}",
                "Sets the current simulation time to the "
                "specified value. If the parameter is a number, the value is the number "
                "of seconds past the J2000 epoch. If it is a string, it has to be a "
                "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. "
                "Note: providing time zone using the Z format is not supported. UTC is "
                "assumed."
            },
            {
                "setDeltaTime",
                &luascriptfunctions::time_setDeltaTime,
                {},
                "number",
                "Sets the amount of simulation time that happens "
                "in one second of real time"
            },
            {
                "setDeltaTimeSteps",
                &luascriptfunctions::time_setDeltaTimeSteps,
                {},
                "List of numbers",
                "Sets the list of discrete delta time steps for the simulation speed "
                "that can be quickly jumped between. The list will be sorted to be in "
                "increasing order. A negative verison of each specified time step will "
                "be added per default as well."
            },
            {
                "deltaTime",
                &luascriptfunctions::time_deltaTime,
                {},
                "",
                "Returns the amount of simulated time that passes in one "
                "second of real time"
            },
            {
                "setPause",
                &luascriptfunctions::time_setPause,
                {},
                "bool",
                "Pauses the simulation time or restores the delta time"
            },
            {
                "togglePause",
                &luascriptfunctions::time_togglePause,
                {},
                "",
                "Toggles the pause function, i.e. temporarily setting the delta time to "
                "0 and restoring it afterwards"
            },
            {
                "interpolateTime",
                &luascriptfunctions::time_interpolateTime,
                {},
                "{number, string} [, number]",
                "Sets the current simulation time to the specified value. "
                "If the first parameter is a number, the target is the number "
                "of seconds past the J2000 epoch. If it is a string, it has to be a "
                "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS "
                "(Note: providing time zone using the Z format is not supported. UTC is "
                "assumed). If a second input value is given, the interpolation is done "
                "over the specified number of seconds."
            },
            {
                "interpolateTimeRelative",
                &luascriptfunctions::time_interpolateTimeRelative,
                {},
                "number [, number]",
                "Increments the current simulation time by the specified number of "
                "seconds. If a second input value is given, the interpolation is done "
                "over the specified number of seconds."
            },
            {
                "interpolateDeltaTime",
                &luascriptfunctions::time_interpolateDeltaTime,
                {},
                "number [, number]",
                "Sets the amount of simulation time that happens in one second of real "
                "time. If a second input value is given, the interpolation is done "
                "over the specified number of seconds."
            },
            {
                "setNextDeltaTimeStep",
                &luascriptfunctions::time_setNextDeltaTimeStep,
                {},
                "",
                "Immediately set the simulation speed to the first delta time step in "
                "the list that is larger than the current choice of simulation speed, "
                "if any."
            },
            {
                "setPreviousDeltaTimeStep",
                &luascriptfunctions::time_setPreviousDeltaTimeStep,
                {},
                "",
                "Immediately set the simulation speed to the first delta time step in "
                "the list that is smaller than the current choice of simulation speed. "
                "if any."
            },
            {
                "interpolateNextDeltaTimeStep",
                &luascriptfunctions::time_interpolateNextDeltaTimeStep,
                {},
                "[number]",
                "Interpolate the simulation speed to the first delta time step in the "
                "list that is larger than the current simulation speed, if any. If an "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolatePreviousDeltaTimeStep",
                &luascriptfunctions::time_interpolatePreviousDeltaTimeStep,
                {},
                "[number]",
                "Interpolate the simulation speed to the first delta time step in the "
                "list that is smaller than the current simulation speed, if any. If an "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolatePause",
                &luascriptfunctions::time_interpolatePause,
                {},
                "bool [, number]",
                "Pauses the simulation time or restores the delta time. If a second "
                "input value is given, the interpolation is done over the specified "
                "number of seconds."
            },
            {
                "interpolateTogglePause",
                &luascriptfunctions::time_interpolateTogglePause,
                {},
                "[number]",
                "Toggles the pause function, i.e. temporarily setting the delta time to 0"
                " and restoring it afterwards. If an input value is given, the "
                "interpolation is done over the specified number of seconds."
            },
            {
                "currentTime",
                &luascriptfunctions::time_currentTime,
                {},
                "",
                "Returns the current time as the number of seconds since "
                "the J2000 epoch"
            },
            {
                "UTC",
                &luascriptfunctions::time_currentTimeUTC,
                {},
                "",
                "Returns the current time as an ISO 8601 date string "
                "(YYYY-MM-DDTHH:MN:SS)"
            },
            {
                "currentWallTime",
                &luascriptfunctions::time_currentWallTime,
                {},
                "",
                "Returns the current wall time as an ISO 8601 date string "
                "(YYYY-MM-DDTHH-MN-SS) in the UTC timezone"
            },
            {
                "advancedTime",
                &luascriptfunctions::time_advancedTime,
                {},
                "string or number, string or number",
                "Modifies the passed time (first argument) by the delta time (second "
                "argument). The first argument can either be an ISO 8601 date string or "
                "the number of seconds past the J2000 epoch. The second argument can "
                "either be a string of the form [-]XX(s,m,h,d,M,y] with (s)econds, "
                "(m)inutes, (h)ours, (d)ays, (M)onths, and (y)ears as units and an "
                "optional - sign to move backwards in time. If the second argument is a "
                "number, it is interpreted as a number of seconds. The return value is "
                "of the same type as the first argument."
            }
        }
    };
}

} // namespace openspace
<|endoftext|>


<commit_before>include <stdio.h>

main(int argc, char const *argv[])
{
	int n;
	scanf("%d",&n);
	int lv[n];
	for (int i = 0; i < n; ++i)
	{
		/* code */

		scanf("%d",data+i);
	}

	int f[10000];
	int s[10000];

	char ch;
	int *p=f;
	int cur=0;
	while(scanf("%c",ch)>0){

		if(ch=='='){
			p=s;
			cur=0;
		}

		for (int i = 0; i < data[ch-'a']; ++i)
		{
			p[cur+i]=ch*10000+i;
			cur++;
		}
	}

	for (int i = 0; i < cur; ++i)
	{
		printf("%d",f+i);
	}
	return 0;
}<commit_msg>update uoj2254_queue<commit_after>include <stdio.h>

main(int argc, char const *argv[])
{
	int n;
	scanf("%d",&n);
	int lv[n];
	for (int i = 0; i < n; ++i)
	{
		/* code */

		scanf("%d",data+i);
	}

	int f[10000];
	int s[10000];

	char ch;
	int *p=f;
	int cur=0;
	while(scanf("%c",ch)>0){

		if(ch=='='){
			p=s;
			cur=0;
		}

		for (int i = 0; i < data[ch-'a']; ++i)
		{
			p[cur+i]=ch*10000+i;
			cur++;
		}
	}

	for (int i = 0; i < cur; ++i)
	{
		printf("%d",*(f+i));
	}
	return 0;
}<|endoftext|>


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

#include <cstdio>
#if defined( __APPLE__ )
# include <cstring>
# include <CoreFoundation/CoreFoundation.h>
#elif defined( __linux__ )
# include <uuid/uuid.h>
#elif defined( _WIN32 )
# include <Rpc.h>
#else
# error "Unsupported operating system for generating UUIDs"
#endif

#include "uuid.h"

using namespace std;

namespace zorba {

///////////////////////////////////////////////////////////////////////////////

void uuid::create( uuid *result ) {
#if defined( __APPLE__ )
  CFUUIDRef uuid_ref = CFUUIDCreate( NULL );
  CFUUIDBytes uuid_bytes = CFUUIDGetUUIDBytes( uuid_ref );
  CFRelease( uuid_ref );
  ::memcpy( result, &uuid_bytes, 16 );
#elif defined( __linux__ )
  uuid_generate( (uuid_t)result );
#elif defined( _WIN32 )
  UuidCreateSequential( (UUID*)result );
#endif /* _WIN32 */
}

uuid::variant uuid::get_variant() const {
  value_type const octet8 = data[8];
  if ( (octet8 & 0x80u) == 0x00u )
    return ncs;
  if ( (octet8 & 0xC0u) == 0x80u )
    return rfc4122;
  if ( (octet8 & 0xE0u) == 0xC0u )
    return microsoft;
  return future;
}

uuid::version uuid::get_version() const {
  switch ( data[6] & 0xF0u ) {
    case 0x10u: return time_based;
    case 0x20u: return dce_security;
    case 0x30u: return name_based_md5;
    case 0x40u: return random_number_based;
    case 0x50u: return name_based_sha1;
    default   : return unknown;
  }
}

///////////////////////////////////////////////////////////////////////////////

ostream& operator<<( ostream &os, uuid const &u ) {
  uint32_t const time_low =
    (u.data[0] << 24) | (u.data[1] << 16) | (u.data[2] << 8) | u.data[3];
  uint16_t const time_mid = (u.data[4] << 8) | u.data[5];
  uint16_t const time_hi_and_version = (u.data[6] << 8) | u.data[7];
  uint8_t const clock_seq_hi_and_reserved = u.data[8];
  uint8_t const clock_seq_low = u.data[9];
  uuid::value_type const *const node = u.data + 10;
  char buf[37];
  sprintf(
    buf, "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
    time_low, time_mid, time_hi_and_version, clock_seq_hi_and_reserved,
    clock_seq_low, node[0], node[1], node[2], node[3], node[4], node[5]
  );
  return os << buf;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace zorba

/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */
<commit_msg>Added ->data.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdio>
#if defined( __APPLE__ )
# include <cstring>
# include <CoreFoundation/CoreFoundation.h>
#elif defined( __linux__ )
# include <uuid/uuid.h>
#elif defined( _WIN32 )
# include <Rpc.h>
#else
# error "Unsupported operating system for generating UUIDs"
#endif

#include "uuid.h"

using namespace std;

namespace zorba {

///////////////////////////////////////////////////////////////////////////////

void uuid::create( uuid *result ) {
#if defined( __APPLE__ )
  CFUUIDRef uuid_ref = CFUUIDCreate( NULL );
  CFUUIDBytes uuid_bytes = CFUUIDGetUUIDBytes( uuid_ref );
  CFRelease( uuid_ref );
  ::memcpy( result->data, &uuid_bytes, 16 );
#elif defined( __linux__ )
  uuid_generate( (uuid_t)result->data );
#elif defined( _WIN32 )
  UuidCreateSequential( (UUID*)result->data );
#endif /* _WIN32 */
}

uuid::variant uuid::get_variant() const {
  value_type const octet8 = data[8];
  if ( (octet8 & 0x80u) == 0x00u )
    return ncs;
  if ( (octet8 & 0xC0u) == 0x80u )
    return rfc4122;
  if ( (octet8 & 0xE0u) == 0xC0u )
    return microsoft;
  return future;
}

uuid::version uuid::get_version() const {
  switch ( data[6] & 0xF0u ) {
    case 0x10u: return time_based;
    case 0x20u: return dce_security;
    case 0x30u: return name_based_md5;
    case 0x40u: return random_number_based;
    case 0x50u: return name_based_sha1;
    default   : return unknown;
  }
}

///////////////////////////////////////////////////////////////////////////////

ostream& operator<<( ostream &os, uuid const &u ) {
  uint32_t const time_low =
    (u.data[0] << 24) | (u.data[1] << 16) | (u.data[2] << 8) | u.data[3];
  uint16_t const time_mid = (u.data[4] << 8) | u.data[5];
  uint16_t const time_hi_and_version = (u.data[6] << 8) | u.data[7];
  uint8_t const clock_seq_hi_and_reserved = u.data[8];
  uint8_t const clock_seq_low = u.data[9];
  uuid::value_type const *const node = u.data + 10;
  char buf[37];
  sprintf(
    buf, "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
    time_low, time_mid, time_hi_and_version, clock_seq_hi_and_reserved,
    clock_seq_low, node[0], node[1], node[2], node[3], node[4], node[5]
  );
  return os << buf;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace zorba

/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */
<|endoftext|>