<commit_before>#include "../NacaBnd_test.h"

using namespace dealii;
using namespace NSFEMSolver;

#define dim 2

int main()
{
  Triangulation<dim> triangulation;
  {
    GridIn<dim> grid_in;
    grid_in.attach_triangulation (triangulation);

    std::ifstream input_file ("NACA0012.msh");
    Assert (input_file, ExcFileNotOpen ("NACA0012.msh"));
    grid_in.read_msh (input_file);
  }

  const BndNaca4DigitSymm<dim> NACA_foil_boundary (0012, 1.0);
  std::ofstream fout ("output.out");
  Assert (fout, ExcFileNotOpen ("output.out"));
  fout << std::scientific;
  fout.precision (8);

  for (typename Triangulation<dim>::active_cell_iterator
       cell = triangulation.begin_active();
       cell != triangulation.end();
       ++cell)
    for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
      if (cell->face (f)->at_boundary())
        {
          if (cell->face (f)->boundary_id() == 1)
            {
              typename Boundary<2,2>::FaceVertexNormals face_vertex_normals;
              NACA_foil_boundary.get_normals_at_vertices (cell->face (f),
                                                          face_vertex_normals);
              for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_face; ++v)
                {
                  fout << cell->face (f)->vertex (v) << '\t';
                  fout << face_vertex_normals[v] << std::endl;
                }
            }
        }

  fout.close();
  return (0);
}
<commit_msg>follow dealii update: rename Boundary to Manifold in regTest<commit_after>#include "../NacaBnd_test.h"

using namespace dealii;
using namespace NSFEMSolver;

#define dim 2

int main()
{
  Triangulation<dim> triangulation;
  {
    GridIn<dim> grid_in;
    grid_in.attach_triangulation (triangulation);

    std::ifstream input_file ("NACA0012.msh");
    Assert (input_file, ExcFileNotOpen ("NACA0012.msh"));
    grid_in.read_msh (input_file);
  }

  const BndNaca4DigitSymm<dim> NACA_foil_boundary (0012, 1.0);
  std::ofstream fout ("output.out");
  Assert (fout, ExcFileNotOpen ("output.out"));
  fout << std::scientific;
  fout.precision (8);

  for (typename Triangulation<dim>::active_cell_iterator
       cell = triangulation.begin_active();
       cell != triangulation.end();
       ++cell)
    for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
      if (cell->face (f)->at_boundary())
        {
          if (cell->face (f)->boundary_id() == 1)
            {
              typename Manifold<2,2>::FaceVertexNormals face_vertex_normals;
              NACA_foil_boundary.get_normals_at_vertices (cell->face (f),
                                                          face_vertex_normals);
              for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_face; ++v)
                {
                  fout << cell->face (f)->vertex (v) << '\t';
                  fout << face_vertex_normals[v] << std::endl;
                }
            }
        }

  fout.close();
  return (0);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Facebook, Inc.
 *
 * 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 "thrift/lib/cpp2/async/GssSaslClient.h"

#include "folly/io/Cursor.h"
#include "folly/io/IOBuf.h"
#include "folly/io/IOBufQueue.h"
#include "folly/Memory.h"
#include "folly/MoveWrapper.h"
#include "thrift/lib/cpp/async/TEventBase.h"
#include "thrift/lib/cpp/concurrency/FunctionRunner.h"
#include "thrift/lib/cpp2/protocol/MessageSerializer.h"
#include "thrift/lib/cpp2/gen-cpp2/Sasl_types.h"
#include "thrift/lib/cpp2/gen-cpp2/SaslAuthService.h"
#include "thrift/lib/cpp2/security/KerberosSASLHandshakeClient.h"
#include "thrift/lib/cpp2/security/KerberosSASLHandshakeUtils.h"
#include "thrift/lib/cpp2/security/KerberosSASLThreadManager.h"
#include "thrift/lib/cpp2/security/SecurityLogger.h"
#include "thrift/lib/cpp/concurrency/Exception.h"

#include <memory>

using folly::IOBuf;
using folly::IOBufQueue;
using folly::MoveWrapper;
using apache::thrift::concurrency::Guard;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::FunctionRunner;
using apache::thrift::concurrency::PosixThreadFactory;
using apache::thrift::concurrency::ThreadManager;
using apache::thrift::concurrency::TooManyPendingTasksException;
using apache::thrift::transport::TTransportException;

using namespace std;
using apache::thrift::sasl::SaslStart;
using apache::thrift::sasl::SaslRequest;
using apache::thrift::sasl::SaslReply;
using apache::thrift::sasl::SaslAuthService_authFirstRequest_pargs;
using apache::thrift::sasl::SaslAuthService_authFirstRequest_presult;
using apache::thrift::sasl::SaslAuthService_authNextRequest_pargs;
using apache::thrift::sasl::SaslAuthService_authNextRequest_presult;

namespace apache { namespace thrift {

static const char MECH[] = "krb5";

GssSaslClient::GssSaslClient(apache::thrift::async::TEventBase* evb,
      const std::shared_ptr<SecurityLogger>& logger)
    : SaslClient(logger)
    , evb_(evb)
    , clientHandshake_(new KerberosSASLHandshakeClient(logger))
    , mutex_(new Mutex)
    , saslThreadManager_(nullptr)
    , seqId_(0) {
}

void GssSaslClient::start(Callback *cb) {

  auto channelCallbackUnavailable = channelCallbackUnavailable_;
  auto clientHandshake = clientHandshake_;
  auto mutex = mutex_;
  auto logger = saslLogger_;

  logger->logStart("prepare_first_request");
  auto ew_tm = folly::try_and_catch<TooManyPendingTasksException>([&]() {
    if (!saslThreadManager_) {
      throw TApplicationException(
        "saslThreadManager is not set in GssSaslClient");
    }

    logger->logStart("thread_manager_overhead");
    saslThreadManager_->get()->add(std::make_shared<FunctionRunner>([=] {
      logger->logEnd("thread_manager_overhead");
      MoveWrapper<unique_ptr<IOBuf>> iobuf;
      folly::exception_wrapper ex;

      // This is an optimization. If the channel is unavailable, we have no
      // need to attempt to communicate to the KDC. Note that this is just
      // checking a boolean, so thread safety is not an issue here.
      if (*channelCallbackUnavailable) {
        return;
      }

      ex = folly::try_and_catch<std::exception, TTransportException,
          TProtocolException, TApplicationException, TKerberosException>(
          [&]() {
        clientHandshake->startClientHandshake();
        auto token = clientHandshake->getTokenToSend();

        SaslStart start;
        start.mechanism = MECH;
        if (token != nullptr) {
          start.request.response = *token;
          start.request.__isset.response = true;
        }
        start.__isset.request = true;
        SaslAuthService_authFirstRequest_pargs argsp;
        argsp.saslStart = &start;

        *iobuf = PargsPresultCompactSerialize(
          argsp, "authFirstRequest", T_CALL, seqId_++);
      });

      Guard guard(*mutex);
      // Return if channel is unavailable. Ie. evb_ may not be good.
      if (*channelCallbackUnavailable) {
        return;
      }

      evb_->runInEventBaseThread([=]() mutable {
        if (*channelCallbackUnavailable) {
          return;
        }
        if (ex) {
          cb->saslError(std::move(ex));
          return;
        } else {
          logger->logStart("first_rtt");
          cb->saslSendServer(std::move(*iobuf));
        }
      });
    }));
  });
  if (ew_tm) {
    logger->log("too_many_pending_tasks_in_start");
    cb->saslError(std::move(ew_tm));
  }
}

void GssSaslClient::consumeFromServer(
  Callback *cb, std::unique_ptr<IOBuf>&& message) {
  std::shared_ptr<IOBuf> smessage(std::move(message));

  auto channelCallbackUnavailable = channelCallbackUnavailable_;
  auto clientHandshake = clientHandshake_;
  auto mutex = mutex_;
  auto logger = saslLogger_;

  auto ew_tm = folly::try_and_catch<TooManyPendingTasksException>([&]() {
    saslThreadManager_->get()->add(std::make_shared<FunctionRunner>([=] {
      std::string req_data;
      MoveWrapper<unique_ptr<IOBuf>> iobuf;
      folly::exception_wrapper ex;

      // This is an optimization. If the channel is unavailable, we have no
      // need to attempt to communicate to the KDC. Note that this is just
      // checking a boolean, so thread safety is not an issue here.
      if (*channelCallbackUnavailable) {
        return;
      }

      // Get the input string or outcome status
      std::string input = "";
      bool finished = false;
      // SaslAuthService_authFirstRequest_presult should be structurally
      // identical to SaslAuthService_authNextRequest_presult
      static_assert(sizeof(SaslAuthService_authFirstRequest_presult) ==
                    sizeof(SaslAuthService_authNextRequest_presult),
                    "Types should be structurally identical");
      static_assert(std::is_same<
          decltype(SaslAuthService_authFirstRequest_presult::success),
          decltype(SaslAuthService_authNextRequest_presult::success)>::value,
        "Types should be structurally identical");
      ex = folly::try_and_catch<std::exception, TTransportException,
          TProtocolException, TApplicationException, TKerberosException>(
          [&]() {
        SaslReply reply;
        SaslAuthService_authFirstRequest_presult presult;
        presult.success = &reply;
        string methodName =
          PargsPresultCompactDeserialize(presult, smessage.get(), T_REPLY).first;
        if (methodName != "authFirstRequest" &&
            methodName != "authNextRequest") {
          throw TApplicationException("Bad return method name: " + methodName);
        }
        if (reply.__isset.challenge) {
          input = reply.challenge;
        }
        if (reply.__isset.outcome) {
          finished = reply.outcome.success;
        }

        clientHandshake->handleResponse(input);
        auto token = clientHandshake->getTokenToSend();
        if (clientHandshake->getPhase() == COMPLETE) {
          assert(token == nullptr);
          if (finished != true) {
            throw TKerberosException("Outcome of false returned from server");
          }
        }
        if (token != nullptr) {
          SaslRequest req;
          req.response = *token;
          req.__isset.response = true;
          SaslAuthService_authNextRequest_pargs argsp;
          argsp.saslRequest = &req;
          *iobuf = PargsPresultCompactSerialize(argsp, "authNextRequest",
                                                T_CALL, seqId_++);
        }
      });

      Guard guard(*mutex);
      // Return if channel is unavailable. Ie. evb_ may not be good.
      if (*channelCallbackUnavailable) {
        return;
      }

      auto phase = clientHandshake->getPhase();
      evb_->runInEventBaseThread([=]() mutable {
        if (*channelCallbackUnavailable) {
          return;
        }
        if (ex) {
          cb->saslError(std::move(ex));
          return;
        }
        if (*iobuf && !(*iobuf)->empty()) {
          if (phase == SELECT_SECURITY_LAYER) {
            logger->logStart("third_rtt");
          } else {
            logger->logStart("second_rtt");
          }
          cb->saslSendServer(std::move(*iobuf));
        }
        if (clientHandshake_->isContextEstablished()) {
          cb->saslComplete();
        }
      });
    }));
  });
  if (ew_tm) {
    logger->log("too_many_pending_tasks_in_consume");
    cb->saslError(std::move(ew_tm));
  }
}

std::unique_ptr<IOBuf> GssSaslClient::wrap(std::unique_ptr<IOBuf>&& buf) {
  buf->coalesce();

  std::unique_ptr<IOBuf> wrapped = clientHandshake_->wrapMessage(
    std::move(buf));
  uint32_t wraplen = wrapped->length();

  std::unique_ptr<IOBuf> framing = IOBuf::create(sizeof(wraplen));
  framing->append(sizeof(wraplen));
  framing->appendChain(std::move(wrapped));

  folly::io::RWPrivateCursor c(framing.get());
  c.writeBE<uint32_t>(wraplen);
  return framing;
}

std::unique_ptr<IOBuf> GssSaslClient::unwrap(
  IOBufQueue* q,
  size_t* remaining) {

  folly::io::Cursor c(q->front());
  size_t chainSize = q->front()->computeChainDataLength();
  uint32_t wraplen = 0;

  if (chainSize < sizeof(wraplen)) {
    *remaining = sizeof(wraplen) - chainSize;
    return nullptr;
  }

  wraplen = c.readBE<uint32_t>();

  if (chainSize < sizeof(wraplen) + wraplen) {
    *remaining = sizeof(wraplen) + wraplen - chainSize;
    return nullptr;
  }

  // unwrap the data
  q->trimStart(sizeof(wraplen));
  std::unique_ptr<IOBuf> input = q->split(wraplen);
  input->coalesce();
  std::unique_ptr<IOBuf> output = clientHandshake_->unwrapMessage(
    std::move(input));
  *remaining = 0;
  return output;
}

std::string GssSaslClient::getClientIdentity() const {
  if (clientHandshake_->isContextEstablished()) {
    return clientHandshake_->getEstablishedClientPrincipal();
  } else {
    return "";
  }
}

std::string GssSaslClient::getServerIdentity() const {
  if (clientHandshake_->isContextEstablished()) {
    return clientHandshake_->getEstablishedServicePrincipal();
  } else {
    return "";
  }
}

}}
<commit_msg>Log a few more things<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * 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 "thrift/lib/cpp2/async/GssSaslClient.h"

