<commit_before>#include <ros/ros.h>

#include <ompl/geometric/SimpleSetup.h>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/base/spaces/SE2StateSpace.h>

#include <cmath>
#include <iostream>
#include <fstream>

namespace ob = ompl::base;
namespace og = ompl::geometric;

void planWithSimpleSetup(){
    ob::StateSpacePtr space(new ob::SE2StateSpace());
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);
    space->as<ob::SE2StateSpace>()->setBounds(bounds);

    og::SimpleSetup ss(space);

    //TODO: Set state validity checker

    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setXY(-0.9, -0.9);
    std::cout << "start: "; start.print(std::cout);

    ob::ScopedState<ob::SE2StateSpace> goal(space);
    goal->setXY(0.9, 0.9);
    std::cout << "goal: " goal.print(std::cout);

    ss.setStartAndGoalStates(start, goal);

    ob::PlannerPtr planner(new og::PRM(ss.getSpaceInformation()));
    ss.setPlanner(planner);

    std::cout << "-----------------" << std::endl;

    ob::PlannerStatus solved = ss.solve(1.0);

    if(solved){
        ss.simplifySolution();
        std::cout << "------------" << std::endl;
        std::cout << "Found solution:" << std::endl;
        ss.getSolutionPath().print(std::cout);

        std::ofstream ofs("path.dat");
        ss.getSolutionPath().printAsMatrix(ofs);
    }else{
        ROS_ERROR("Solution is not found");
    }
}

int main(int argc, char *argv[]){
    ros::init(argc, argv, "global_path_planner");
    planWithSimpleSetup();
    return 0;
}

<commit_msg>Fix syntax error<commit_after>#include <ros/ros.h>

#include <ompl/geometric/SimpleSetup.h>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/base/spaces/SE2StateSpace.h>

#include <cmath>
#include <iostream>
#include <fstream>

namespace ob = ompl::base;
namespace og = ompl::geometric;

void planWithSimpleSetup(){
    ob::StateSpacePtr space(new ob::SE2StateSpace());
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);
    space->as<ob::SE2StateSpace>()->setBounds(bounds);

    og::SimpleSetup ss(space);

    //TODO: Set state validity checker

    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setXY(-0.9, -0.9);
    std::cout << "start: "; start.print(std::cout);

    ob::ScopedState<ob::SE2StateSpace> goal(space);
    goal->setXY(0.9, 0.9);
    std::cout << "goal: "; goal.print(std::cout);

    ss.setStartAndGoalStates(start, goal);

    ob::PlannerPtr planner(new og::PRM(ss.getSpaceInformation()));
    ss.setPlanner(planner);

    std::cout << "-----------------" << std::endl;

    ob::PlannerStatus solved = ss.solve(1.0);

    if(solved){
        ss.simplifySolution();
        std::cout << "------------" << std::endl;
        std::cout << "Found solution:" << std::endl;
        ss.getSolutionPath().print(std::cout);

        std::ofstream ofs("path.dat");
        ss.getSolutionPath().printAsMatrix(ofs);
    }else{
        ROS_ERROR("Solution is not found");
    }
}

int main(int argc, char *argv[]){
    ros::init(argc, argv, "global_path_planner");
    planWithSimpleSetup();
    return 0;
}

<|endoftext|>


<commit_before>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"

using namespace llvm;

static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);

static cl::list<int> Offsets(
    "offset", cl::desc("Format a range starting at this file offset."));
static cl::list<int> Lengths(
    "length", cl::desc("Format a range of this length, -1 for end of file."));
static cl::opt<std::string> Style(
    "style",
    cl::desc("Coding style, currently supports: LLVM, Google, Chromium."),
    cl::init("LLVM"));
static cl::opt<bool> Inplace("i",
                             cl::desc("Inplace edit <file>, if specified."));

static cl::opt<bool> OutputXML(
    "output-replacements-xml", cl::desc("Output replacements as XML."));

// FIXME: Remove this when styles are configurable through files.
static cl::opt<bool> InvertPointerBinding(
    "invert-pointer-binding", cl::desc("Inverts the side to which */& bind"),
    cl::init(false));

static cl::opt<std::string> FileName(cl::Positional, cl::desc("[<file>]"),
                                     cl::init("-"));

namespace clang {
namespace format {

static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
                                 SourceManager &Sources, FileManager &Files) {
  const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
                                                    FileName,
                                                Source->getBufferSize(), 0);
  Sources.overrideFileContents(Entry, Source, true);
  return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}

static FormatStyle getStyle() {
  FormatStyle TheStyle = getGoogleStyle();
  if (Style == "LLVM")
    TheStyle = getLLVMStyle();
  if (Style == "Chromium")
    TheStyle = getChromiumStyle();
  if (InvertPointerBinding) {
    TheStyle.PointerAndReferenceBindToType =
        !TheStyle.PointerAndReferenceBindToType;
  }
  return TheStyle;
}

static void format() {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return;
  }
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
  if (Offsets.empty())
    Offsets.push_back(0);
  if (Offsets.size() != Lengths.size() &&
      !(Offsets.size() == 1 && Lengths.empty())) {
    llvm::errs() << "Number of -offset and -length arguments must match.\n";
    return;
  }
  std::vector<CharSourceRange> Ranges;
  for (cl::list<int>::size_type i = 0, e = Offsets.size(); i != e; ++i) {
    SourceLocation Start =
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
    SourceLocation End;
    if (i < Lengths.size()) {
      End = Start.getLocWithOffset(Lengths[i]);
    } else {
      End = Sources.getLocForEndOfFile(ID);
    }
    Ranges.push_back(CharSourceRange::getCharRange(Start, End));
  }
  tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs() << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::raw_fd_ostream::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
}

}  // namespace format
}  // namespace clang

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  cl::ParseCommandLineOptions(
      argc, argv,
      "A tool to format C/C++/Obj-C code.\n\n"
      "Currently supports LLVM and Google style guides.\n"
      "If no arguments are specified, it formats the code from standard input\n"
      "and writes the result to the standard output.\n"
      "If <file> is given, it reformats the file. If -i is specified together\n"
      "with <file>, the file is edited in-place. Otherwise, the result is\n"
      "written to the standard output.\n");
  if (Help)
    cl::PrintHelpMessage();
  clang::format::format();
  return 0;
}
<commit_msg>Remove superseeded option.<commit_after>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"

using namespace llvm;

static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);

static cl::list<int> Offsets(
    "offset", cl::desc("Format a range starting at this file offset."));
static cl::list<int> Lengths(
    "length", cl::desc("Format a range of this length, -1 for end of file."));
static cl::opt<std::string> Style(
    "style",
    cl::desc("Coding style, currently supports: LLVM, Google, Chromium."),
    cl::init("LLVM"));
static cl::opt<bool> Inplace("i",
                             cl::desc("Inplace edit <file>, if specified."));

static cl::opt<bool> OutputXML(
    "output-replacements-xml", cl::desc("Output replacements as XML."));

static cl::opt<std::string> FileName(cl::Positional, cl::desc("[<file>]"),
                                     cl::init("-"));

namespace clang {
namespace format {

static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
                                 SourceManager &Sources, FileManager &Files) {
  const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
                                                    FileName,
                                                Source->getBufferSize(), 0);
  Sources.overrideFileContents(Entry, Source, true);
  return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}

static FormatStyle getStyle() {
  FormatStyle TheStyle = getGoogleStyle();
  if (Style == "LLVM")
    TheStyle = getLLVMStyle();
  if (Style == "Chromium")
    TheStyle = getChromiumStyle();
  return TheStyle;
}

static void format() {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return;
  }
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
  if (Offsets.empty())
    Offsets.push_back(0);
  if (Offsets.size() != Lengths.size() &&
      !(Offsets.size() == 1 && Lengths.empty())) {
    llvm::errs() << "Number of -offset and -length arguments must match.\n";
    return;
  }
  std::vector<CharSourceRange> Ranges;
  for (cl::list<int>::size_type i = 0, e = Offsets.size(); i != e; ++i) {
    SourceLocation Start =
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
    SourceLocation End;
    if (i < Lengths.size()) {
      End = Start.getLocWithOffset(Lengths[i]);
    } else {
      End = Sources.getLocForEndOfFile(ID);
    }
    Ranges.push_back(CharSourceRange::getCharRange(Start, End));
  }
  tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs() << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::raw_fd_ostream::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
}

}  // namespace format
}  // namespace clang

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  cl::ParseCommandLineOptions(
      argc, argv,
      "A tool to format C/C++/Obj-C code.\n\n"
      "Currently supports LLVM and Google style guides.\n"
      "If no arguments are specified, it formats the code from standard input\n"
      "and writes the result to the standard output.\n"
      "If <file> is given, it reformats the file. If -i is specified together\n"
      "with <file>, the file is edited in-place. Otherwise, the result is\n"
      "written to the standard output.\n");
  if (Help)
    cl::PrintHelpMessage();
  clang::format::format();
  return 0;
}
<|endoftext|>


<commit_before>/* LibMemcached
 * Copyright (C) 2006-2009 Brian Aker
 * All rights reserved.
 *
 * Use and distribution licensed under the BSD license.  See
 * the COPYING file in the parent directory for full text.
 *
 * Summary: String structure used for libmemcached.
 *
 */