#include "folly/io/Cursor.h"
#include "folly/io/IOBuf.h"
#include "folly/io/IOBufQueue.h"
#include "folly/Memory.h"
#include "folly/MoveWrapper.h"
#include "thrift/lib/cpp/async/TEventBase.h"
#include "thrift/lib/cpp/concurrency/FunctionRunner.h"
#include "thrift/lib/cpp2/protocol/MessageSerializer.h"
#include "thrift/lib/cpp2/gen-cpp2/Sasl_types.h"
#include "thrift/lib/cpp2/gen-cpp2/SaslAuthService.h"
#include "thrift/lib/cpp2/security/KerberosSASLHandshakeClient.h"
#include "thrift/lib/cpp2/security/KerberosSASLHandshakeUtils.h"
#include "thrift/lib/cpp2/security/KerberosSASLThreadManager.h"
#include "thrift/lib/cpp2/security/SecurityLogger.h"
#include "thrift/lib/cpp/concurrency/Exception.h"

#include <memory>

using folly::IOBuf;
using folly::IOBufQueue;
using folly::MoveWrapper;
using apache::thrift::concurrency::Guard;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::FunctionRunner;
using apache::thrift::concurrency::PosixThreadFactory;
using apache::thrift::concurrency::ThreadManager;
using apache::thrift::concurrency::TooManyPendingTasksException;
using apache::thrift::transport::TTransportException;

using namespace std;
using apache::thrift::sasl::SaslStart;
using apache::thrift::sasl::SaslRequest;
using apache::thrift::sasl::SaslReply;
using apache::thrift::sasl::SaslAuthService_authFirstRequest_pargs;
using apache::thrift::sasl::SaslAuthService_authFirstRequest_presult;
using apache::thrift::sasl::SaslAuthService_authNextRequest_pargs;
using apache::thrift::sasl::SaslAuthService_authNextRequest_presult;

namespace apache { namespace thrift {

static const char MECH[] = "krb5";

GssSaslClient::GssSaslClient(apache::thrift::async::TEventBase* evb,
      const std::shared_ptr<SecurityLogger>& logger)
    : SaslClient(logger)
    , evb_(evb)
    , clientHandshake_(new KerberosSASLHandshakeClient(logger))
    , mutex_(new Mutex)
    , saslThreadManager_(nullptr)
    , seqId_(0) {
}

void GssSaslClient::start(Callback *cb) {

  auto channelCallbackUnavailable = channelCallbackUnavailable_;
  auto clientHandshake = clientHandshake_;
  auto mutex = mutex_;
  auto logger = saslLogger_;

  logger->logStart("prepare_first_request");
  auto ew_tm = folly::try_and_catch<TooManyPendingTasksException>([&]() {
    if (!saslThreadManager_) {
      throw TApplicationException(
        "saslThreadManager is not set in GssSaslClient");
    }

    logger->logStart("thread_manager_overhead");
    saslThreadManager_->get()->add(std::make_shared<FunctionRunner>([=] {
      logger->logEnd("thread_manager_overhead");
      MoveWrapper<unique_ptr<IOBuf>> iobuf;
      folly::exception_wrapper ex;

      // This is an optimization. If the channel is unavailable, we have no
      // need to attempt to communicate to the KDC. Note that this is just
      // checking a boolean, so thread safety is not an issue here.
      if (*channelCallbackUnavailable) {
        return;
      }

      ex = folly::try_and_catch<std::exception, TTransportException,
          TProtocolException, TApplicationException, TKerberosException>(
          [&]() {
        clientHandshake->startClientHandshake();
        auto token = clientHandshake->getTokenToSend();

        SaslStart start;
        start.mechanism = MECH;
        if (token != nullptr) {
          start.request.response = *token;
          start.request.__isset.response = true;
        }
        start.__isset.request = true;
        SaslAuthService_authFirstRequest_pargs argsp;
        argsp.saslStart = &start;

        *iobuf = PargsPresultCompactSerialize(
          argsp, "authFirstRequest", T_CALL, seqId_++);
      });

      Guard guard(*mutex);
      // Return if channel is unavailable. Ie. evb_ may not be good.
      if (*channelCallbackUnavailable) {
        return;
      }

      // Log the overhead around rescheduling the remainder of the
      // handshake at the back of the evb queue.
      logger->logStart("evb_overhead");
      evb_->runInEventBaseThread([=]() mutable {
        logger->logEnd("evb_overhead");
        if (*channelCallbackUnavailable) {
          return;
        }
        if (ex) {
          cb->saslError(std::move(ex));
          return;
        } else {
          logger->logStart("first_rtt");
          cb->saslSendServer(std::move(*iobuf));
        }
      });
    }));
  });
  if (ew_tm) {
    logger->log("too_many_pending_tasks_in_start");
    cb->saslError(std::move(ew_tm));
  }
}

void GssSaslClient::consumeFromServer(
  Callback *cb, std::unique_ptr<IOBuf>&& message) {
  std::shared_ptr<IOBuf> smessage(std::move(message));

  auto channelCallbackUnavailable = channelCallbackUnavailable_;
  auto clientHandshake = clientHandshake_;
  auto mutex = mutex_;
  auto logger = saslLogger_;

  auto ew_tm = folly::try_and_catch<TooManyPendingTasksException>([&]() {
    saslThreadManager_->get()->add(std::make_shared<FunctionRunner>([=] {
      std::string req_data;
      MoveWrapper<unique_ptr<IOBuf>> iobuf;
      folly::exception_wrapper ex;

      // This is an optimization. If the channel is unavailable, we have no
      // need to attempt to communicate to the KDC. Note that this is just
      // checking a boolean, so thread safety is not an issue here.
      if (*channelCallbackUnavailable) {
        return;
      }

      // Get the input string or outcome status
      std::string input = "";
      bool finished = false;
      // SaslAuthService_authFirstRequest_presult should be structurally
      // identical to SaslAuthService_authNextRequest_presult
      static_assert(sizeof(SaslAuthService_authFirstRequest_presult) ==
                    sizeof(SaslAuthService_authNextRequest_presult),
                    "Types should be structurally identical");
      static_assert(std::is_same<
          decltype(SaslAuthService_authFirstRequest_presult::success),
          decltype(SaslAuthService_authNextRequest_presult::success)>::value,
        "Types should be structurally identical");
      ex = folly::try_and_catch<std::exception, TTransportException,
          TProtocolException, TApplicationException, TKerberosException>(
          [&]() {
        SaslReply reply;
        SaslAuthService_authFirstRequest_presult presult;
        presult.success = &reply;
        string methodName =
          PargsPresultCompactDeserialize(presult, smessage.get(), T_REPLY).first;
        if (methodName != "authFirstRequest" &&
            methodName != "authNextRequest") {
          throw TApplicationException("Bad return method name: " + methodName);
        }
        if (reply.__isset.challenge) {
          input = reply.challenge;
        }
        if (reply.__isset.outcome) {
          finished = reply.outcome.success;
        }

        clientHandshake->handleResponse(input);
        auto token = clientHandshake->getTokenToSend();
        if (clientHandshake->getPhase() == COMPLETE) {
          assert(token == nullptr);
          if (finished != true) {
            throw TKerberosException("Outcome of false returned from server");
          }
        }
        if (token != nullptr) {
          SaslRequest req;
          req.response = *token;
          req.__isset.response = true;
          SaslAuthService_authNextRequest_pargs argsp;
          argsp.saslRequest = &req;
          *iobuf = PargsPresultCompactSerialize(argsp, "authNextRequest",
                                                T_CALL, seqId_++);
        }
      });

      Guard guard(*mutex);
      // Return if channel is unavailable. Ie. evb_ may not be good.
      if (*channelCallbackUnavailable) {
        return;
      }

      auto phase = clientHandshake->getPhase();
      evb_->runInEventBaseThread([=]() mutable {
        if (*channelCallbackUnavailable) {
          return;
        }
        if (ex) {
          cb->saslError(std::move(ex));
          return;
        }
        if (*iobuf && !(*iobuf)->empty()) {
          if (phase == SELECT_SECURITY_LAYER) {
            logger->logStart("third_rtt");
          } else {
            logger->logStart("second_rtt");
          }
          cb->saslSendServer(std::move(*iobuf));
        }
        if (clientHandshake_->isContextEstablished()) {
          cb->saslComplete();
        }
      });
    }));
  });
  if (ew_tm) {
    logger->log("too_many_pending_tasks_in_consume");
    cb->saslError(std::move(ew_tm));
  }
}

std::unique_ptr<IOBuf> GssSaslClient::wrap(std::unique_ptr<IOBuf>&& buf) {
  buf->coalesce();

  std::unique_ptr<IOBuf> wrapped = clientHandshake_->wrapMessage(
    std::move(buf));
  uint32_t wraplen = wrapped->length();

  std::unique_ptr<IOBuf> framing = IOBuf::create(sizeof(wraplen));
  framing->append(sizeof(wraplen));
  framing->appendChain(std::move(wrapped));

  folly::io::RWPrivateCursor c(framing.get());
  c.writeBE<uint32_t>(wraplen);
  return framing;
}

std::unique_ptr<IOBuf> GssSaslClient::unwrap(
  IOBufQueue* q,
  size_t* remaining) {

  folly::io::Cursor c(q->front());
  size_t chainSize = q->front()->computeChainDataLength();
  uint32_t wraplen = 0;

  if (chainSize < sizeof(wraplen)) {
    *remaining = sizeof(wraplen) - chainSize;
    return nullptr;
  }

  wraplen = c.readBE<uint32_t>();

  if (chainSize < sizeof(wraplen) + wraplen) {
    *remaining = sizeof(wraplen) + wraplen - chainSize;
    return nullptr;
  }

  // unwrap the data
  q->trimStart(sizeof(wraplen));
  std::unique_ptr<IOBuf> input = q->split(wraplen);
  input->coalesce();
  std::unique_ptr<IOBuf> output = clientHandshake_->unwrapMessage(
    std::move(input));
  *remaining = 0;
  return output;
}

std::string GssSaslClient::getClientIdentity() const {
  if (clientHandshake_->isContextEstablished()) {
    return clientHandshake_->getEstablishedClientPrincipal();
  } else {
    return "";
  }
}

std::string GssSaslClient::getServerIdentity() const {
  if (clientHandshake_->isContextEstablished()) {
    return clientHandshake_->getEstablishedServicePrincipal();
  } else {
    return "";
  }
}

}}
<|endoftext|>


<commit_before>// @(#)root/gpad:$Id$
// Author: Rene Brun   01/07/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TROOT.h"
#include "TBox.h"
#include "TGroupButton.h"
#include "TVirtualX.h"
#include "TDialogCanvas.h"
#include "TCanvas.h"
#include "TText.h"
#include "TInterpreter.h"
#include "TTimer.h"
#include <string.h>

ClassImp(TGroupButton)

//______________________________________________________________________________
//
//  A TGroupButton object is a specialized TButton used in a group of Buttons.
//  When a button from a group of TGroupButtons is selected, all other buttons
//  from the group with the same name are disabled.
//
//  For examples of use of TGroupButton objects, see:
//    TAttFillCanvas, TAttLineCanvas, TAttTextCanvas and TAttMarkerCanvas.

//______________________________________________________________________________
TGroupButton::TGroupButton(): TButton()
{
   // GroupButton default constructor.

   SetFraming();
}

//______________________________________________________________________________
TGroupButton::TGroupButton(const char *groupname, const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t  y2)
           :TButton(title,method,x1,y1,x2,y2)
{
   // GroupButton normal constructor.

   SetName((char*)groupname);
   SetFraming();
}

//______________________________________________________________________________
TGroupButton::~TGroupButton()
{
   // GroupButton default destructor.
}

//______________________________________________________________________________
void TGroupButton::DisplayColorTable(const char *action, Double_t x0, Double_t y0, Double_t wc, Double_t hc)
{
   // Display Color Table in an attribute canvas.

   TGroupButton *colorpad;
   Int_t i, j;
   Int_t color;
   Double_t xlow, ylow, hs, ws;

   // draw colortable buttons
   hs = hc/5;
   ws = wc/10;
   char command[32];
   for (i=0;i<10;i++) {
      xlow = x0 + ws*i;
      for (j=0;j<5;j++) {
         ylow = y0 + hs*j;
         color = 10*j + i + 1;
         snprintf(command,32,"%s(%d)",action,10*j+i+1);
         colorpad = new TGroupButton("Color","",command,xlow, ylow, xlow+0.9*ws, ylow+0.9*hs);
         colorpad->SetFillColor(color);
         colorpad->SetBorderSize(1);
         if (i == 0 && j == 0) colorpad->SetBorderMode(-1);
         colorpad->Draw();
      }
   }
}

//______________________________________________________________________________
void TGroupButton::ExecuteAction()
{
   // Execute action of this button.
   //
   //   If an object has been selected before executing the APPLY button
   //   in the control canvas, The member function and its parameters
   //   for this object is executed via the interpreter.

   TVirtualPad *pad;
   char line[128];
   strlcpy(line,GetMethod(),128);
   char *method = line;
   if(!strlen(line)) return;
   char *params = strchr(method,'(');
   if (params) {
      *params = 0;
      params++;
      char *end = strrchr(params,')');
      if (end) *end = 0;
   }
   TDialogCanvas *canvas = (TDialogCanvas*)GetMother();
   TObject *obj = canvas->GetRefObject();
   if (!obj) return;
   if (strcmp(method,"PIXELS")) {
      obj->Execute(method,params);
   } else {
      TText *text = (TText*)GetListOfPrimitives()->First();
      Int_t npixels = Int_t((YtoPixel(0) - YtoPixel(1))*text->GetTextSize());
      Double_t dy;
      pad = gROOT->GetSelectedPad();
      if (!params) return;
      Int_t nmax = (Int_t)(params-method);
      if (obj->InheritsFrom("TPaveLabel")) {
         TBox *pl = (TBox*)obj;
         dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
         snprintf(params,nmax,"%f",dy/(pl->GetY2() - pl->GetY1()));
         obj->Execute("SetTextSize",params);
      } else {
         if (obj->InheritsFrom("TPave")) {
            dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
            snprintf(params,nmax,"%f",dy/(pad->GetY2() - pad->GetY1()));
            obj->Execute("SetTextSize",params);
         } else {
            snprintf(params,nmax,"%d",npixels);
            obj->Execute("SetTextSizePixels",params);
         }
      }
   }
}