/*
  This is a partial implementation for fetching/creating memcached_server_st objects.
*/
#include <libmemcached/common.h>

static inline void _server_init(memcached_server_st *self, const memcached_st *root,
                                const char *hostname, in_port_t port,
                                uint32_t weight, memcached_connection_t type)
{
  self->options.is_shutting_down= false;
  self->options.is_dead= false;
  self->number_of_hosts= 0;
  self->cursor_active= 0;
  self->port= port;
  self->cached_errno= 0;
  self->fd= -1;
  self->io_bytes_sent= 0;
  self->server_failure_counter= 0;
  self->weight= weight ? weight : 1; // 1 is the default weight value
  WATCHPOINT_SET(self->io_wait_count.read= 0);
  WATCHPOINT_SET(self->io_wait_count.write= 0);
  self->major_version= UINT8_MAX;
  self->micro_version= UINT8_MAX;
  self->minor_version= UINT8_MAX;
  self->type= type;
  self->read_ptr= self->read_buffer;
  self->cached_server_error= NULL;
  self->read_buffer_length= 0;
  self->read_data_length= 0;
  self->write_buffer_offset= 0;
  self->address_info= NULL;
  self->address_info_next= NULL;

  if (root)
  {
    self->next_retry= root->retry_timeout;
  }
  else
  {
    self->next_retry= 0;
  }

  self->root= root;
  self->limit_maxbytes= 0;
  if (hostname == NULL)
  {
    self->hostname[0]= 0;
  }
  else
  {
    strncpy(self->hostname, hostname, NI_MAXHOST - 1);
  }
}

static memcached_server_st *_server_create(memcached_server_st *self, const memcached_st *memc)
{
  if (self == NULL)
  {
   self= (memcached_server_st *)libmemcached_malloc(memc, sizeof(memcached_server_st));

    if (! self)
      return NULL; /*  MEMCACHED_MEMORY_ALLOCATION_FAILURE */

    self->options.is_allocated= true;
  }
  else
  {
    self->options.is_allocated= false;
  }

  self->options.is_initialized= true;

  return self;
}

memcached_server_st *memcached_server_create_with(const memcached_st *memc,
                                                  memcached_server_write_instance_st self,
                                                  const char *hostname, in_port_t port,
                                                  uint32_t weight, memcached_connection_t type)
{
  self= _server_create(self, memc);

  if (self == NULL)
    return NULL;

  _server_init(self, memc, hostname, port, weight, type);

  if (type == MEMCACHED_CONNECTION_UDP)
  {
    self->write_buffer_offset= UDP_DATAGRAM_HEADER_LENGTH;
    memcached_io_init_udp_header(self, 0);
  }

  return self;
}

void memcached_server_free(memcached_server_st *self)
{
  memcached_quit_server(self, false);

  if (self->cached_server_error)
    free(self->cached_server_error);

  if (self->address_info)
    freeaddrinfo(self->address_info);

  if (memcached_is_allocated(self))
  {
    if (self->root)
    {
      libmemcached_free(self->root, self);
    }
    else
    {
      free(self);
    }
  }
  else
  {
    self->options.is_initialized= false;
  }
}

/*
  If we do not have a valid object to clone from, we toss an error.
*/
memcached_server_st *memcached_server_clone(memcached_server_st *destination,
                                            const memcached_server_st *source)
{
  /* We just do a normal create if source is missing */
  if (source == NULL)
    return NULL;

  destination= memcached_server_create_with(source->root, destination,
                                            source->hostname, source->port, source->weight,
                                            source->type);
  if (destination != NULL)
  {
    destination->cached_errno= source->cached_errno;

    if (source->cached_server_error)
      destination->cached_server_error= strdup(source->cached_server_error);
  }

  return destination;

}

memcached_return_t memcached_server_cursor(const memcached_st *ptr,
                                           const memcached_server_fn *callback,
                                           void *context,
                                           uint32_t number_of_callbacks)
{
  memcached_return_t rc;
  if ((rc= initialize_const_query(ptr)) != MEMCACHED_SUCCESS)
  {
    return rc;
  }

  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_instance_st instance=
      memcached_server_instance_by_position(ptr, x);

    for (uint32_t y= 0; y < number_of_callbacks; y++)
    {
      unsigned int iferror;

      iferror= (*callback[y])(ptr, instance, context);

      if (iferror)
        continue;
    }
  }

  return MEMCACHED_SUCCESS;
}

memcached_return_t memcached_server_execute(memcached_st *ptr,
                                            memcached_server_execute_fn callback,
                                            void *context)
{
  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_write_instance_st instance=
      memcached_server_instance_fetch(ptr, x);

    unsigned int iferror;

    iferror= (*callback)(ptr, instance, context);

    if (iferror)
      continue;
  }

  return MEMCACHED_SUCCESS;
}

memcached_server_instance_st memcached_server_by_key(const memcached_st *ptr,
                                                     const char *key,
                                                     size_t key_length,
                                                     memcached_return_t *error)
{
  memcached_return_t rc;
  if (memcached_failed(rc= initialize_const_query(ptr)))
  {
    if (error)
      *error= rc;

    return NULL;
  }

  if (memcached_failed(rc= memcached_validate_key_length(key_length, ptr->flags.binary_protocol)))
  {
    if (error)
      *error= rc;

    return NULL;
  }

  if (ptr->flags.verify_key && (memcached_key_test((const char **)&key, &key_length, 1) == MEMCACHED_BAD_KEY_PROVIDED))
  {
    if (error)
      *error= MEMCACHED_BAD_KEY_PROVIDED;
    return NULL;
  }

  uint32_t server_key= memcached_generate_hash(ptr, key, key_length);
  return memcached_server_instance_by_position(ptr, server_key);

}

void memcached_server_error_reset(memcached_server_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return;

  self->cached_server_error[0]= 0;
}

memcached_server_instance_st memcached_server_get_last_disconnect(const memcached_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->last_disconnected_server;
}

void memcached_server_list_free(memcached_server_list_st self)
{
  if (not self)
    return;

  for (uint32_t x= 0; x < memcached_server_list_count(self); x++)
  {
    if (self[x].address_info)
    {
      freeaddrinfo(self[x].address_info);
      self[x].address_info= NULL;
    }
  }

  const memcached_st *root= self->root;
  if (root)
  {
    libmemcached_free(root, self);
  }
  else
  {
    free(self);
  }
}

uint32_t memcached_servers_set_count(memcached_server_st *servers, uint32_t count)
{
  WATCHPOINT_ASSERT(servers);
  if (not servers)
    return 0;

  return servers->number_of_hosts= count;
}

uint32_t memcached_server_count(const memcached_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->number_of_hosts;
}

const char *memcached_server_name(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return NULL;

  return self->hostname;
}

in_port_t memcached_server_port(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->port;
}

uint32_t memcached_server_response_count(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->cursor_active;
}

const char *memcached_server_error(memcached_server_instance_st ptr)
{
  return ptr ?  ptr->cached_server_error : NULL;
}

<commit_msg>Small style cleanup<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Libmemcached library
 *
 *  Copyright (C) 2011 Data Differential, http://datadifferential.com/
 *  Copyright (C) 2006-2009 Brian Aker 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.
 *
 *      * The names of its contributors may not 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.
 *
 */

/*
  This is a partial implementation for fetching/creating memcached_server_st objects.
*/
#include <libmemcached/common.h>
#include <cassert>

static inline void _server_init(memcached_server_st *self, const memcached_st *root,
                                const char *hostname, in_port_t port,
                                uint32_t weight, memcached_connection_t type)
{
  self->options.is_shutting_down= false;
  self->options.is_dead= false;
  self->number_of_hosts= 0;
  self->cursor_active= 0;
  self->port= port;
  self->cached_errno= 0;
  self->fd= -1;
  self->io_bytes_sent= 0;
  self->server_failure_counter= 0;
  self->weight= weight ? weight : 1; // 1 is the default weight value
  WATCHPOINT_SET(self->io_wait_count.read= 0);
  WATCHPOINT_SET(self->io_wait_count.write= 0);
  self->major_version= UINT8_MAX;
  self->micro_version= UINT8_MAX;
  self->minor_version= UINT8_MAX;
  self->type= type;
  self->read_ptr= self->read_buffer;
  self->cached_server_error= NULL;
  self->read_buffer_length= 0;
  self->read_data_length= 0;
  self->write_buffer_offset= 0;
  self->address_info= NULL;
  self->address_info_next= NULL;

  if (root)
  {
    self->next_retry= root->retry_timeout;
  }
  else
  {
    self->next_retry= 0;
  }

  self->root= root;
  self->limit_maxbytes= 0;
  if (hostname == NULL)
  {
    self->hostname[0]= 0;
  }
  else
  {
    strncpy(self->hostname, hostname, NI_MAXHOST - 1);
  }
}

static memcached_server_st *_server_create(memcached_server_st *self, const memcached_st *memc)
{
  if (self == NULL)
  {
   self= (memcached_server_st *)libmemcached_malloc(memc, sizeof(memcached_server_st));

    if (! self)
      return NULL; /*  MEMCACHED_MEMORY_ALLOCATION_FAILURE */

    self->options.is_allocated= true;
  }
  else
  {
    self->options.is_allocated= false;
  }

  self->options.is_initialized= true;

  return self;
}

memcached_server_st *memcached_server_create_with(const memcached_st *memc,
                                                  memcached_server_write_instance_st self,
                                                  const char *hostname, in_port_t port,
                                                  uint32_t weight, memcached_connection_t type)
{
  self= _server_create(self, memc);

  if (self == NULL)
    return NULL;

  _server_init(self, memc, hostname, port, weight, type);

  if (type == MEMCACHED_CONNECTION_UDP)
  {
    self->write_buffer_offset= UDP_DATAGRAM_HEADER_LENGTH;
    memcached_io_init_udp_header(self, 0);
  }

  return self;
}

void memcached_server_free(memcached_server_st *self)
{
  assert(self);
  memcached_quit_server(self, false);

  if (self->cached_server_error)
    free(self->cached_server_error);

  if (self->address_info)
    freeaddrinfo(self->address_info);

  if (memcached_is_allocated(self))
  {
    if (self->root)
    {
      libmemcached_free(self->root, self);
    }
    else
    {
      free(self);
    }
  }
  else
  {
    self->options.is_initialized= false;
  }
}

/*
  If we do not have a valid object to clone from, we toss an error.
*/
memcached_server_st *memcached_server_clone(memcached_server_st *destination,
                                            const memcached_server_st *source)
{
  /* We just do a normal create if source is missing */
  if (not source)
    return NULL;

  destination= memcached_server_create_with(source->root, destination,
                                            source->hostname, source->port, source->weight,
                                            source->type);
  if (destination != NULL)
  {
    destination->cached_errno= source->cached_errno;

    if (source->cached_server_error)
      destination->cached_server_error= strdup(source->cached_server_error);
  }

  return destination;

}

memcached_return_t memcached_server_cursor(const memcached_st *ptr,
                                           const memcached_server_fn *callback,
                                           void *context,
                                           uint32_t number_of_callbacks)
{
  memcached_return_t rc;
  if (memcached_failed(rc= initialize_const_query(ptr)))
  {
    return rc;
  }

  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_instance_st instance=
      memcached_server_instance_by_position(ptr, x);

    for (uint32_t y= 0; y < number_of_callbacks; y++)
    {
      unsigned int iferror;

      iferror= (*callback[y])(ptr, instance, context);

      if (iferror)
        continue;
    }
  }

  return MEMCACHED_SUCCESS;
}

memcached_return_t memcached_server_execute(memcached_st *ptr,
                                            memcached_server_execute_fn callback,
                                            void *context)
{
  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, x);

    unsigned int iferror= (*callback)(ptr, instance, context);

    if (iferror)
      continue;
  }

  return MEMCACHED_SUCCESS;
}

memcached_server_instance_st memcached_server_by_key(const memcached_st *ptr,
                                                     const char *key,
                                                     size_t key_length,
                                                     memcached_return_t *error)
{
  memcached_return_t rc;
  memcached_return_t unused;

  if (not error)
    error= &unused;

  if (memcached_failed(rc= initialize_const_query(ptr)))
  {
    *error= rc;
    return NULL;
  }

  if (memcached_failed(rc= memcached_validate_key_length(key_length, ptr->flags.binary_protocol)))
  {
    *error= rc;
    return NULL;
  }

  if (ptr->flags.verify_key && (memcached_key_test((const char **)&key, &key_length, 1) == MEMCACHED_BAD_KEY_PROVIDED))
  {
    *error= MEMCACHED_BAD_KEY_PROVIDED;
    return NULL;
  }

  uint32_t server_key= memcached_generate_hash(ptr, key, key_length);
  return memcached_server_instance_by_position(ptr, server_key);

}

void memcached_server_error_reset(memcached_server_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return;

  self->cached_server_error[0]= 0;
}

memcached_server_instance_st memcached_server_get_last_disconnect(const memcached_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->last_disconnected_server;
}

void memcached_server_list_free(memcached_server_list_st self)
{
  if (not self)
    return;

  for (uint32_t x= 0; x < memcached_server_list_count(self); x++)
  {
    if (self[x].address_info)
    {
      freeaddrinfo(self[x].address_info);
      self[x].address_info= NULL;
    }
  }

  const memcached_st *root= self->root;
  if (root)
  {
    libmemcached_free(root, self);
  }
  else
  {
    free(self);
  }
}

uint32_t memcached_servers_set_count(memcached_server_st *servers, uint32_t count)
{
  WATCHPOINT_ASSERT(servers);
  if (not servers)
    return 0;

  return servers->number_of_hosts= count;
}

uint32_t memcached_server_count(const memcached_st *self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->number_of_hosts;
}

const char *memcached_server_name(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return NULL;

  return self->hostname;
}

in_port_t memcached_server_port(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->port;
}

uint32_t memcached_server_response_count(memcached_server_instance_st self)
{
  WATCHPOINT_ASSERT(self);
  if (not self)
    return 0;

  return self->cursor_active;
}

const char *memcached_server_error(memcached_server_instance_st ptr)
{
  return ptr ?  ptr->cached_server_error : NULL;
}

<|endoftext|>


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

#include "common/json.h"
#include "client.h"
#include "error_page.h"
#include "orchestrator.h"
#include "file.h"

/* Constants */
#define BUF_MAXLEN	1024

CClient::CClient(CSocket *_Socket, FileLogger *_log) {
	/* Set the client socket */
	Socket = _Socket;
	logger = _log;
}

CClient::~CClient() {
	/* Disconnect client */
	Disconnect();

	/* Delete socket */
	delete Socket;
}

void CClient::Disconnect() {
	/* Destroy socket */
	Socket->Destroy();
}

std::string CClient::Remote() {
	return Socket->RemoteAddr() + ':' + Socket->RemotePort();
}

int CClient::Read(void *buffer, size_t len) {
	/* Receive data */
	return Socket->Receive(buffer, len);
}

int CClient::Write(const void *buffer, size_t len) {
	unsigned char *ptr = (unsigned char *)buffer;

	size_t  cnt = 0;
	ssize_t res;

	/* Write loop */
	while (cnt < len) {
		/* Send data */
		res = Socket->Send(ptr + cnt, len - cnt);

		/* Check result */
		if (res == -1)
			return res;
		if (res == 0)
			break;

		/* Increment counter */
		cnt += res;
	}

	return cnt;
}

int CClient::ReadLoop(void *buffer, size_t len) {
	unsigned char *ptr = (unsigned char *)buffer;

	size_t  cnt = 0;
	ssize_t res;

	/* Read loop */
	while (cnt < len) {
		/* Receive data */
		res = Socket->Receive(ptr + cnt, len - cnt);

		/* Check result */
		if (res == -1)
			return res;
		if (res == 0)
			break;

		/* Increment counter */
		cnt += res;
	}

	return cnt;
}

bool CClient::SendHtml(const void *buffer, size_t len, int reply) {
	CHeader Header;

	ssize_t res;
	bool    ret;

	/* Setup header */
	Header.AddReply(reply);
	Header.AddType("text/html; charset=UTF-8");
	Header.Set("X-Content-Type-Options: nosniff\r\n");
	Header.Set("X-Frame-Options: deny\r\n");
	Header.Set("X-XSS-Protection: 1; mode=block\r\n");
	Header.AddAdditional();

	Header.AddDate();
	Header.AddServer();
	if (len > 0)
		Header.AddLength(len);
	Header.AddEnd();

	/* Send header */
	ret = SendHeader(Header);
	if (!ret)
		return false;

	/* Send data */
	if (len > 0) {
		res = Write(buffer, len);
		if (res <= 0)
			return false;
	}

	return true;
}

bool CClient::SendRedirect(const std::string& location) {
	CHeader Header;
	bool    ret;

	/* Setup header */
	Header.AddReply(REPLY_REDIR_PER);
	Header.AddLocation(location);
	Header.AddAdditional();
	Header.AddDate();
	Header.AddServer();
	Header.AddEnd();

	/* Send header */
	ret = SendHeader(Header);
	if (!ret)
		return false;

	return true;
}

bool CClient::SendHeader(CHeader &Header) {
	std::string  hdr;
	int len, res;

	/* Generate header */
	hdr = Header.Generate();
	len = hdr.length();

	/* Send header */
	res = Write(hdr.c_str(), len);
	if (res != len)
		return false;

	return true;
}