//______________________________________________________________________________
void TGroupButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
   // Execute action corresponding to one event.
   //
   //  This member function is called when a Button object is clicked.

   if (fMother->IsEditable()) {
      TPad::ExecuteEvent(event,px,py);
      return;
   }

   TIter next(gPad->GetCanvas()->GetListOfPrimitives());
   TObject *obj;
   TGroupButton *button;
   TPad *pad;
   TDialogCanvas *canvas;

   switch (event) {

   case kButton1Down:

   case kMouseMotion:

      break;

   case kButton1Motion:

      break;

   case kButton1Up:
      //Clicked on APPLY button?
      if (!strcasecmp(GetName(),"APPLY")) {
         canvas = (TDialogCanvas*)GetMother();
         if (!strcasecmp(GetTitle(),"CLOSE")) {
            canvas->Close();
            return;
         }
         pad = canvas->GetRefPad();
         if (pad) pad->GetCanvas()->FeedbackMode(kFALSE);
         canvas->Apply(GetTitle());   //just in case the apply button executes some code
         if (pad) {
            pad->Modified(kTRUE);
            pad->Update();
         }
         break;
      }
      //Unset other buttons with same name
      while ((obj = next())) {
         if (obj == this) continue;
         if (obj->InheritsFrom(TGroupButton::Class())) {
            button = (TGroupButton*)obj;
            if (!strcmp(button->GetName(),GetName())) {
               if (button->GetBorderMode() < 0) {
                  button->SetBorderMode(1);
                  button->Modified();
               }
            }
         }
      }
      //Set button on
      SetBorderMode(-1);
      Modified();
      gPad->GetCanvas()->Modified();
      gPad->Update();
      break;
   }
}

//______________________________________________________________________________
void TGroupButton::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
   // Save primitive as a C++ statement(s) on output stream out

   TPad *padsav = (TPad*)gPad;
   char quote = '"';
   if (gROOT->ClassSaved(TGroupButton::Class())) {
      out<<"   ";
   } else {
      out<<"   TGroupButton *";
   }
   out<<"button = new TGroupButton("<<quote<<GetName()<<quote<<", "<<quote<<GetTitle()
      <<quote<<","<<quote<<GetMethod()<<quote
      <<","<<fXlowNDC
      <<","<<fYlowNDC
      <<","<<fXlowNDC+fWNDC
      <<","<<fYlowNDC+fHNDC
      <<");"<<endl;

   SaveFillAttributes(out,"button",0,1001);
   SaveLineAttributes(out,"button",1,1,1);
   SaveTextAttributes(out,"button",22,0,1,62,.75);

   if (GetBorderSize() != 2) {
      out<<"   button->SetBorderSize("<<GetBorderSize()<<");"<<endl;
   }
   if (GetBorderMode() != 1) {
      out<<"   button->SetBorderMode("<<GetBorderMode()<<");"<<endl;
   }

   out<<"   button->Draw();"<<endl;
   out<<"   button->cd();"<<endl;

   TIter next(GetListOfPrimitives());
   TObject *obj = next();  //do not save first primitive

   while ((obj = next()))
         obj->SavePrimitive(out, (Option_t *)next.GetOption());

   out<<"   "<<padsav->GetName()<<"->cd();"<<endl;
   padsav->cd();
}
<commit_msg>Fix Coverty report #33226<commit_after>// @(#)root/gpad:$Id$
// Author: Rene Brun   01/07/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TROOT.h"
#include "TBox.h"
#include "TGroupButton.h"
#include "TVirtualX.h"
#include "TDialogCanvas.h"
#include "TCanvas.h"
#include "TText.h"
#include "TInterpreter.h"
#include "TTimer.h"
#include <string.h>

ClassImp(TGroupButton)

//______________________________________________________________________________
//
//  A TGroupButton object is a specialized TButton used in a group of Buttons.
//  When a button from a group of TGroupButtons is selected, all other buttons
//  from the group with the same name are disabled.
//
//  For examples of use of TGroupButton objects, see:
//    TAttFillCanvas, TAttLineCanvas, TAttTextCanvas and TAttMarkerCanvas.

//______________________________________________________________________________
TGroupButton::TGroupButton(): TButton()
{
   // GroupButton default constructor.

   SetFraming();
}

//______________________________________________________________________________
TGroupButton::TGroupButton(const char *groupname, const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t  y2)
           :TButton(title,method,x1,y1,x2,y2)
{
   // GroupButton normal constructor.

   SetName((char*)groupname);
   SetFraming();
}

//______________________________________________________________________________
TGroupButton::~TGroupButton()
{
   // GroupButton default destructor.
}

//______________________________________________________________________________
void TGroupButton::DisplayColorTable(const char *action, Double_t x0, Double_t y0, Double_t wc, Double_t hc)
{
   // Display Color Table in an attribute canvas.

   TGroupButton *colorpad;
   Int_t i, j;
   Int_t color;
   Double_t xlow, ylow, hs, ws;

   // draw colortable buttons
   hs = hc/5;
   ws = wc/10;
   char command[32];
   for (i=0;i<10;i++) {
      xlow = x0 + ws*i;
      for (j=0;j<5;j++) {
         ylow = y0 + hs*j;
         color = 10*j + i + 1;
         snprintf(command,32,"%s(%d)",action,10*j+i+1);
         colorpad = new TGroupButton("Color","",command,xlow, ylow, xlow+0.9*ws, ylow+0.9*hs);
         colorpad->SetFillColor(color);
         colorpad->SetBorderSize(1);
         if (i == 0 && j == 0) colorpad->SetBorderMode(-1);
         colorpad->Draw();
      }
   }
}

//______________________________________________________________________________
void TGroupButton::ExecuteAction()
{
   // Execute action of this button.
   //
   //   If an object has been selected before executing the APPLY button
   //   in the control canvas, The member function and its parameters
   //   for this object is executed via the interpreter.

   TVirtualPad *pad;
   char line[128];
   strlcpy(line,GetMethod(),128);
   char *method = line;
   if(!strlen(line)) return;
   char *params = strchr(method,'(');
   if (params) {
      *params = 0;
      params++;
      char *end = strrchr(params,')');
      if (end) *end = 0;
   }
   TDialogCanvas *canvas = (TDialogCanvas*)GetMother();
   TObject *obj = canvas->GetRefObject();
   if (!obj) return;
   if (strcmp(method,"PIXELS")) {
      obj->Execute(method,params);
   } else {
      TText *text = (TText*)GetListOfPrimitives()->First();
      Int_t npixels = Int_t((YtoPixel(0) - YtoPixel(1))*text->GetTextSize());
      Double_t dy;
      pad = gROOT->GetSelectedPad();
      if (!params) return;
      Int_t nmax = (Int_t)(params-method);
      if (obj->InheritsFrom("TPaveLabel")) {
         TBox *pl = (TBox*)obj;
         dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
         snprintf(params,nmax,"%f",dy/(pl->GetY2() - pl->GetY1()));
         obj->Execute("SetTextSize",params);
      } else {
         if (obj->InheritsFrom("TPave")) {
            dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
            snprintf(params,nmax,"%f",dy/(pad->GetY2() - pad->GetY1()));
            obj->Execute("SetTextSize",params);
         } else {
            snprintf(params,nmax,"%d",npixels);
            obj->Execute("SetTextSizePixels",params);
         }
      }
   }
}

//______________________________________________________________________________
void TGroupButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
   // Execute action corresponding to one event.
   //
   //  This member function is called when a Button object is clicked.

   if (fMother->IsEditable()) {
      TPad::ExecuteEvent(event,px,py);
      return;
   }

   TCanvas *c = gPad->GetCanvas();
   if (!c) return;
   TIter next(c->GetListOfPrimitives());
   TObject *obj;
   TGroupButton *button;
   TPad *pad;
   TDialogCanvas *canvas;

   switch (event) {

   case kButton1Down:

   case kMouseMotion:

      break;

   case kButton1Motion:

      break;

   case kButton1Up:
      //Clicked on APPLY button?
      if (!strcasecmp(GetName(),"APPLY")) {
         canvas = (TDialogCanvas*)GetMother();
         if (!strcasecmp(GetTitle(),"CLOSE")) {
            canvas->Close();
            return;
         }
         pad = canvas->GetRefPad();
         if (pad) pad->GetCanvas()->FeedbackMode(kFALSE);
         canvas->Apply(GetTitle());   //just in case the apply button executes some code
         if (pad) {
            pad->Modified(kTRUE);
            pad->Update();
         }
         break;
      }
      //Unset other buttons with same name
      while ((obj = next())) {
         if (obj == this) continue;
         if (obj->InheritsFrom(TGroupButton::Class())) {
            button = (TGroupButton*)obj;
            if (!strcmp(button->GetName(),GetName())) {
               if (button->GetBorderMode() < 0) {
                  button->SetBorderMode(1);
                  button->Modified();
               }
            }
         }
      }
      //Set button on
      SetBorderMode(-1);
      Modified();
      gPad->GetCanvas()->Modified();
      gPad->Update();
      break;
   }
}

//______________________________________________________________________________
void TGroupButton::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
   // Save primitive as a C++ statement(s) on output stream out

   TPad *padsav = (TPad*)gPad;
   char quote = '"';
   if (gROOT->ClassSaved(TGroupButton::Class())) {
      out<<"   ";
   } else {
      out<<"   TGroupButton *";
   }
   out<<"button = new TGroupButton("<<quote<<GetName()<<quote<<", "<<quote<<GetTitle()
      <<quote<<","<<quote<<GetMethod()<<quote
      <<","<<fXlowNDC
      <<","<<fYlowNDC
      <<","<<fXlowNDC+fWNDC
      <<","<<fYlowNDC+fHNDC
      <<");"<<endl;

   SaveFillAttributes(out,"button",0,1001);
   SaveLineAttributes(out,"button",1,1,1);
   SaveTextAttributes(out,"button",22,0,1,62,.75);

   if (GetBorderSize() != 2) {
      out<<"   button->SetBorderSize("<<GetBorderSize()<<");"<<endl;
   }
   if (GetBorderMode() != 1) {
      out<<"   button->SetBorderMode("<<GetBorderMode()<<");"<<endl;
   }

   out<<"   button->Draw();"<<endl;
   out<<"   button->cd();"<<endl;

   TIter next(GetListOfPrimitives());
   TObject *obj = next();  //do not save first primitive

   while ((obj = next()))
         obj->SavePrimitive(out, (Option_t *)next.GetOption());

   out<<"   "<<padsav->GetName()<<"->cd();"<<endl;
   padsav->cd();
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "videodataoutput.h"
#include "videodataoutput_p.h"
#include "../factory.h"
#include <QtCore/QSize>

#define PHONON_CLASSNAME VideoDataOutput

namespace Phonon
{
namespace Experimental
{

VideoDataOutput::VideoDataOutput(QObject *parent)
    : QObject(parent)
    , AbstractVideoOutput(*new VideoDataOutputPrivate)
{
    K_D(VideoDataOutput);
    d->createBackendObject();
}

void VideoDataOutputPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(VideoDataOutput);
    m_backendObject = Factory::createVideoDataOutput(q);
    if (m_backendObject) {
        setupBackendObject();
    }
}

PHONON_GETTER(int, latency, d->latency)

bool VideoDataOutputPrivate::aboutToDeleteBackendObject()
{
    Q_ASSERT(m_backendObject);

    return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();
}

void VideoDataOutputPrivate::setupBackendObject()
{
    Q_Q(VideoDataOutput);
    Q_ASSERT(m_backendObject);
    //AbstractVideoOutputPrivate::setupBackendObject();

    //QObject::connect(m_backendObject, SIGNAL(frameReady(const Phonon::Experimental::VideoFrame &)),
    //        q, SIGNAL(frameReady(const Phonon::Experimental::VideoFrame &)));

    QObject::connect(m_backendObject, SIGNAL(displayFrame(qint64, qint64)),
                     q, SIGNAL(displayFrame(qint64, qint64)));
    QObject::connect(m_backendObject, SIGNAL(endOfMedia()), q, SIGNAL(endOfMedia()));
}

bool VideoDataOutput::isRunning() const
{
     K_D(const VideoDataOutput);
     //return d->m_backendObject->isRunning();
     return false;
}

VideoFrame VideoDataOutput::frameForTime(qint64 timestamp)
{
    //return d->m_backendObject->frameForTime(timestamp);
}

void VideoDataOutput::setRunning(bool running)
{
    //return d->m_backendObject->setRunning(running);
}

void VideoDataOutput::start()
{
    //return d->m_backendObject->setRunning(true);
}

void VideoDataOutput::stop()
{
    //return d->m_backendObject->setRunning(false);
}

} // namespace Experimental
} // namespace Phonon

#include "videodataoutput.moc"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<commit_msg>seems to be needed to compile on VS 05 as long as the real implementation is missing<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "videodataoutput.h"
#include "videodataoutput_p.h"
#include "../factory.h"
#include <QtCore/QSize>

#define PHONON_CLASSNAME VideoDataOutput

namespace Phonon
{
namespace Experimental
{

VideoDataOutput::VideoDataOutput(QObject *parent)
    : QObject(parent)
    , AbstractVideoOutput(*new VideoDataOutputPrivate)
{
    K_D(VideoDataOutput);
    d->createBackendObject();
}

void VideoDataOutputPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(VideoDataOutput);
    m_backendObject = Factory::createVideoDataOutput(q);
    if (m_backendObject) {
        setupBackendObject();
    }
}

PHONON_GETTER(int, latency, d->latency)

bool VideoDataOutputPrivate::aboutToDeleteBackendObject()
{
    Q_ASSERT(m_backendObject);

    return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();
}

void VideoDataOutputPrivate::setupBackendObject()
{
    Q_Q(VideoDataOutput);
    Q_ASSERT(m_backendObject);
    //AbstractVideoOutputPrivate::setupBackendObject();

    //QObject::connect(m_backendObject, SIGNAL(frameReady(const Phonon::Experimental::VideoFrame &)),
    //        q, SIGNAL(frameReady(const Phonon::Experimental::VideoFrame &)));

    QObject::connect(m_backendObject, SIGNAL(displayFrame(qint64, qint64)),
                     q, SIGNAL(displayFrame(qint64, qint64)));
    QObject::connect(m_backendObject, SIGNAL(endOfMedia()), q, SIGNAL(endOfMedia()));
}

bool VideoDataOutput::isRunning() const
{
     K_D(const VideoDataOutput);
     //return d->m_backendObject->isRunning();
     return false;
}

VideoFrame VideoDataOutput::frameForTime(qint64 timestamp)
{
    //return d->m_backendObject->frameForTime(timestamp);
    return VideoFrame();
}

void VideoDataOutput::setRunning(bool running)
{
    //return d->m_backendObject->setRunning(running);
}

void VideoDataOutput::start()
{
    //return d->m_backendObject->setRunning(true);
}

void VideoDataOutput::stop()
{
    //return d->m_backendObject->setRunning(false);
}

} // namespace Experimental
} // namespace Phonon

#include "videodataoutput.moc"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before>/*== SAGITTARIUS =====================================================================
 * Copyright (c) 2012, Jesse K Medley
 * 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 University of Washington 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 HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE
 * 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.
 */

//== BEGINNING OF CODE ===============================================================

//== INCLUDES ========================================================================

#include "graphfab/core/SagittariusCore.h"
#include "graphfab/sbml/autolayoutSBML.h"
#include "graphfab/diag/error.h"

#include "sbml/SBMLTypes.h"
#include <sstream>

void gf_freeSBMLModel(gf_SBMLModel* lo) {
    if(!lo)
        AN(0, "Not a valid layout pointer"); //null
    SBMLDocument* doc = (SBMLDocument*)lo->pdoc;
    delete doc;
    free(lo);
}

extern "C" gf_SBMLModel* gf_loadSBMLbuf(const char* buf) {
    gf_SBMLModel* r=(gf_SBMLModel*)malloc(sizeof(gf_SBMLModel));
    SBMLReader reader;
    SBMLDocument* doc = reader.readSBMLFromString(buf);

    AN(doc, "Failed to parse SBML"); //not libSBML's documented way of failing, but just in case...

    if(doc->getNumErrors()) {
        #if SAGITTARIUS_DEBUG_LEVEL >= 2
        fprintf(stderr, "Failed to parse SBML\n");
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
            std::cerr << "Error " << i << ": " <<doc->getError(i)->getMessage() << "\n";
        }
        std::stringstream ss;
        ss << "Failed to parse SBML\n";
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
            ss << "Error " << i << ": " <<doc->getError(i)->getMessage() << "\n";
        }
        gf_setError(ss.str().c_str());
        #endif
        // if all are warnings, continue - else abort
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
          if (!doc->getError(i)->isWarning())
            return NULL;
        }
    }

    r->pdoc = doc;
    return r;
}

extern "C" gf_SBMLModel* gf_loadSBMLfile(const char* path) {
    char* buf;
    size_t size=0;
    FILE* file=NULL;
    size_t bytes_read;

    #if SAGITTARIUS_DEBUG_LEVEL >= 2
//     fprintf(stderr, "Specified file is %s\n", path);
    #endif
    file = fopen(path, "rb");
    if(!file)
    {
        #if SAGITTARIUS_DEBUG_LEVEL >= 2
        fprintf(stderr, "Failed to open file\n"); // Assert elided on release build, which we have to use thanks to libsbml
        #endif
        return NULL;
    }
    //get t3h s!z3
    fseek(file, 0, SEEK_END);
    size = ftell(file);
    rewind(file);
    #if SAGITTARIUS_DEBUG_LEVEL >= 2
//     fprintf(stderr, "File size is %lu\n", size);
    #endif
    assert(size > 0);

    //allocated buffer
    assert(sizeof(char) == 1 && "char must be one byte wide");
    buf=(char*)malloc(size+1); //one extra byte for null char
    assert(buf && "Failed to allocate buffer");
    //read the whole file at once
    bytes_read = fread(buf, 1, size, file);
    assert(bytes_read == size && "Failed to read whole file (wrong size specified?)");
    //trip EOF indicator
    fgetc(file);
    assert(feof(file) && "EOF Expected");
    buf[size] = '\0'; //terminating null char

    /*close*/
    fclose(file);

    gf_SBMLModel* mod = gf_loadSBMLbuf(buf);

    free(buf);

    return mod;
}