bool CClient::ParseUri(std::string filepath) {
	const std::string service("/core::foundation::rpc::service");
	const std::string webledge("/core::webledge::");

	if (!filepath.compare(0, service.size(), service)) {
		CHeader 	Header;
		const char *buffer;
		size_t      len, res;
		nlohmann::json object;

		object["active"] = true;
		object["operation"] = "default";
		object["type"] = "jsonrpc";
		object["success"] = true;
		object["message"] = nullptr;
		object["parameters"] = {"calls", {
			{"status", "Server status"},
			{"solicit", "Register instance"}
		}};
		std::string s = object.dump(4);

		buffer = s.c_str();
		len    = s.length();

		/* Setup header */
		Header.AddReply(REPLY_OK);
		Header.AddType("application/json");
		Header.AddDate();
		Header.AddServer();
		Header.AddConnection(false);
		Header.AddLength(len);
		Header.Set("Access-Control-Allow-Origin: *\r\n");
		Header.AddAdditional();
		Header.AddEnd();

		/* Send header */
		res = SendHeader(Header);
		if (!res)
			return false;

		/* Send data */
		if (len > 0) {
			res = Write(buffer, len);
			if (res <= 0)
				return false;
		}

		return true;
	}

	if (!filepath.compare(0, webledge.size(), webledge)) {
		std::string dir = filepath.substr(webledge.size()).c_str();
		if (!dir.empty()) {
			std::string subdir = "";

			size_t index;
			while ((index = dir.find("::")) != std::string::npos)
				dir.replace(index, 2, "/");

  			dir.substr(0, dir.find_last_of('#'));

			SendFile(dir);
			return true;
		}

		SendFile("index.html");

		return true;
	}

	if (!filepath.compare("/favicon.ico") || !filepath.compare("/sitemap.xml")) {
		HandleError(REPLY_NOENT);

		return true;
	}

	return false;
}

bool CClient::SendFile(std::string filepath) {
	return SendFile(filepath.c_str());
}

bool CClient::SendFile(const char *filepath) {
	CFile   File;
	CHeader Header;

	char   buffer[BUF_MAXLEN];
	size_t len;
	bool   res;

	/* Open file */
	res = File.Open(filepath);

	/* File not found */
	if (!res) {
		/* Handle error */
		HandleError(REPLY_NOENT);
		goto out;
	}

	/* Get file size */
	len = File.Size();

	/* No contents? */
	if (!len) {
		/* Handle error */
		HandleError(REPLY_INTERR);

		res = false;
		goto out;
	}

	/* Setup header */
	Header.AddReply(REPLY_OK);
	Header.AddType(File.Type());
	Header.AddDate();
	Header.AddServer();
	Header.AddAdditional();
	Header.AddLength(len);
	Header.AddEnd();

	/* Send header */
	res = SendHeader(Header);
	if (!res)
		goto out;

	/* Read loop */
	while (len) {
		ssize_t ret, size;

		/* Block size */
		size = (len > BUF_MAXLEN) ? BUF_MAXLEN : len;

		/* Read block */
		res = File.Read(buffer, size);
		if (!res)
			break;

		/* Send block */
		ret = Write(buffer, size);
		if (ret != size) {
			res = false;
			break;
		}

		/* Update length */
		len -= size;
	}

out:
	/* Close file */
	File.Close();

	return res;
}

bool CClient::RecvRequest(CHeader &Header) {
	char   *buffer;
	ssize_t res;

	/* Allocate buffer */
	buffer = new char[HDR_MAXLEN];
	if (!buffer)
		return false;

	/* Read data */
	res = Read(buffer, HDR_MAXLEN);

	/* Set header string */
	if (res > 0)
		Header.Set(buffer);

	/* Delete buffer */
	delete buffer;

	return (res > 0) ? true : false;
}

bool CClient::HandleError(int reply) {
	const char *buffer;
	size_t      len;

	std::string data;

	/* Get the error page */
	data = CErrorPage::Get(reply);

	/* Set buffer */
	buffer = data.c_str();
	len    = data.length();

	/* Send reply */
	return SendHtml(buffer, len, reply);
}

<commit_msg>Correct dealloc<commit_after>#include <iostream>
#include <fstream>
#include <cstring>

#include "common/json.h"
#include "client.h"
#include "error_page.h"
#include "orchestrator.h"
#include "file.h"

/* Constants */
#define BUF_MAXLEN	1024

CClient::CClient(CSocket *_Socket, FileLogger *_log) {
	/* Set the client socket */
	Socket = _Socket;
	logger = _log;
}

CClient::~CClient() {
	/* Disconnect client */
	Disconnect();

	/* Delete socket */
	delete Socket;
}

void CClient::Disconnect() {
	/* Destroy socket */
	Socket->Destroy();
}

std::string CClient::Remote() {
	return Socket->RemoteAddr() + ':' + Socket->RemotePort();
}

int CClient::Read(void *buffer, size_t len) {
	/* Receive data */
	return Socket->Receive(buffer, len);
}

int CClient::Write(const void *buffer, size_t len) {
	unsigned char *ptr = (unsigned char *)buffer;

	size_t  cnt = 0;
	ssize_t res;

	/* Write loop */
	while (cnt < len) {
		/* Send data */
		res = Socket->Send(ptr + cnt, len - cnt);

		/* Check result */
		if (res == -1)
			return res;
		if (res == 0)
			break;

		/* Increment counter */
		cnt += res;
	}

	return cnt;
}

int CClient::ReadLoop(void *buffer, size_t len) {
	unsigned char *ptr = (unsigned char *)buffer;

	size_t  cnt = 0;
	ssize_t res;

	/* Read loop */
	while (cnt < len) {
		/* Receive data */
		res = Socket->Receive(ptr + cnt, len - cnt);

		/* Check result */
		if (res == -1)
			return res;
		if (res == 0)
			break;

		/* Increment counter */
		cnt += res;
	}

	return cnt;
}

bool CClient::SendHtml(const void *buffer, size_t len, int reply) {
	CHeader Header;

	ssize_t res;
	bool    ret;

	/* Setup header */
	Header.AddReply(reply);
	Header.AddType("text/html; charset=UTF-8");
	Header.Set("X-Content-Type-Options: nosniff\r\n");
	Header.Set("X-Frame-Options: deny\r\n");
	Header.Set("X-XSS-Protection: 1; mode=block\r\n");
	Header.AddAdditional();

	Header.AddDate();
	Header.AddServer();
	if (len > 0)
		Header.AddLength(len);
	Header.AddEnd();

	/* Send header */
	ret = SendHeader(Header);
	if (!ret)
		return false;

	/* Send data */
	if (len > 0) {
		res = Write(buffer, len);
		if (res <= 0)
			return false;
	}

	return true;
}

bool CClient::SendRedirect(const std::string& location) {
	CHeader Header;
	bool    ret;

	/* Setup header */
	Header.AddReply(REPLY_REDIR_PER);
	Header.AddLocation(location);
	Header.AddAdditional();
	Header.AddDate();
	Header.AddServer();
	Header.AddEnd();

	/* Send header */
	ret = SendHeader(Header);
	if (!ret)
		return false;

	return true;
}

bool CClient::SendHeader(CHeader &Header) {
	std::string  hdr;
	int len, res;

	/* Generate header */
	hdr = Header.Generate();
	len = hdr.length();

	/* Send header */
	res = Write(hdr.c_str(), len);
	if (res != len)
		return false;

	return true;
}

bool CClient::ParseUri(std::string filepath) {
	const std::string service("/core::foundation::rpc::service");
	const std::string webledge("/core::webledge::");

	if (!filepath.compare(0, service.size(), service)) {
		CHeader 	Header;
		const char *buffer;
		size_t      len, res;
		nlohmann::json object;

		object["active"] = true;
		object["operation"] = "default";
		object["type"] = "jsonrpc";
		object["success"] = true;
		object["message"] = nullptr;
		object["parameters"] = {"calls", {
			{"status", "Server status"},
			{"solicit", "Register instance"}
		}};
		std::string s = object.dump(4);

		buffer = s.c_str();
		len    = s.length();

		/* Setup header */
		Header.AddReply(REPLY_OK);
		Header.AddType("application/json");
		Header.AddDate();
		Header.AddServer();
		Header.AddConnection(false);
		Header.AddLength(len);
		Header.Set("Access-Control-Allow-Origin: *\r\n");
		Header.AddAdditional();
		Header.AddEnd();

		/* Send header */
		res = SendHeader(Header);
		if (!res)
			return false;

		/* Send data */
		if (len > 0) {
			res = Write(buffer, len);
			if (res <= 0)
				return false;
		}

		return true;
	}

	if (!filepath.compare(0, webledge.size(), webledge)) {
		std::string dir = filepath.substr(webledge.size()).c_str();
		if (!dir.empty()) {
			std::string subdir = "";

			size_t index;
			while ((index = dir.find("::")) != std::string::npos)
				dir.replace(index, 2, "/");

  			dir.substr(0, dir.find_last_of('#'));

			SendFile(dir);
			return true;
		}

		SendFile("index.html");

		return true;
	}

	if (!filepath.compare("/favicon.ico") || !filepath.compare("/sitemap.xml")) {
		HandleError(REPLY_NOENT);

		return true;
	}

	return false;
}

bool CClient::SendFile(std::string filepath) {
	return SendFile(filepath.c_str());
}

bool CClient::SendFile(const char *filepath) {
	CFile   File;
	CHeader Header;

	char   buffer[BUF_MAXLEN];
	size_t len;
	bool   res;

	/* Open file */
	res = File.Open(filepath);

	/* File not found */
	if (!res) {
		/* Handle error */
		HandleError(REPLY_NOENT);
		goto out;
	}

	/* Get file size */
	len = File.Size();

	/* No contents? */
	if (!len) {
		/* Handle error */
		HandleError(REPLY_INTERR);

		res = false;
		goto out;
	}

	/* Setup header */
	Header.AddReply(REPLY_OK);
	Header.AddType(File.Type());
	Header.AddDate();
	Header.AddServer();
	Header.AddAdditional();
	Header.AddLength(len);
	Header.AddEnd();

	/* Send header */
	res = SendHeader(Header);
	if (!res)
		goto out;

	/* Read loop */
	while (len) {
		ssize_t ret, size;

		/* Block size */
		size = (len > BUF_MAXLEN) ? BUF_MAXLEN : len;

		/* Read block */
		res = File.Read(buffer, size);
		if (!res)
			break;

		/* Send block */
		ret = Write(buffer, size);
		if (ret != size) {
			res = false;
			break;
		}

		/* Update length */
		len -= size;
	}

out:
	/* Close file */
	File.Close();

	return res;
}

bool CClient::RecvRequest(CHeader &Header) {
	char   *buffer;
	ssize_t res;

	/* Allocate buffer */
	buffer = new char[HDR_MAXLEN];
	if (!buffer)
		return false;

	/* Read data */
	res = Read(buffer, HDR_MAXLEN);

	/* Set header string */
	if (res > 0)
		Header.Set(buffer);

	/* Delete buffer */
	delete[] buffer;

	return (res > 0) ? true : false;
}

bool CClient::HandleError(int reply) {
	const char *buffer;
	size_t      len;

	std::string data;

	/* Get the error page */
	data = CErrorPage::Get(reply);

	/* Set buffer */
	buffer = data.c_str();
	len    = data.length();

	/* Send reply */
	return SendHtml(buffer, len, reply);
}

<|endoftext|>


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

#ifndef _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX
#define _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX

#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include <xmlprhdl.hxx>
#endif

/**
    PropertyHandler for the XML-data-type:
*/
class XMLKerningPropHdl : public XMLPropertyHandler
{
public:
    virtual ~XMLKerningPropHdl();