<commit_msg>add more error checking to gf_loadSBMLfile<commit_after>/*== SAGITTARIUS =====================================================================
 * Copyright (c) 2012, Jesse K Medley
 * 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 University of Washington 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 HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE
 * 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.
 */

//== BEGINNING OF CODE ===============================================================

//== INCLUDES ========================================================================

#include "graphfab/core/SagittariusCore.h"
#include "graphfab/sbml/autolayoutSBML.h"
#include "graphfab/diag/error.h"

#include "sbml/SBMLTypes.h"
#include <sstream>

void gf_freeSBMLModel(gf_SBMLModel* lo) {
    if(!lo)
        AN(0, "Not a valid layout pointer"); //null
    SBMLDocument* doc = (SBMLDocument*)lo->pdoc;
    delete doc;
    free(lo);
}

extern "C" gf_SBMLModel* gf_loadSBMLbuf(const char* buf) {
    gf_SBMLModel* r=(gf_SBMLModel*)malloc(sizeof(gf_SBMLModel));
    SBMLReader reader;
    SBMLDocument* doc = reader.readSBMLFromString(buf);

    AN(doc, "Failed to parse SBML"); //not libSBML's documented way of failing, but just in case...

    if(doc->getNumErrors()) {
        #if SAGITTARIUS_DEBUG_LEVEL >= 2
        fprintf(stderr, "Failed to parse SBML\n");
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
            std::cerr << "Error " << i << ": " <<doc->getError(i)->getMessage() << "\n";
        }
        std::stringstream ss;
        ss << "Failed to parse SBML\n";
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
            ss << "Error " << i << ": " <<doc->getError(i)->getMessage() << "\n";
        }
        gf_setError(ss.str().c_str());
        #endif
        // if all are warnings, continue - else abort
        for(unsigned int i=0; i<doc->getNumErrors(); ++i) {
          if (!doc->getError(i)->isWarning())
            return NULL;
        }
    }

    r->pdoc = doc;
    return r;
}

extern "C" gf_SBMLModel* gf_loadSBMLfile(const char* path) {
  char* buf;
  size_t size=0;
  FILE* file=NULL;
  size_t bytes_read;

  try {

    file = fopen(path, "rb");
    if(!file)
      SBNW_THROW(InternalCheckFailureException, "Failed to open file", "gf_loadSBMLfile");

    //get t3h s!z3
    fseek(file, 0, SEEK_END);
    size = ftell(file);
    rewind(file);
    #if SAGITTARIUS_DEBUG_LEVEL >= 2
  //     fprintf(stderr, "File size is %lu\n", size);
    #endif
    assert(size > 0);

    //allocated buffer
    if (sizeof(char) != 1)
      SBNW_THROW(InternalCheckFailureException, "char must be one byte wide", "gf_loadSBMLfile");
    buf=(char*)malloc(size+1); //one extra byte for null char
    if (!buf)
      SBNW_THROW(InternalCheckFailureException, "Failed to allocate buffer", "gf_loadSBMLfile");
    //read the whole file at once
    bytes_read = fread(buf, 1, size, file);
    if (bytes_read != size)
      SBNW_THROW(InternalCheckFailureException, "Failed to read whole file (wrong size specified?)", "gf_loadSBMLfile");
    //trip EOF indicator
    fgetc(file);
    if (!feof(file))
      SBNW_THROW(InternalCheckFailureException, "EOF Expected", "gf_loadSBMLfile");
    buf[size] = '\0'; //terminating null char

    /*close*/
    fclose(file);

    gf_SBMLModel* mod = gf_loadSBMLbuf(buf);

    free(buf);

    return mod;

  } catch (const Exception& e) {
    gf_setError( e.getReport().c_str() );
    return NULL;
  }
}

<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
 * Copyright (C) 2008 Charles Huet <packadal@gmail.com>
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "graphics/material.h"
#include "graphics/manager.h"
#include "graphics/renderwidget.h"

#include <QtGui/QApplication>
#include <shader.h>
#include <backend.h>

int main( int argc, char* argv[] )
{
    QApplication app( argc, argv );

    //GluonGraphics::RenderWidget widget;
    //widget.show();

    //GluonGraphics::Material* mat = new GluonGraphics::Material();
    //GluonGraphics::Material* mat = GluonGraphics::Manager::instance()->createResource< GluonGraphics::Material >( "Main" );
    //createResource< GluonGraphics::Material >( "Main" );
    //GluonGraphics::Manager::instance()->destroyResource< GluonGraphics::Material >( "Main" );
    //qDebug() << GluonGraphics::Manager::instance()->backend( widget )->information( GluonGraphics::Backend::VerboseInformation );

    GluonGraphics::RenderWidget widget;
    widget.show();
    //app.exec();

    //delete widget;

    //Create a widget to render the graphics on.
//     GluonGraphics::RenderWidget* widget = new GluonGraphics::RenderWidget();
//     widget->show();

//     GluonGraphics::World* world = GluonGraphics::Manager::instance()->createWorld();

    //Create a camera to view the scene from.
//     GluonGraphics::Camera* cam = world->createEntity< GluonGraphics::Camera* >();

    //Set the viewport
//     cam->frustrum()->setOrthographic( -5.f, 5.f, -5.f, 5.f, -5.f, 5.f );

    //Activate the new camera
    //GluonGraphics::Manager::instance()->setActiveCamera( cam );

    //Create an item to display
//     GluonGraphics::Item* item = GluonGraphics::Engine::instance()->createItem( "default" );
//
//     QMatrix4x4 mat;
//     mat.translate( -1.5f, -1.5f );
//     item->setTransform( mat );
//
//     item = GluonGraphics::Engine::instance()->createItem( "default" );
//     mat.translate( 3.f, 3.f );
//     item->setTransform( mat );
//
//     QTimer::singleShot( 0, widget, SLOT(updateGL()) );
// return app.exec();

    app.exec();
}
<commit_msg>Create and load a texture in the example.<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
 * Copyright (C) 2008 Charles Huet <packadal@gmail.com>
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "graphics/material.h"
#include "graphics/manager.h"
#include "graphics/renderwidget.h"

#include <QtGui/QApplication>
#include <shader.h>
#include <backend.h>
#include <texture.h>
#include <core/directoryprovider.h>

int main( int argc, char* argv[] )
{
    QApplication app( argc, argv );

    //GluonGraphics::RenderWidget widget;
    //widget.show();

    //GluonGraphics::Material* mat = new GluonGraphics::Material();
    //GluonGraphics::Material* mat = GluonGraphics::Manager::instance()->createResource< GluonGraphics::Material >( "Main" );
    //createResource< GluonGraphics::Material >( "Main" );
    //GluonGraphics::Manager::instance()->destroyResource< GluonGraphics::Material >( "Main" );
    //qDebug() << GluonGraphics::Manager::instance()->backend( widget )->information( GluonGraphics::Backend::VerboseInformation );
    GluonGraphics::RenderWidget widget;
    widget.show();
    //app.exec();

    GluonGraphics::Texture* texture = GluonGraphics::Manager::instance()->createResource< GluonGraphics::Texture >( "test" );
    texture->load( GluonCore::DirectoryProvider::instance()->dataDirectory() + "/gluon/defaults/default.png" );

    //delete widget;

    //Create a widget to render the graphics on.
//     GluonGraphics::RenderWidget* widget = new GluonGraphics::RenderWidget();
//     widget->show();

//     GluonGraphics::World* world = GluonGraphics::Manager::instance()->createWorld();

    //Create a camera to view the scene from.
//     GluonGraphics::Camera* cam = world->createEntity< GluonGraphics::Camera* >();

    //Set the viewport
//     cam->frustrum()->setOrthographic( -5.f, 5.f, -5.f, 5.f, -5.f, 5.f );

    //Activate the new camera
    //GluonGraphics::Manager::instance()->setActiveCamera( cam );

    //Create an item to display
//     GluonGraphics::Item* item = GluonGraphics::Engine::instance()->createItem( "default" );
//
//     QMatrix4x4 mat;
//     mat.translate( -1.5f, -1.5f );
//     item->setTransform( mat );
//
//     item = GluonGraphics::Engine::instance()->createItem( "default" );
//     mat.translate( 3.f, 3.f );
//     item->setTransform( mat );
//
//     QTimer::singleShot( 0, widget, SLOT(updateGL()) );
// return app.exec();

    app.exec();
}
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Brad van der Laan
 *
 * 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 <QCoreApplication>
#include <QFileInfo>
#include <functional>
#include "CommandLineInterface.hpp"
#include "InputArgument.hpp"

using namespace Taranis;
using action_callback = std::function<void(QVariant)>;

const QString CommandLineInterface::VERSIONARGUMENT = "version";

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface::CommandLineInterface(const QString applicationName, QStringList arguments, QStringList acceptedArgumentPrefixes)
    : m_applicationName(applicationName),
      m_inputArguments( arguments ),
      m_acceptedArgumentPrefixs( acceptedArgumentPrefixes )
{
    addHelpArguments();
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface::~CommandLineInterface()
{
//    qDeleteAll( m_arguments );
    m_arguments.clear();
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::name() const
{
    return m_applicationName;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::version() const
{
    return m_version;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::description() const
{
    return m_description;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QStringList CommandLineInterface::arguments() const
{
    return m_arguments.keys();
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface& CommandLineInterface::process()
{
    foreach( QString a, m_inputArguments )
    {
        InputArgument arg( a, m_acceptedArgumentPrefixs );
        if ( arg.isValid() )
        {
            QString key = arg.name().toLower();
            if ( m_arguments.contains( key ) )
            {
                m_arguments[key]->callback()(arg.value());
            }
        }
    }
    return *this;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QVariant CommandLineInterface::operator[](const QString key) const
{
    if ( m_arguments.contains(key) )
    {
        return m_arguments[key]->value();
    }
    else
    {
        return QVariant();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterfaceBuilder CommandLineInterface::build()
{
    return CommandLineInterfaceBuilder();
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::addArgument(Argument* arg)
{
    m_arguments[arg->name()] = arg;
    if ( arg->hasShortName() )
    {
        m_arguments[arg->shortName()] = arg;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setVersion(const QString version)
{
    m_version = version;
    if ( m_version.isEmpty() )
    {
        delete m_arguments.value(VERSIONARGUMENT);
        m_arguments.remove(VERSIONARGUMENT);
    }
    else
    {
        action_callback versionCallback = std::bind( &CommandLineInterface::doVersionAction, this );
        addArgument( new Argument( VERSIONARGUMENT, "Display version information and exit", ArgumentType::Action, versionCallback) );
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setName(const QString name)
{
    m_applicationName = name;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setDescription(const QString description)
{
    m_description = description;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::addHelpArguments()
{
    action_callback helpCallback = std::bind( &CommandLineInterface::doHelpAction, this );
    addArgument( new Argument( "help", "Display this help and exit", ArgumentType::Action, helpCallback) );
    addArgument( new Argument( "?", "Display this help and exit", ArgumentType::Action, helpCallback) );
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setValue(const QString key, const QVariant value)
{
    if ( m_arguments.contains(key) )
    {
        m_arguments[key]->setValue(value);
    }
    else
    {
        Q_ASSERT_X( false, "CommandLineInterface::setValue", QString("No argument with name %1").arg(key).toLatin1().data() );
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::helpMessage() const
{
    QString applicationExecutable = QFileInfo( QCoreApplication::applicationFilePath() ).fileName();
    QString message = generateTitle();

    if ( !message.isEmpty() )
    {
        message += QString(message.length()-1, '=') + QStringLiteral("\n");
    }

    if ( !m_description.isEmpty() )
    {
        message += m_description + QStringLiteral("\n\n");
    }

    message += QString("Usage: %1 [OPTION]\n\n").arg(applicationExecutable);

    QStringList filterArgumentAliases;
    foreach( Argument* arg, m_arguments.values() )
    {
        if ( filterArgumentAliases.contains( arg->name() ) ) continue;
        if ( arg->hasShortName() )
        {
            message += QString( "  -%1, --%2").arg(arg->shortName()).arg(arg->name());
        }
        else
        {
            message += QString( "  -%1").arg(arg->name());
        }

        message += QString("\t%1\n").arg(arg->description());
        filterArgumentAliases.append( arg->name());
    }
    return message;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::generateTitle() const
{
    QString message;
    if ( !m_applicationName.isEmpty() && !m_version.isEmpty() )
    {
        message += QString("%1 - Version %2\n").arg(m_applicationName).arg(m_version);
    }
    else if ( !m_applicationName.isEmpty() )
    {
        message += QString("%1\n").arg(m_applicationName);
    }
    else if ( !m_version.isEmpty() )
    {
        message += QString("Version %1\n").arg(m_version);
    }

    return message;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::doHelpAction() const
{
    printf( "%s", helpMessage().toLatin1().data() );
    QCoreApplication::exit(0);
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::doVersionAction() const
{
    printf( "%s", generateTitle().toLatin1().data() );
    QCoreApplication::exit(0);
}
<commit_msg>Change QCoreApplication::exit(0) to just exit(0) for the doVersion and doHelp methods. I didn't think about it, but the CommandLineInterface will process the doVersion and doHelp methods _before_ the event loop is spun up. QCoreApplication::exit(int) only terminates the event loop and since we typically spin up the event loop like 'return app.exec();' that would terminate the application. However these methods are executed before the event loop is spun up so if we really want the application to terminate after they are processed we need to call the standard exit(int) method instead which does explicitly terminate the applicaiton.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Brad van der Laan
 *
 * 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 <QCoreApplication>
#include <QFileInfo>
#include <functional>
#include "CommandLineInterface.hpp"
#include "InputArgument.hpp"

using namespace Taranis;
using action_callback = std::function<void(QVariant)>;

const QString CommandLineInterface::VERSIONARGUMENT = "version";

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface::CommandLineInterface(const QString applicationName, QStringList arguments, QStringList acceptedArgumentPrefixes)
    : m_applicationName(applicationName),
      m_inputArguments( arguments ),
      m_acceptedArgumentPrefixs( acceptedArgumentPrefixes )
{
    addHelpArguments();
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface::~CommandLineInterface()
{
//    qDeleteAll( m_arguments );
    m_arguments.clear();
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::name() const
{
    return m_applicationName;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::version() const
{
    return m_version;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::description() const
{
    return m_description;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QStringList CommandLineInterface::arguments() const
{
    return m_arguments.keys();
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterface& CommandLineInterface::process()
{
    foreach( QString a, m_inputArguments )
    {
        InputArgument arg( a, m_acceptedArgumentPrefixs );
        if ( arg.isValid() )
        {
            QString key = arg.name().toLower();
            if ( m_arguments.contains( key ) )
            {
                m_arguments[key]->callback()(arg.value());
            }
        }
    }
    return *this;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QVariant CommandLineInterface::operator[](const QString key) const
{
    if ( m_arguments.contains(key) )
    {
        return m_arguments[key]->value();
    }
    else
    {
        return QVariant();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
CommandLineInterfaceBuilder CommandLineInterface::build()
{
    return CommandLineInterfaceBuilder();
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::addArgument(Argument* arg)
{
    m_arguments[arg->name()] = arg;
    if ( arg->hasShortName() )
    {
        m_arguments[arg->shortName()] = arg;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setVersion(const QString version)
{
    m_version = version;
    if ( m_version.isEmpty() )
    {
        delete m_arguments.value(VERSIONARGUMENT);
        m_arguments.remove(VERSIONARGUMENT);
    }
    else
    {
        action_callback versionCallback = std::bind( &CommandLineInterface::doVersionAction, this );
        addArgument( new Argument( VERSIONARGUMENT, "Display version information and exit", ArgumentType::Action, versionCallback) );
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setName(const QString name)
{
    m_applicationName = name;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setDescription(const QString description)
{
    m_description = description;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::addHelpArguments()
{
    action_callback helpCallback = std::bind( &CommandLineInterface::doHelpAction, this );
    addArgument( new Argument( "help", "Display this help and exit", ArgumentType::Action, helpCallback) );
    addArgument( new Argument( "?", "Display this help and exit", ArgumentType::Action, helpCallback) );
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::setValue(const QString key, const QVariant value)
{
    if ( m_arguments.contains(key) )
    {
        m_arguments[key]->setValue(value);
    }
    else
    {
        Q_ASSERT_X( false, "CommandLineInterface::setValue", QString("No argument with name %1").arg(key).toLatin1().data() );
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::helpMessage() const
{
    QString applicationExecutable = QFileInfo( QCoreApplication::applicationFilePath() ).fileName();
    QString message = generateTitle();

    if ( !message.isEmpty() )
    {
        message += QString(message.length()-1, '=') + QStringLiteral("\n");
    }

    if ( !m_description.isEmpty() )
    {
        message += m_description + QStringLiteral("\n\n");
    }

    message += QString("Usage: %1 [OPTION]\n\n").arg(applicationExecutable);

    QStringList filterArgumentAliases;
    foreach( Argument* arg, m_arguments.values() )
    {
        if ( filterArgumentAliases.contains( arg->name() ) ) continue;
        if ( arg->hasShortName() )
        {
            message += QString( "  -%1, --%2").arg(arg->shortName()).arg(arg->name());
        }
        else
        {
            message += QString( "  -%1").arg(arg->name());
        }

        message += QString("\t%1\n").arg(arg->description());
        filterArgumentAliases.append( arg->name());
    }
    return message;
}

////////////////////////////////////////////////////////////////////////////////////////////////
QString CommandLineInterface::generateTitle() const
{
    QString message;
    if ( !m_applicationName.isEmpty() && !m_version.isEmpty() )
    {
        message += QString("%1 - Version %2\n").arg(m_applicationName).arg(m_version);
    }
    else if ( !m_applicationName.isEmpty() )
    {
        message += QString("%1\n").arg(m_applicationName);
    }
    else if ( !m_version.isEmpty() )
    {
        message += QString("Version %1\n").arg(m_version);
    }

    return message;
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::doHelpAction() const
{
    printf( "%s", helpMessage().toLatin1().data() );
    exit(0);
}

////////////////////////////////////////////////////////////////////////////////////////////////
void CommandLineInterface::doVersionAction() const
{
    printf( "%s", generateTitle().toLatin1().data() );
    exit(0);
}
<|endoftext|>


<commit_before>/**
 *  @file column_types_test.cpp
 *  @date 09.01.2015
 *  @author mkoenig
 */

#include "pydbc/column_types.h"

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit_toolbox/helpers/is_abstract_base_class.h>

#include "mock_classes.h"
#include <sqlext.h>

class column_types_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( column_types_test );

	CPPUNIT_TEST( long_column_bound_on_construction );
	CPPUNIT_TEST( string_column_bound_on_construction );

CPPUNIT_TEST_SUITE_END();

public:

	void long_column_bound_on_construction();
	void string_column_bound_on_construction();

};

// Registers the fixture with the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( column_types_test );

using pydbc_test::mock_statement;

void column_types_test::long_column_bound_on_construction()
{
	std::size_t const column_index = 42;
	auto const buffer_type = SQL_C_SBIGINT;
	mock_statement statement;

	EXPECT_CALL(statement, do_bind_column(column_index, buffer_type, testing::_)).Times(1);
	pydbc::long_column column(statement, column_index);
}

void column_types_test::string_column_bound_on_construction()
{
	std::size_t const column_index = 42;
	auto const buffer_type = SQL_CHAR;
	mock_statement statement;

	EXPECT_CALL(statement, do_bind_column(column_index, buffer_type, testing::_)).Times(1);
	pydbc::string_column column(statement, column_index);
}

<commit_msg>Improved on column types tests<commit_after>/**
 *  @file column_types_test.cpp
 *  @date 09.01.2015
 *  @author mkoenig
 */

#include "pydbc/column_types.h"

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit_toolbox/helpers/is_abstract_base_class.h>

#include "mock_classes.h"
#include <sqlext.h>
#include <boost/variant/get.hpp>
#include <cstring>

class column_types_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( column_types_test );

	CPPUNIT_TEST( long_column_get_field );
	CPPUNIT_TEST( string_column_get_field );

CPPUNIT_TEST_SUITE_END();

public:

	void long_column_get_field();
	void string_column_get_field();

};

// Registers the fixture with the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( column_types_test );

using pydbc_test::mock_statement;

namespace {
	/**
	* Change the address of the given target_pointer to point to the third argument of the mocked function
	*/
	ACTION_P(store_pointer_to_buffer_in, target_pointer) {
		*target_pointer = &arg2;
	}

	std::size_t const column_index = 42;
}

namespace {
	void fill_buffer_with_value(cpp_odbc::multi_value_buffer & buffer, long value)
	{
		auto element = buffer[0];
		memcpy(element.data_pointer, &value, sizeof(long));
		element.indicator = sizeof(long);
	}
}

void column_types_test::long_column_get_field()
{
	long const expected = 12345;
	auto const buffer_type = SQL_C_SBIGINT;
	mock_statement statement;

	cpp_odbc::multi_value_buffer * buffer = nullptr;
	EXPECT_CALL(statement, do_bind_column(column_index, buffer_type, testing::_))
		.WillOnce(store_pointer_to_buffer_in(&buffer));

	pydbc::long_column column(statement, column_index);
	CPPUNIT_ASSERT( buffer != nullptr);

	fill_buffer_with_value(*buffer, expected);
	CPPUNIT_ASSERT_EQUAL(expected, boost::get<long>(column.get_field()));
}

namespace {
	void fill_buffer_with_value(cpp_odbc::multi_value_buffer & buffer, std::string const & value)
	{
		auto element = buffer[0];
		memcpy(element.data_pointer, value.data(), value.size() + 1);
		element.indicator = value.size();
	}
}

void column_types_test::string_column_get_field()
{
	std::string const expected("this is a test string");
	auto const buffer_type = SQL_CHAR;
	mock_statement statement;

	cpp_odbc::multi_value_buffer * buffer = nullptr;
	EXPECT_CALL(statement, do_bind_column(column_index, buffer_type, testing::_))
		.WillOnce(store_pointer_to_buffer_in(&buffer));

	pydbc::string_column column(statement, column_index);
	CPPUNIT_ASSERT( buffer != nullptr);

	fill_buffer_with_value(*buffer, expected);
	CPPUNIT_ASSERT_EQUAL(expected, boost::get<std::string>(column.get_field()));
}

<|endoftext|>


<commit_before>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===//
//
// This file implements the top-level functionality for the LLVM interpreter.
// This interpreter is designed to be a very simple, portable, inefficient
// interpreter.
//
//===----------------------------------------------------------------------===//

#include "Interpreter.h"
#include "llvm/Target/TargetMachineImpls.h"

/// createInterpreter - Create a new interpreter object.  This can never fail.
///
ExecutionEngine *ExecutionEngine::createInterpreter(Module *M,
						    unsigned Config,
						    bool DebugMode,
						    bool TraceMode) {
  return new Interpreter(M, Config, DebugMode, TraceMode);
}

//===----------------------------------------------------------------------===//
// Interpreter ctor - Initialize stuff
//
Interpreter::Interpreter(Module *M, unsigned Config,
			 bool DebugMode, bool TraceMode)
  : ExecutionEngine(M), ExitCode(0), Debug(DebugMode), Trace(TraceMode),
    CurFrame(-1), TD("lli", (Config & TM::EndianMask) == TM::LittleEndian,
		     1, 4,
		     (Config & TM::PtrSizeMask) == TM::PtrSize64 ? 8 : 4,
		     (Config & TM::PtrSizeMask) == TM::PtrSize64 ? 8 : 4) {

  setTargetData(TD);
  // Initialize the "backend"
  initializeExecutionEngine();
  initializeExternalMethods();
  CW.setModule(M);  // Update Writer
}

/// run - Start execution with the specified function and arguments.
///
int Interpreter::run(const std::string &MainFunction,
		     const std::vector<std::string> &Args) {
  // Start interpreter into the main function...
  //
  if (!callMainMethod(MainFunction, Args) && !Debug) {
    // If not in debug mode and if the call succeeded, run the code now...
    run();
  }

  // If debug mode, allow the user to interact... also, if the user pressed
  // ctrl-c or execution hit an error, enter the event loop...
  if (Debug || isStopped())
    handleUserInput();
  return ExitCode;
}

<commit_msg>MAke sure that LLI properly configures align_of(double)<commit_after>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===//
//
// This file implements the top-level functionality for the LLVM interpreter.
// This interpreter is designed to be a very simple, portable, inefficient
// interpreter.
//
//===----------------------------------------------------------------------===//

#include "Interpreter.h"
#include "llvm/Target/TargetMachineImpls.h"

/// createInterpreter - Create a new interpreter object.  This can never fail.
///
ExecutionEngine *ExecutionEngine::createInterpreter(Module *M,
						    unsigned Config,
						    bool DebugMode,
						    bool TraceMode) {
  return new Interpreter(M, Config, DebugMode, TraceMode);
}

//===----------------------------------------------------------------------===//
// Interpreter ctor - Initialize stuff
//
Interpreter::Interpreter(Module *M, unsigned Config,
			 bool DebugMode, bool TraceMode)
  : ExecutionEngine(M), ExitCode(0), Debug(DebugMode), Trace(TraceMode),
    CurFrame(-1), TD("lli", (Config & TM::EndianMask) == TM::LittleEndian,
		     1, 4,
		     (Config & TM::PtrSizeMask) == TM::PtrSize64 ? 8 : 4,
		     (Config & TM::PtrSizeMask) == TM::PtrSize64 ? 8 : 4,
		     (Config & TM::PtrSizeMask) == TM::PtrSize64 ? 8 : 4) {

  setTargetData(TD);
  // Initialize the "backend"
  initializeExecutionEngine();
  initializeExternalMethods();
  CW.setModule(M);  // Update Writer
}

/// run - Start execution with the specified function and arguments.
///
int Interpreter::run(const std::string &MainFunction,
		     const std::vector<std::string> &Args) {
  // Start interpreter into the main function...
  //
  if (!callMainMethod(MainFunction, Args) && !Debug) {
    // If not in debug mode and if the call succeeded, run the code now...
    run();
  }

  // If debug mode, allow the user to interact... also, if the user pressed
  // ctrl-c or execution hit an error, enter the event loop...
  if (Debug || isStopped())
    handleUserInput();
  return ExitCode;
}

<|endoftext|>