    virtual sal_Bool importXML( const ::rtl::OUString& rStrImpValue, ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const;
    virtual sal_Bool exportXML( ::rtl::OUString& rStrExpValue, const ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const;
};

#endif      // _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.652); FILE MERGED 2005/09/05 14:39:27 rt 1.1.1.1.652.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: kernihdl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:44:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX
#define _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX

#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include <xmlprhdl.hxx>
#endif

/**
    PropertyHandler for the XML-data-type:
*/
class XMLKerningPropHdl : public XMLPropertyHandler
{
public:
    virtual ~XMLKerningPropHdl();

    virtual sal_Bool importXML( const ::rtl::OUString& rStrImpValue, ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const;
    virtual sal_Bool exportXML( ::rtl::OUString& rStrExpValue, const ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const;
};

#endif      // _XMLOFF_PROPERTYHANDLER_KERNINGTYPES_HXX
<|endoftext|>


<commit_before>/*
 * Thread Class
 * Copyright (c) 2005-2008 Ali Mashtizadeh
 * All rights reserved.
 */

#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

#include <string>

#include "thread.h"

using namespace std;

// Add support for using Thread::Thread() to get the current thread or the static GetThread().

void EntryWrapper(Thread *t);

Thread::Thread()
{
    cstate = Running;
    tname = "";
    tid = pthread_self(); // How do i fix this for the current thread
}

Thread::Thread(const string &name)
{
    cstate = Running;
    tname = name;
    tid = pthread_self();
}

Thread::~Thread()
{
}

string Thread::getName()
{
    return tname;
}

void Thread::setName(const string &name)
{
    tname = name;
}

ThreadPriority Thread::getPriority()
{
    return NormalPriority;
}

void Thread::setPriority(ThreadPriority p)
{
    //pthread_setschedprio(tid,p);
}

int Thread::terminate()
{
    if (tid == pthread_self())
	pthread_exit(0);
    return pthread_kill(tid, SIGKILL);
}

void Thread::exit(void *retval)
{
    pthread_exit(retval);
}

void Thread::sleep(unsigned long secs)
{
    sleep(secs);
}

void Thread::usleep(useconds_t usecs)
{
    usleep(usecs);
}

void Thread::start()
{
    int ret = pthread_create(&tid,
			     attr,
			     (void *(*)(void *))EntryWrapper,
			     (void *)this);
    //pthread_attr_destroy(attr);
    if (ret != 0) {
	cstate = Running;
	return;
    }
    return;
}

bool Thread::wait(unsigned long time)
{
    // pthread_join
    return false;
}

void Thread::yield()
{
    pthread_yield();
}

void EntryWrapper(Thread *t)
{
    t->run();
}

<commit_msg>pthread_yield to sched_yield (standard)<commit_after>/*
 * Thread Class
 * Copyright (c) 2005-2008 Ali Mashtizadeh
 * All rights reserved.
 */

#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <sched.h>

#include <string>

#include "thread.h"

using namespace std;

// Add support for using Thread::Thread() to get the current thread or the static GetThread().

void EntryWrapper(Thread *t);

Thread::Thread()
{
    cstate = Running;
    tname = "";
    tid = pthread_self(); // How do i fix this for the current thread
}

Thread::Thread(const string &name)
{
    cstate = Running;
    tname = name;
    tid = pthread_self();
}

Thread::~Thread()
{
}

string Thread::getName()
{
    return tname;
}

void Thread::setName(const string &name)
{
    tname = name;
}

ThreadPriority Thread::getPriority()
{
    return NormalPriority;
}

void Thread::setPriority(ThreadPriority p)
{
    //pthread_setschedprio(tid,p);
}

int Thread::terminate()
{
    if (tid == pthread_self())
	pthread_exit(0);
    return pthread_kill(tid, SIGKILL);
}

void Thread::exit(void *retval)
{
    pthread_exit(retval);
}

void Thread::sleep(unsigned long secs)
{
    sleep(secs);
}

void Thread::usleep(useconds_t usecs)
{
    usleep(usecs);
}

void Thread::start()
{
    int ret = pthread_create(&tid,
			     attr,
			     (void *(*)(void *))EntryWrapper,
			     (void *)this);
    //pthread_attr_destroy(attr);
    if (ret != 0) {
	cstate = Running;
	return;
    }
    return;
}

bool Thread::wait(unsigned long time)
{
    // pthread_join
    return false;
}

void Thread::yield()
{
    sched_yield();
}

void EntryWrapper(Thread *t)
{
    t->run();
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Some portions Copyright (c) 2009 The Chromium Authors.
//
// Driver program for applying a minijail from the commandline to
// a process and its children (depending on the feature).

#include "minijail/minijail.h"

#include <errno.h>
#include <linux/capability.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <unistd.h>

#include <iostream>
#include <new>
#include <string>
#include <vector>

#include <base/basictypes.h>
#include <base/command_line.h>
#include <base/logging.h>
#include <base/string_util.h>

namespace switches {
static const char kAddReadonlyMounts[] = "add-readonly-mounts";
static const char kDisableTracing[] = "disable-tracing";
static const char kEnforceSyscallsBenchmark[] = "enforce-syscall-benchmark";
static const char kEnforceSyscallsBySource[] = "enforce-syscall-by-source";
static const char kGid[] = "gid";
static const char kNamespaceVfs[] = "namespace-vfs";
static const char kNamespacePid[] = "namespace-pid";
static const char kSanitizeEnvironment[] = "sanitize-environment";
static const char kUid[] = "uid";
static const char kUseCapabilities[] = "use-capabilities";
static const char kHelp[] = "help";

static const char kHelpMessage[] = "Available Switches:\n"
"  --add-readonly-mounts\n"
"    Mounts a read-only /proc. (implies namespace-vfs)\n"
"    (TODO other read-only/special mounts)\n"
"  --disable-tracing\n"
"    Disables ptrace() and core dumps.\n"
"    This may break debugging helpers\n"
"  --enforce-syscall-benchmark-source\n"
"    Runs system call filtering in a pass-through capacity only for\n"
"    benchmarking\n"
"  --enforce-syscall-by-source\n"
"    Enables kernel enforcement that system calls originate from read-only\n"
"    memory areas\n"
"  --gid [number]\n"
"    Numeric gid to transition to prior to execution.\n"
"   (TODO: Supplemental groups will be cleared.)\n"
"  --namespace-vfs\n"
"    Enables a process-tree specific VFS view.\n"
"  --namespace-pid\n"
"    Makes the executed process into procss id 1 in its own process view.\n"
"    With --add-readonly-mounts, other processes will not be visible\n"
"  --sanitize-environment\n"
"    Scrubs the environment clean of potentially dangerous values.\n"
"    (Note, this is a blacklist and not a whitelist so it may need attention)\n"
"  --uid [number]\n"
"    Numeric uid to transition to prior to execution.\n"
"  --use-capabilities\n"
"    Restricts all root-level capabilities to CAP_SETPCAP and enables\n"
"    SECURE_NOROOT.\n"
"  -- /path/to/program [arg1 [arg2 [ . . . ] ] ]\n"
"    Supplies the required program to execute and its arguments.\n"
"    At present, an empty environment will be passed.\n"
"\n";

}  // namespace switches

static void ProcessSwitches(CommandLine *cl,
                            chromeos::MiniJailOptions *jail_opts) {
  if (cl->HasSwitch(switches::kHelp)) {
    std::cerr << switches::kHelpMessage;
    exit(0);
  }

  // Configure the jail options
  jail_opts->set_namespace_pid(cl->HasSwitch(switches::kNamespacePid));
  jail_opts->set_namespace_vfs(cl->HasSwitch(switches::kNamespaceVfs));
  jail_opts->set_add_readonly_mounts(
    cl->HasSwitch(switches::kAddReadonlyMounts));
  jail_opts->set_disable_tracing(cl->HasSwitch(switches::kDisableTracing));
  jail_opts->set_enforce_syscalls_by_source(
    cl->HasSwitch(switches::kEnforceSyscallsBySource));
  jail_opts->set_use_capabilities(cl->HasSwitch(switches::kUseCapabilities));
  jail_opts->set_sanitize_environment(
    cl->HasSwitch(switches::kSanitizeEnvironment));

  std::string uid_string = cl->GetSwitchValueASCII(switches::kUid);
  if (!uid_string.empty()) {
    errno = 0;
    uid_t uid = static_cast<uid_t>(strtol(uid_string.c_str(), NULL, 0));
    PLOG_IF(WARNING, errno) << "failed to parse uid";
    jail_opts->set_uid(uid);
  }

  std::string gid_string = cl->GetSwitchValueASCII(switches::kGid);
  if (!gid_string.empty()) {
    errno = 0;
    gid_t gid = static_cast<gid_t>(strtol(gid_string.c_str(), NULL, 0));
    PLOG_IF(WARNING, errno) << "failed to parse gid";
    jail_opts->set_gid(gid);
  }

  if (!jail_opts->FixUpDependencies()) {
    LOG(FATAL) << "Irreconcilable jail options given. Aborting.";
  }

  // Grab the loose args to use as the command line.
  // We have to wstring->argv[][] manually. Ugh.
  std::vector<std::wstring> loose_wide_args = cl->GetLooseValues();
  std::vector<std::string> loose_args(loose_wide_args.size());
  char const* *jailed_argv = new char const*[loose_wide_args.size() + 1];
  std::vector<std::wstring>::const_iterator arg_it = loose_wide_args.begin();
  char const* *ja = jailed_argv;
  for (; arg_it != loose_wide_args.end(); ++arg_it) {
    std::string arg = WideToASCII(*arg_it);
    loose_args.push_back(arg);
    // XXX: clean up this leak even though it doesn't matter.
    *ja++ = strdup(arg.c_str());
  }
  *ja = 0;

  jail_opts->set_executable_path(jailed_argv[0]);
  jail_opts->set_arguments(const_cast<char * const*>(jailed_argv),
                           loose_args.size());
  // XXX We just leak this since we're going to exec anyhow.
  // delete jailed_argv;
}

int main(int argc, char *argv[], char **envp) {
  CommandLine::Init(argc, argv);
  logging::InitLogging(NULL,
                       logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
                       logging::DONT_LOCK_LOG_FILE,
                       logging::APPEND_TO_OLD_LOG_FILE);

  chromeos::MiniJailOptions jail_opts;
  CommandLine *cl = CommandLine::ForCurrentProcess();
  ProcessSwitches(cl, &jail_opts);
  jail_opts.set_environment(envp);

  LOG_IF(FATAL, !jail_opts.executable_path()) << "No executable given";

  chromeos::MiniJail jail;
  jail.Initialize(&jail_opts);
  bool ok = jail.Jail() && jail.Run();
  return !ok;
}

<commit_msg>enable seccomp benchmark options which was in the switch list but not connected to anything...<commit_after>// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Some portions Copyright (c) 2009 The Chromium Authors.
//
// Driver program for applying a minijail from the commandline to
// a process and its children (depending on the feature).

#include "minijail/minijail.h"

#include <errno.h>
#include <linux/capability.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <unistd.h>

#include <iostream>
#include <new>
#include <string>
#include <vector>

#include <base/basictypes.h>
#include <base/command_line.h>
#include <base/logging.h>
#include <base/string_util.h>

namespace switches {
static const char kAddReadonlyMounts[] = "add-readonly-mounts";
static const char kDisableTracing[] = "disable-tracing";
static const char kEnforceSyscallsBenchmark[] = "enforce-syscall-benchmark";
static const char kEnforceSyscallsBySource[] = "enforce-syscall-by-source";
static const char kGid[] = "gid";
static const char kNamespaceVfs[] = "namespace-vfs";
static const char kNamespacePid[] = "namespace-pid";
static const char kSanitizeEnvironment[] = "sanitize-environment";
static const char kUid[] = "uid";
static const char kUseCapabilities[] = "use-capabilities";
static const char kHelp[] = "help";

static const char kHelpMessage[] = "Available Switches:\n"
"  --add-readonly-mounts\n"
"    Mounts a read-only /proc. (implies namespace-vfs)\n"
"    (TODO other read-only/special mounts)\n"
"  --disable-tracing\n"
"    Disables ptrace() and core dumps.\n"
"    This may break debugging helpers\n"
"  --enforce-syscall-benchmark\n"
"    Runs system call filtering in a pass-through capacity only for\n"
"    benchmarking\n"
"  --enforce-syscall-by-source\n"
"    Enables kernel enforcement that system calls originate from read-only\n"
"    memory areas\n"
"  --gid [number]\n"
"    Numeric gid to transition to prior to execution.\n"
"   (TODO: Supplemental groups will be cleared.)\n"
"  --namespace-vfs\n"
"    Enables a process-tree specific VFS view.\n"
"  --namespace-pid\n"
"    Makes the executed process into procss id 1 in its own process view.\n"
"    With --add-readonly-mounts, other processes will not be visible\n"
"  --sanitize-environment\n"
"    Scrubs the environment clean of potentially dangerous values.\n"
"    (Note, this is a blacklist and not a whitelist so it may need attention)\n"
"  --uid [number]\n"
"    Numeric uid to transition to prior to execution.\n"
"  --use-capabilities\n"
"    Restricts all root-level capabilities to CAP_SETPCAP and enables\n"
"    SECURE_NOROOT.\n"
"  -- /path/to/program [arg1 [arg2 [ . . . ] ] ]\n"
"    Supplies the required program to execute and its arguments.\n"
"    At present, an empty environment will be passed.\n"
"\n";

}  // namespace switches

static void ProcessSwitches(CommandLine *cl,
                            chromeos::MiniJailOptions *jail_opts) {
  if (cl->HasSwitch(switches::kHelp)) {
    std::cerr << switches::kHelpMessage;
    exit(0);
  }

  // Configure the jail options
  jail_opts->set_namespace_pid(cl->HasSwitch(switches::kNamespacePid));
  jail_opts->set_namespace_vfs(cl->HasSwitch(switches::kNamespaceVfs));
  jail_opts->set_add_readonly_mounts(
    cl->HasSwitch(switches::kAddReadonlyMounts));
  jail_opts->set_disable_tracing(cl->HasSwitch(switches::kDisableTracing));
  jail_opts->set_enforce_syscalls_benchmark(
    cl->HasSwitch(switches::kEnforceSyscallsBenchmark));
  jail_opts->set_enforce_syscalls_by_source(
    cl->HasSwitch(switches::kEnforceSyscallsBySource));
  jail_opts->set_use_capabilities(cl->HasSwitch(switches::kUseCapabilities));
  jail_opts->set_sanitize_environment(
    cl->HasSwitch(switches::kSanitizeEnvironment));

  std::string uid_string = cl->GetSwitchValueASCII(switches::kUid);
  if (!uid_string.empty()) {
    errno = 0;
    uid_t uid = static_cast<uid_t>(strtol(uid_string.c_str(), NULL, 0));
    PLOG_IF(WARNING, errno) << "failed to parse uid";
    jail_opts->set_uid(uid);
  }

  std::string gid_string = cl->GetSwitchValueASCII(switches::kGid);
  if (!gid_string.empty()) {
    errno = 0;
    gid_t gid = static_cast<gid_t>(strtol(gid_string.c_str(), NULL, 0));
    PLOG_IF(WARNING, errno) << "failed to parse gid";
    jail_opts->set_gid(gid);
  }

  if (!jail_opts->FixUpDependencies()) {
    LOG(FATAL) << "Irreconcilable jail options given. Aborting.";
  }

  // Grab the loose args to use as the command line.
  // We have to wstring->argv[][] manually. Ugh.
  std::vector<std::wstring> loose_wide_args = cl->GetLooseValues();
  std::vector<std::string> loose_args(loose_wide_args.size());
  char const* *jailed_argv = new char const*[loose_wide_args.size() + 1];
  std::vector<std::wstring>::const_iterator arg_it = loose_wide_args.begin();
  char const* *ja = jailed_argv;
  for (; arg_it != loose_wide_args.end(); ++arg_it) {
    std::string arg = WideToASCII(*arg_it);
    loose_args.push_back(arg);
    // XXX: clean up this leak even though it doesn't matter.
    *ja++ = strdup(arg.c_str());
  }
  *ja = 0;

  jail_opts->set_executable_path(jailed_argv[0]);
  jail_opts->set_arguments(const_cast<char * const*>(jailed_argv),
                           loose_args.size());
  // XXX We just leak this since we're going to exec anyhow.
  // delete jailed_argv;
}

int main(int argc, char *argv[], char **envp) {
  CommandLine::Init(argc, argv);
  logging::InitLogging(NULL,
                       logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
                       logging::DONT_LOCK_LOG_FILE,
                       logging::APPEND_TO_OLD_LOG_FILE);

  chromeos::MiniJailOptions jail_opts;
  CommandLine *cl = CommandLine::ForCurrentProcess();
  ProcessSwitches(cl, &jail_opts);
  jail_opts.set_environment(envp);

  LOG_IF(FATAL, !jail_opts.executable_path()) << "No executable given";

  chromeos::MiniJail jail;
  jail.Initialize(&jail_opts);
  bool ok = jail.Jail() && jail.Run();
  return !ok;
}

<|endoftext|>


<commit_before>#include "phAttrib.h"
#include "gmi_sim.h"
#include <SimAttribute.h>
#include <SimUtil.h>
#include <cstdlib>

/* Simmetrix, for the love of all that is good,
   please put this in your header files.
   We can't work with files from Simmodeler without it. */
pAManager SModel_attManager(pModel model);

typedef ph::BC* (*BCFactory)(pAttribute a, pGEntity ge);
typedef std::map<std::string, BCFactory> BCFactories;

struct SimBC : public ph::BC
{
  SimBC(pGEntity ge)
  {
    dim = GEN_type(ge);
    tag = GEN_tag(ge);
  }
};

struct Tensor0BC : public SimBC
{
  Tensor0BC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_tensor0) {
      fprintf(stderr, "tensor 0 attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeTensor0)a;
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    buf = AttributeTensor0_evalDS(attribute, &x[0]);
    return &buf;
  }
  pAttributeTensor0 attribute;
  double buf;
};

struct Tensor1BC : public SimBC {
  Tensor1BC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_tensor1) {
      fprintf(stderr, "tensor 1 attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeTensor1)a;
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    for (int i = 0; i < 3; ++i)
      buf[i] = AttributeTensor1_evalDS(attribute, i, &x[0]);
    return buf;
  }
  pAttributeTensor1 attribute;
  double buf[3];
};

struct CompBC : public SimBC {
  CompBC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_void) {
      fprintf(stderr, "comp1/3 attribute does not match type\n");
      abort();
    }
    pPList children = Attribute_children(a);
    magnitude = 0;
    direction = 0;
    for (int i = 0; i < PList_size(children); ++i) {
      pAttribute child = (pAttribute) PList_item(children, i);
      if (Attribute_repType(child) == Att_double)
        magnitude = (pAttributeDouble) child;
      else if (Attribute_repType(child) == Att_tensor1)
        direction = (pAttributeTensor1) child;
    }
    PList_delete(children);
    if (!magnitude) {
      fprintf(stderr, "comp1/3 attribute does not have magnitude\n");
      abort();
    }
    if (!direction) {
      fprintf(stderr, "comp1/3 attribute does not have direction\n");
      abort();
    }
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    buf[0] = AttributeDouble_evalDS(magnitude, &x[0]);
    for (int i = 0; i < 3; ++i)
      buf[i + 1] = AttributeTensor1_evalDS(direction, i, &x[0]);
    return buf;
  }
  pAttributeDouble magnitude;
  pAttributeTensor1 direction;
  double buf[4];
};

struct IntBC : public SimBC
{
  IntBC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_int) {
      fprintf(stderr, "int attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeInt)a;
  }
  virtual double* eval(apf::Vector3 const&)
  {
    /* forgive me for I am storing an int in a double.
       let there be more than 32 mantissa bits such that
       this conversion is lossless. */
    buf = AttributeInt_value(attribute);
    return &buf;
  }
  pAttributeInt attribute;
  double buf;
};

static ph::BC* tensor0Factory(pAttribute a, pGEntity ge)
{
  return new Tensor0BC(a, ge);
}

static ph::BC* tensor1Factory(pAttribute a, pGEntity ge)
{
  return new Tensor1BC(a, ge);
}

static ph::BC* compFactory(pAttribute a, pGEntity ge)
{
  return new CompBC(a, ge);
}

static ph::BC* intFactory(pAttribute a, pGEntity ge)
{
  return new IntBC(a, ge);
}

/* this should follow the KnownBC tables in phBC.cc */
static void formFactories(BCFactories& fs)
{
  fs["density"]              = tensor0Factory;
  fs["temperature"]          = tensor0Factory;
  fs["pressure"]             = tensor0Factory;
  fs["comp1"]                = compFactory;
  fs["comp3"]                = compFactory;
  fs["scalar_1"]             = tensor0Factory;
  fs["scalar_2"]             = tensor0Factory;
  fs["scalar_3"]             = tensor0Factory;
  fs["scalar_4"]             = tensor0Factory;
  fs["mass flux"]            = tensor0Factory;
  fs["natural pressure"]     = tensor0Factory;
  fs["traction vector"]      = tensor1Factory;
  fs["heat flux"]            = tensor0Factory;
  fs["turbulence wall"]      = tensor0Factory;
  fs["scalar_1 flux"]        = tensor0Factory;
  fs["scalar_2 flux"]        = tensor0Factory;
  fs["scalar_3 flux"]        = tensor0Factory;
  fs["scalar_4 flux"]        = tensor0Factory;
  fs["surf ID"]              = tensor0Factory;
  fs["initial pressure"]     = tensor0Factory;
  fs["initial velocity"]     = tensor1Factory;
  fs["initial temperature"]  = tensor0Factory;
  fs["initial scalar_1"]     = tensor0Factory;
  fs["initial scalar_2"]     = tensor0Factory;
  fs["initial scalar_3"]     = tensor0Factory;
  fs["initial scalar_4"]     = tensor0Factory;
  fs["periodic slave"]       = intFactory;
  fs["DG interface"]         = intFactory;
  fs["material type"]        = intFactory;
}

static std::string getType(pAttribute a)
{
  char* c_infoType = Attribute_infoType(a);
  std::string infoType(c_infoType);
  Sim_deleteString(c_infoType);
  char* c_imageClass = Attribute_infoType(a);
  std::string imageClass(c_imageClass);
  Sim_deleteString(c_imageClass);
  if (imageClass.length() != 0)
    return imageClass;
  return infoType;
}

static void addAttribute(BCFactories& fs, pAttribute a, pGEntity ge,
    ph::BCs& bcs)
{
  std::string type = getType(a);
  if (!fs.count(type)) {
    fprintf(stderr,"unknown attribute type \"%s\", ignoring !\n", type.c_str());
    fprintf(stderr,"it had repType %d\n",
        Attribute_repType(a));
    return;
  }
  if (!bcs.fields.count(type))
    bcs.fields[type] = ph::FieldBCs();
  ph::FieldBCs& fbcs = bcs.fields[type];
  BCFactory f = fs[type];
  fbcs.bcs.insert( f(a, ge) );
}

static void addAttributes(BCFactories& fs, pPList as, pGEntity ge,
    ph::BCs& bcs)
{
  for (int i = 0; i < PList_size(as); ++i) {
    pAttribute a = (pAttribute) PList_item(as, i);
    addAttribute(fs, a, ge, bcs);
  }
}

namespace {
  void getSimModelAndCase(gmi_model* m, pGModel& smdl, pACase& pd) {
    smdl = gmi_export_sim(m);
    pAManager mngr = SModel_attManager(smdl);
    if (!mngr) {
      fprintf(stderr,"Simmetrix model did not come with an Attribute Manager\n");
      abort();
    }
    pd = AMAN_findCaseByType(mngr, "problem definition");
    if (!pd) {
      fprintf(stderr,"no Attribute Case \"problem definition\"\n");
      abort();
    }
  }
}

void ph::clearAttAssociation(gmi_model* mdl, ph::Input& in)
{
  const char* attFile = in.attributeFileName.c_str();
  if (gmi_has_ext(attFile, "spj"))
    return;
  pGModel smdl = NULL;
  pACase pd = NULL;
  getSimModelAndCase(mdl,smdl,pd);
  AttCase_unassociate(pd);
}

void ph::getSimmetrixAttributes(gmi_model* model, ph::BCs& bcs)
{
  pGModel smdl = NULL;
  pACase pd = NULL;
  getSimModelAndCase(model,smdl,pd);
  AttCase_setModel(pd, smdl);
  AttCase_associate(pd, NULL);
  BCFactories fs;
  formFactories(fs);
  for (int dim = 0; dim < 4; ++dim) {
    gmi_iter* it = gmi_begin(model, dim);
    gmi_ent* e;
    while ((e = gmi_next(model, it))) {
      pGEntity ge = (pGEntity) e;
      pPList attribs = GEN_attributes(ge, "");
      addAttributes(fs, attribs, ge, bcs);
    }
    gmi_end(model, it);
  }
  /* Simmodeler seems to put ICs on the model itself, not the regions.
     spread all ICs off the model onto the regions.
     also, this code does assume the domain is 3D. */
  pPList attribs = GM_attributes(smdl, "");
  GRIter rit = GM_regionIter(smdl);
  pGRegion gr;
  while ((gr = GRIter_next(rit)))
    addAttributes(fs, attribs, gr, bcs);
  GRIter_delete(rit);
}

<commit_msg>fix stupid copy-paste mistake<commit_after>#include "phAttrib.h"
#include "gmi_sim.h"
#include <SimAttribute.h>
#include <SimUtil.h>
#include <cstdlib>

/* Simmetrix, for the love of all that is good,
   please put this in your header files.
   We can't work with files from Simmodeler without it. */
pAManager SModel_attManager(pModel model);

typedef ph::BC* (*BCFactory)(pAttribute a, pGEntity ge);
typedef std::map<std::string, BCFactory> BCFactories;

struct SimBC : public ph::BC
{
  SimBC(pGEntity ge)
  {
    dim = GEN_type(ge);
    tag = GEN_tag(ge);
  }
};

struct Tensor0BC : public SimBC
{
  Tensor0BC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_tensor0) {
      fprintf(stderr, "tensor 0 attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeTensor0)a;
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    buf = AttributeTensor0_evalDS(attribute, &x[0]);
    return &buf;
  }
  pAttributeTensor0 attribute;
  double buf;
};

struct Tensor1BC : public SimBC {
  Tensor1BC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_tensor1) {
      fprintf(stderr, "tensor 1 attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeTensor1)a;
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    for (int i = 0; i < 3; ++i)
      buf[i] = AttributeTensor1_evalDS(attribute, i, &x[0]);
    return buf;
  }
  pAttributeTensor1 attribute;
  double buf[3];
};

struct CompBC : public SimBC {
  CompBC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_void) {
      fprintf(stderr, "comp1/3 attribute does not match type\n");
      abort();
    }
    pPList children = Attribute_children(a);
    magnitude = 0;
    direction = 0;
    for (int i = 0; i < PList_size(children); ++i) {
      pAttribute child = (pAttribute) PList_item(children, i);
      if (Attribute_repType(child) == Att_double)
        magnitude = (pAttributeDouble) child;
      else if (Attribute_repType(child) == Att_tensor1)
        direction = (pAttributeTensor1) child;
    }
    PList_delete(children);
    if (!magnitude) {
      fprintf(stderr, "comp1/3 attribute does not have magnitude\n");
      abort();
    }
    if (!direction) {
      fprintf(stderr, "comp1/3 attribute does not have direction\n");
      abort();
    }
  }
  virtual double* eval(apf::Vector3 const& x)
  {
    buf[0] = AttributeDouble_evalDS(magnitude, &x[0]);
    for (int i = 0; i < 3; ++i)
      buf[i + 1] = AttributeTensor1_evalDS(direction, i, &x[0]);
    return buf;
  }
  pAttributeDouble magnitude;
  pAttributeTensor1 direction;
  double buf[4];
};

struct IntBC : public SimBC
{
  IntBC(pAttribute a, pGEntity ge):SimBC(ge)
  {
    if (Attribute_repType(a) != Att_int) {
      fprintf(stderr, "int attribute does not match type\n");
      abort();
    }
    attribute = (pAttributeInt)a;
  }
  virtual double* eval(apf::Vector3 const&)
  {
    /* forgive me for I am storing an int in a double.
       let there be more than 32 mantissa bits such that
       this conversion is lossless. */
    buf = AttributeInt_value(attribute);
    return &buf;
  }
  pAttributeInt attribute;
  double buf;
};

static ph::BC* tensor0Factory(pAttribute a, pGEntity ge)
{
  return new Tensor0BC(a, ge);
}

static ph::BC* tensor1Factory(pAttribute a, pGEntity ge)
{
  return new Tensor1BC(a, ge);
}

static ph::BC* compFactory(pAttribute a, pGEntity ge)
{
  return new CompBC(a, ge);
}

static ph::BC* intFactory(pAttribute a, pGEntity ge)
{
  return new IntBC(a, ge);
}

/* this should follow the KnownBC tables in phBC.cc */
static void formFactories(BCFactories& fs)
{
  fs["density"]              = tensor0Factory;
  fs["temperature"]          = tensor0Factory;
  fs["pressure"]             = tensor0Factory;
  fs["comp1"]                = compFactory;
  fs["comp3"]                = compFactory;
  fs["scalar_1"]             = tensor0Factory;
  fs["scalar_2"]             = tensor0Factory;
  fs["scalar_3"]             = tensor0Factory;
  fs["scalar_4"]             = tensor0Factory;
  fs["mass flux"]            = tensor0Factory;
  fs["natural pressure"]     = tensor0Factory;
  fs["traction vector"]      = tensor1Factory;
  fs["heat flux"]            = tensor0Factory;
  fs["turbulence wall"]      = tensor0Factory;
  fs["scalar_1 flux"]        = tensor0Factory;
  fs["scalar_2 flux"]        = tensor0Factory;
  fs["scalar_3 flux"]        = tensor0Factory;
  fs["scalar_4 flux"]        = tensor0Factory;
  fs["surf ID"]              = tensor0Factory;
  fs["initial pressure"]     = tensor0Factory;
  fs["initial velocity"]     = tensor1Factory;
  fs["initial temperature"]  = tensor0Factory;
  fs["initial scalar_1"]     = tensor0Factory;
  fs["initial scalar_2"]     = tensor0Factory;
  fs["initial scalar_3"]     = tensor0Factory;
  fs["initial scalar_4"]     = tensor0Factory;
  fs["periodic slave"]       = intFactory;
  fs["DG interface"]         = intFactory;
  fs["material type"]        = intFactory;
}

static std::string getType(pAttribute a)
{
  char* c_infoType = Attribute_infoType(a);
  std::string infoType(c_infoType);
  Sim_deleteString(c_infoType);
  char* c_imageClass = Attribute_imageClass(a);
  std::string imageClass(c_imageClass);
  Sim_deleteString(c_imageClass);
  if (imageClass.length() != 0)
    return imageClass;
  return infoType;
}

static void addAttribute(BCFactories& fs, pAttribute a, pGEntity ge,
    ph::BCs& bcs)
{
  std::string type = getType(a);
  if (!fs.count(type)) {
    fprintf(stderr,"unknown attribute type \"%s\", ignoring !\n", type.c_str());
    fprintf(stderr,"it had repType %d\n",
        Attribute_repType(a));
    return;
  }
  if (!bcs.fields.count(type))
    bcs.fields[type] = ph::FieldBCs();
  ph::FieldBCs& fbcs = bcs.fields[type];
  BCFactory f = fs[type];
  fbcs.bcs.insert( f(a, ge) );
}

static void addAttributes(BCFactories& fs, pPList as, pGEntity ge,
    ph::BCs& bcs)
{
  for (int i = 0; i < PList_size(as); ++i) {
    pAttribute a = (pAttribute) PList_item(as, i);
    addAttribute(fs, a, ge, bcs);
  }
}

namespace {
  void getSimModelAndCase(gmi_model* m, pGModel& smdl, pACase& pd) {
    smdl = gmi_export_sim(m);
    pAManager mngr = SModel_attManager(smdl);
    if (!mngr) {
      fprintf(stderr,"Simmetrix model did not come with an Attribute Manager\n");
      abort();
    }
    pd = AMAN_findCaseByType(mngr, "problem definition");
    if (!pd) {
      fprintf(stderr,"no Attribute Case \"problem definition\"\n");
      abort();
    }
  }
}

void ph::clearAttAssociation(gmi_model* mdl, ph::Input& in)
{
  const char* attFile = in.attributeFileName.c_str();
  if (gmi_has_ext(attFile, "spj"))
    return;
  pGModel smdl = NULL;
  pACase pd = NULL;
  getSimModelAndCase(mdl,smdl,pd);
  AttCase_unassociate(pd);
}

void ph::getSimmetrixAttributes(gmi_model* model, ph::BCs& bcs)
{
  pGModel smdl = NULL;
  pACase pd = NULL;
  getSimModelAndCase(model,smdl,pd);
  AttCase_setModel(pd, smdl);
  AttCase_associate(pd, NULL);
  BCFactories fs;
  formFactories(fs);
  for (int dim = 0; dim < 4; ++dim) {
    gmi_iter* it = gmi_begin(model, dim);
    gmi_ent* e;
    while ((e = gmi_next(model, it))) {
      pGEntity ge = (pGEntity) e;
      pPList attribs = GEN_attributes(ge, "");
      addAttributes(fs, attribs, ge, bcs);
    }
    gmi_end(model, it);
  }
  /* Simmodeler seems to put ICs on the model itself, not the regions.
     spread all ICs off the model onto the regions.
     also, this code does assume the domain is 3D. */
  pPList attribs = GM_attributes(smdl, "");
  GRIter rit = GM_regionIter(smdl);
  pGRegion gr;
  while ((gr = GRIter_next(rit)))
    addAttributes(fs, attribs, gr, bcs);
  GRIter_delete(rit);
}

<|endoftext|>