<commit_before>/*
 * Copyright 2019 Google 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 "buildjson.hpp"

#include "file_handler.hpp"
#include "fs.hpp"
#include "general_systemd.hpp"
#include "prepare_systemd.hpp"
#include "update_systemd.hpp"

#include <algorithm>
#include <cstdio>
#include <exception>
#include <fstream>
#include <nlohmann/json.hpp>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <sdbusplus/bus.hpp>
#include <string>
#include <vector>

namespace ipmi_flash
{

std::unique_ptr<TriggerableActionInterface>
    buildFileSystemd(const nlohmann::json& data)
{
    /* This type of action requires a path and unit, and optionally a mode. */
    const auto& path = data.at("path");
    const auto& unit = data.at("unit");

    /* the mode parameter is optional. */
    std::string systemdMode = "replace";
    const auto& mode = data.find("mode");
    if (mode != data.end())
    {
        systemdMode = data.at("mode").get<std::string>();
    }

    return SystemdWithStatusFile::CreateSystemdWithStatusFile(
        sdbusplus::bus::new_default(), path, unit, systemdMode);
}

std::vector<HandlerConfig> buildHandlerFromJson(const nlohmann::json& data)
{
    std::vector<HandlerConfig> handlers;

    for (const auto& item : data)
    {
        try
        {
            HandlerConfig output;

            /* at() throws an exception when the key is not present. */
            item.at("blob").get_to(output.blobId);

            /* name must be: /flash/... */
            if (!std::regex_match(output.blobId, std::regex("^\\/flash\\/.+")))
            {
                throw std::runtime_error("Invalid blob name: '" +
                                         output.blobId +
                                         "' must start with /flash/");
            }

            /* handler is required. */
            const auto& h = item.at("handler");
            const std::string handlerType = h.at("type");
            if (handlerType == "file")
            {
                const auto& path = h.at("path");
                output.handler = std::make_unique<FileHandler>(path);
            }
            else
            {
                throw std::runtime_error("Invalid handler type: " +
                                         handlerType);
            }

            /* actions are required (presently). */
            const auto& a = item.at("actions");
            std::unique_ptr<ActionPack> pack = std::make_unique<ActionPack>();

            /* It hasn't been fully determined if any action being optional is
             * useful, so for now they will be required.
             * TODO: Evaluate how the behaviors change if some actions are
             * missing, does the code just assume it was successful?  I would
             * think not.
             */
            const auto& prep = a.at("preparation");
            const std::string prepareType = prep.at("type");
            if (prepareType == "systemd")
            {
                const auto& unit = prep.at("unit");
                pack->preparation = SystemdPreparation::CreatePreparation(
                    sdbusplus::bus::new_default(), unit);
            }
            else
            {
                throw std::runtime_error("Invalid preparation type: " +
                                         prepareType);
            }

            const auto& verify = a.at("verification");
            const std::string verifyType = verify.at("type");
            if (verifyType == "fileSystemdVerify")
            {
                pack->verification = std::move(buildFileSystemd(verify));
            }
            else
            {
                throw std::runtime_error("Invalid verification type:" +
                                         verifyType);
            }

            const auto& update = a.at("update");
            const std::string updateType = update.at("type");
            if (updateType == "reboot")
            {
                static constexpr auto rebootTarget = "reboot.target";
                static constexpr auto rebootMode = "replace-irreversibly";
                pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(
                    sdbusplus::bus::new_default(), rebootTarget, rebootMode);
            }
            else if (updateType == "fileSystemdUpdate")
            {
                pack->update = std::move(buildFileSystemd(update));
            }
            else if (updateType == "systemd")
            {
                const auto& unit = update.at("unit");

                /* the mode parameter is optional. */
                std::string systemdMode = "replace";
                const auto& mode = update.find("mode");
                if (mode != update.end())
                {
                    systemdMode = update.at("mode").get<std::string>();
                }

                pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(
                    sdbusplus::bus::new_default(), unit, systemdMode);
            }
            else
            {
                throw std::runtime_error("Invalid update type: " + updateType);
            }

            output.actions = std::move(pack);
            handlers.push_back(std::move(output));
        }
        catch (const std::exception& e)
        {
            /* TODO: Once phosphor-logging supports unit-test injection, fix
             * this to log.
             */
            std::fprintf(stderr,
                         "Excepted building HandlerConfig from json: %s\n",
                         e.what());
        }
    }

    return handlers;
}

std::vector<HandlerConfig> BuildHandlerConfigs(const std::string& directory)
{
    using namespace phosphor::logging;

    std::vector<HandlerConfig> output;

    std::vector<std::string> jsonPaths = GetJsonList(directory);

    for (const auto& path : jsonPaths)
    {
        std::ifstream jsonFile(path);
        if (!jsonFile.is_open())
        {
            log<level::ERR>("Unable to open json file",
                            entry("PATH=%s", path.c_str()));
            continue;
        }

        auto data = nlohmann::json::parse(jsonFile, nullptr, false);
        if (data.is_discarded())
        {
            log<level::ERR>("Parsing json failed",
                            entry("PATH=%s", path.c_str()));
            continue;
        }

        std::vector<HandlerConfig> configs = buildHandlerFromJson(data);
        std::move(configs.begin(), configs.end(), std::back_inserter(output));
    }

    return output;
}

} // namespace ipmi_flash
<commit_msg>bmc: use string literals instead of variables<commit_after>/*
 * Copyright 2019 Google 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 "buildjson.hpp"

#include "file_handler.hpp"
#include "fs.hpp"
#include "general_systemd.hpp"
#include "prepare_systemd.hpp"
#include "update_systemd.hpp"

#include <algorithm>
#include <cstdio>
#include <exception>
#include <fstream>
#include <nlohmann/json.hpp>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <sdbusplus/bus.hpp>
#include <string>
#include <vector>

namespace ipmi_flash
{

std::unique_ptr<TriggerableActionInterface>
    buildFileSystemd(const nlohmann::json& data)
{
    /* This type of action requires a path and unit, and optionally a mode. */
    const auto& path = data.at("path");
    const auto& unit = data.at("unit");

    /* the mode parameter is optional. */
    std::string systemdMode = "replace";
    const auto& mode = data.find("mode");
    if (mode != data.end())
    {
        systemdMode = data.at("mode").get<std::string>();
    }

    return SystemdWithStatusFile::CreateSystemdWithStatusFile(
        sdbusplus::bus::new_default(), path, unit, systemdMode);
}

std::vector<HandlerConfig> buildHandlerFromJson(const nlohmann::json& data)
{
    std::vector<HandlerConfig> handlers;

    for (const auto& item : data)
    {
        try
        {
            HandlerConfig output;

            /* at() throws an exception when the key is not present. */
            item.at("blob").get_to(output.blobId);

            /* name must be: /flash/... */
            if (!std::regex_match(output.blobId, std::regex("^\\/flash\\/.+")))
            {
                throw std::runtime_error("Invalid blob name: '" +
                                         output.blobId +
                                         "' must start with /flash/");
            }

            /* handler is required. */
            const auto& h = item.at("handler");
            const std::string handlerType = h.at("type");
            if (handlerType == "file")
            {
                const auto& path = h.at("path");
                output.handler = std::make_unique<FileHandler>(path);
            }
            else
            {
                throw std::runtime_error("Invalid handler type: " +
                                         handlerType);
            }

            /* actions are required (presently). */
            const auto& a = item.at("actions");
            std::unique_ptr<ActionPack> pack = std::make_unique<ActionPack>();

            /* It hasn't been fully determined if any action being optional is
             * useful, so for now they will be required.
             * TODO: Evaluate how the behaviors change if some actions are
             * missing, does the code just assume it was successful?  I would
             * think not.
             */
            const auto& prep = a.at("preparation");
            const std::string prepareType = prep.at("type");
            if (prepareType == "systemd")
            {
                const auto& unit = prep.at("unit");
                pack->preparation = SystemdPreparation::CreatePreparation(
                    sdbusplus::bus::new_default(), unit);
            }
            else
            {
                throw std::runtime_error("Invalid preparation type: " +
                                         prepareType);
            }

            const auto& verify = a.at("verification");
            const std::string verifyType = verify.at("type");
            if (verifyType == "fileSystemdVerify")
            {
                pack->verification = std::move(buildFileSystemd(verify));
            }
            else
            {
                throw std::runtime_error("Invalid verification type:" +
                                         verifyType);
            }

            const auto& update = a.at("update");
            const std::string updateType = update.at("type");
            if (updateType == "reboot")
            {
                pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(
                    sdbusplus::bus::new_default(), "reboot.target",
                    "replace-irreversibly");
            }
            else if (updateType == "fileSystemdUpdate")
            {
                pack->update = std::move(buildFileSystemd(update));
            }
            else if (updateType == "systemd")
            {
                const auto& unit = update.at("unit");

                /* the mode parameter is optional. */
                std::string systemdMode = "replace";
                const auto& mode = update.find("mode");
                if (mode != update.end())
                {
                    systemdMode = update.at("mode").get<std::string>();
                }

                pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(
                    sdbusplus::bus::new_default(), unit, systemdMode);
            }
            else
            {
                throw std::runtime_error("Invalid update type: " + updateType);
            }

            output.actions = std::move(pack);
            handlers.push_back(std::move(output));
        }
        catch (const std::exception& e)
        {
            /* TODO: Once phosphor-logging supports unit-test injection, fix
             * this to log.
             */
            std::fprintf(stderr,
                         "Excepted building HandlerConfig from json: %s\n",
                         e.what());
        }
    }

    return handlers;
}

std::vector<HandlerConfig> BuildHandlerConfigs(const std::string& directory)
{
    using namespace phosphor::logging;

    std::vector<HandlerConfig> output;

    std::vector<std::string> jsonPaths = GetJsonList(directory);

    for (const auto& path : jsonPaths)
    {
        std::ifstream jsonFile(path);
        if (!jsonFile.is_open())
        {
            log<level::ERR>("Unable to open json file",
                            entry("PATH=%s", path.c_str()));
            continue;
        }

        auto data = nlohmann::json::parse(jsonFile, nullptr, false);
        if (data.is_discarded())
        {
            log<level::ERR>("Parsing json failed",
                            entry("PATH=%s", path.c_str()));
            continue;
        }

        std::vector<HandlerConfig> configs = buildHandlerFromJson(data);
        std::move(configs.begin(), configs.end(), std::back_inserter(output));
    }

    return output;
}

} // namespace ipmi_flash
<|endoftext|>


<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#include "../precompiled.hpp"
#include "abstract_stream_socket.hpp"
#include "socket_address.hpp"
#include "../static/network_driver.hpp"
#include "../utilities.hpp"

namespace poseidon {

Abstract_Stream_Socket::
~Abstract_Stream_Socket()
  {
  }

IO_Result
Abstract_Stream_Socket::
do_call_stream_preshutdown_nolock()
noexcept
  try {
    // Call `do_stream_preshutdown_nolock()`, ignoring any exeptions.
    return this->do_stream_preshutdown_nolock();
  }
  catch(const exception& stdex) {
    POSEIDON_LOG_WARN("Failed to perform graceful shutdown on stream socket: $1\n"
                      "[exception class `$2`]",
                      stdex.what(), typeid(stdex).name());
    return io_result_eof;
  }

IO_Result
Abstract_Stream_Socket::
do_async_shutdown_nolock()
noexcept
  {
    switch(this->m_cstate) {
      case connection_state_initial:
      case connection_state_connecting:
        // Shut down the connection. Discard pending data.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (not established): $1", this);
        return io_result_eof;

      case connection_state_established: {
        // Ensure pending data are delivered.
        if(this->m_wqueue.size()) {
          ::shutdown(this->get_fd(), SHUT_RD);
          this->m_cstate = connection_state_closing;
          POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (data pending): $1", this);
          return io_result_not_eof;
        }

        // Wait for shutdown.
        auto io_res = this->do_call_stream_preshutdown_nolock();
        if(io_res != io_result_eof) {
          ::shutdown(this->get_fd(), SHUT_RD);
          this->m_cstate = connection_state_closing;
          POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (preshutdown pending): $1", this);
          return io_res;
        }

        // Close the connection.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this);
        return io_result_eof;
      }

      case connection_state_closing: {
        // Ensure pending data are delivered.
        if(this->m_wqueue.size())
          return io_result_not_eof;

        // Wait for shutdown.
        auto io_res = this->do_call_stream_preshutdown_nolock();
        if(io_res != io_result_eof)
          return io_res;

        // Close the connection.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this);
        return io_result_eof;
      }

      case connection_state_closed:
        // Do nothing.
        return io_result_eof;

      default:
        ROCKET_ASSERT(false);
    }
  }

IO_Result
Abstract_Stream_Socket::
do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size)
  {
    lock.assign(this->m_mutex);

    // If the stream is in CLOSED state, fail.
    if(this->m_cstate == connection_state_closed)
      return io_result_eof;

    // Try reading some bytes.
    auto io_res = this->do_stream_read_nolock(hint, size);
    if(io_res < 0)
      return io_res;

    if(io_res == io_result_eof) {
      this->do_async_shutdown_nolock();
      return io_result_eof;
    }

    // Process the data that have been read.
    lock.unlock();
    this->do_on_async_receive(hint, static_cast<size_t>(io_res));
    lock.assign(this->m_mutex);
    return io_res;
  }

size_t
Abstract_Stream_Socket::
do_write_queue_size(Si_Mutex::unique_lock& lock)
const
  {
    lock.assign(this->m_mutex);

    // Get the size of pending data.
    size_t size = this->m_wqueue.size();
    if(size != 0)
      return size;

    // If a shutdown request is pending, report at least one byte.
    if(this->m_cstate == connection_state_closing)
      return 1;

    // There is nothing to write.
    return 0;
  }

IO_Result
Abstract_Stream_Socket::
do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* /*hint*/, size_t /*size*/)
  {
    lock.assign(this->m_mutex);

    // If the stream is in CLOSED state, fail.
    if(this->m_cstate == connection_state_closed)
      return io_result_eof;

    // If the stream is in CONNECTING state, mark it ESTABLISHED.
    if(this->m_cstate < connection_state_established) {
      this->m_cstate = connection_state_established;

      lock.unlock();
      this->do_on_async_establish();
      lock.assign(this->m_mutex);
    }

    // Try writing some bytes.
    size_t size = this->m_wqueue.size();
    if(size == 0) {
      if(this->m_cstate <= connection_state_established)
        return io_result_eof;

      // Shut down the connection completely now.
      return this->do_async_shutdown_nolock();
    }

    auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size);
    if(io_res < 0)
      return io_res;

    // Remove data that have been written.
    this->m_wqueue.discard(static_cast<size_t>(io_res));
    return io_res;
  }

void
Abstract_Stream_Socket::
do_on_async_poll_shutdown(int err)
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    this->m_cstate = connection_state_closed;
    lock.unlock();

    this->do_on_async_shutdown(err);
  }

void
Abstract_Stream_Socket::
do_async_connect(const Socket_Address& addr)
  {
    // Lock the stream and examine connection state.
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate != connection_state_initial)
      POSEIDON_THROW("another connection already in progress or established");

    // Initiate the connection.
    this->do_stream_preconnect_nolock();

    // No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current
    // socket is set to the CONNECTING state.
    if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) {
      int err = errno;
      if(err != EINPROGRESS)
        POSEIDON_THROW("failed to initiate connection to '$2'\n"
                       "[`connect()` failed: $1]",
                       noadl::format_errno(err), addr);
    }
    this->m_cstate = connection_state_connecting;
  }

Socket_Address
Abstract_Stream_Socket::
get_remote_address()
const
  {
    // Try getting the remote address.
    Socket_Address::storage_type addrst;
    Socket_Address::size_type addrlen = sizeof(addrst);
    if(::getpeername(this->get_fd(), addrst, &addrlen) != 0)
      POSEIDON_THROW("could not get remote socket address\n"
                     "[`getpeername()` failed: $1]",
                     noadl::format_errno(errno));
    return { addrst, addrlen };
  }

bool
Abstract_Stream_Socket::
async_send(const void* data, size_t size)
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate > connection_state_established)
      return false;

    // Append data to the write queue.
    this->m_wqueue.putn(static_cast<const char*>(data), size);
    lock.unlock();

    // Notify the driver about availability of outgoing data.
    Network_Driver::notify_writable_internal(this);
    return true;
  }

bool
Abstract_Stream_Socket::
async_shutdown()
noexcept
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate > connection_state_established)
      return false;

    // Initiate asynchronous shutdown.
    this->do_async_shutdown_nolock();
    lock.unlock();

    // Notify the driver about availability of outgoing data.
    Network_Driver::notify_writable_internal(this);
    return true;
  }

}  // namespace poseidon
<commit_msg>network/abstract_stream_socket: Add EOF log<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#include "../precompiled.hpp"
#include "abstract_stream_socket.hpp"
#include "socket_address.hpp"
#include "../static/network_driver.hpp"
#include "../utilities.hpp"

namespace poseidon {

Abstract_Stream_Socket::
~Abstract_Stream_Socket()
  {
  }

IO_Result
Abstract_Stream_Socket::
do_call_stream_preshutdown_nolock()
noexcept
  try {
    // Call `do_stream_preshutdown_nolock()`, ignoring any exeptions.
    return this->do_stream_preshutdown_nolock();
  }
  catch(const exception& stdex) {
    POSEIDON_LOG_WARN("Failed to perform graceful shutdown on stream socket: $1\n"
                      "[exception class `$2`]",
                      stdex.what(), typeid(stdex).name());
    return io_result_eof;
  }

IO_Result
Abstract_Stream_Socket::
do_async_shutdown_nolock()
noexcept
  {
    switch(this->m_cstate) {
      case connection_state_initial:
      case connection_state_connecting:
        // Shut down the connection. Discard pending data.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (not established): $1", this);
        return io_result_eof;

      case connection_state_established: {
        // Ensure pending data are delivered.
        if(this->m_wqueue.size()) {
          ::shutdown(this->get_fd(), SHUT_RD);
          this->m_cstate = connection_state_closing;
          POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (data pending): $1", this);
          return io_result_not_eof;
        }

        // Wait for shutdown.
        auto io_res = this->do_call_stream_preshutdown_nolock();
        if(io_res != io_result_eof) {
          ::shutdown(this->get_fd(), SHUT_RD);
          this->m_cstate = connection_state_closing;
          POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (preshutdown pending): $1", this);
          return io_res;
        }

        // Close the connection.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this);
        return io_result_eof;
      }

      case connection_state_closing: {
        // Ensure pending data are delivered.
        if(this->m_wqueue.size())
          return io_result_not_eof;

        // Wait for shutdown.
        auto io_res = this->do_call_stream_preshutdown_nolock();
        if(io_res != io_result_eof)
          return io_res;

        // Close the connection.
        ::shutdown(this->get_fd(), SHUT_RDWR);
        this->m_cstate = connection_state_closed;
        POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this);
        return io_result_eof;
      }

      case connection_state_closed:
        // Do nothing.
        return io_result_eof;

      default:
        ROCKET_ASSERT(false);
    }
  }

IO_Result
Abstract_Stream_Socket::
do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size)
  {
    lock.assign(this->m_mutex);

    // If the stream is in CLOSED state, fail.
    if(this->m_cstate == connection_state_closed)
      return io_result_eof;

    // Try reading some bytes.
    auto io_res = this->do_stream_read_nolock(hint, size);
    if(io_res < 0)
      return io_res;

    if(io_res == io_result_eof) {
      POSEIDON_LOG_TRACE("End of stream encountered: $1", this);
      this->do_async_shutdown_nolock();
      return io_result_eof;
    }

    // Process the data that have been read.
    lock.unlock();
    this->do_on_async_receive(hint, static_cast<size_t>(io_res));
    lock.assign(this->m_mutex);
    return io_res;
  }

size_t
Abstract_Stream_Socket::
do_write_queue_size(Si_Mutex::unique_lock& lock)
const
  {
    lock.assign(this->m_mutex);

    // Get the size of pending data.
    size_t size = this->m_wqueue.size();
    if(size != 0)
      return size;

    // If a shutdown request is pending, report at least one byte.
    if(this->m_cstate == connection_state_closing)
      return 1;

    // There is nothing to write.
    return 0;
  }

IO_Result
Abstract_Stream_Socket::
do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* /*hint*/, size_t /*size*/)
  {
    lock.assign(this->m_mutex);

    // If the stream is in CLOSED state, fail.
    if(this->m_cstate == connection_state_closed)
      return io_result_eof;

    // If the stream is in CONNECTING state, mark it ESTABLISHED.
    if(this->m_cstate < connection_state_established) {
      this->m_cstate = connection_state_established;

      lock.unlock();
      this->do_on_async_establish();
      lock.assign(this->m_mutex);
    }

    // Try writing some bytes.
    size_t size = this->m_wqueue.size();
    if(size == 0) {
      if(this->m_cstate <= connection_state_established)
        return io_result_eof;

      // Shut down the connection completely now.
      return this->do_async_shutdown_nolock();
    }

    auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size);
    if(io_res < 0)
      return io_res;

    // Remove data that have been written.
    this->m_wqueue.discard(static_cast<size_t>(io_res));
    return io_res;
  }

void
Abstract_Stream_Socket::
do_on_async_poll_shutdown(int err)
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    this->m_cstate = connection_state_closed;
    lock.unlock();

    this->do_on_async_shutdown(err);
  }

void
Abstract_Stream_Socket::
do_async_connect(const Socket_Address& addr)
  {
    // Lock the stream and examine connection state.
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate != connection_state_initial)
      POSEIDON_THROW("another connection already in progress or established");

    // Initiate the connection.
    this->do_stream_preconnect_nolock();

    // No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current
    // socket is set to the CONNECTING state.
    if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) {
      int err = errno;
      if(err != EINPROGRESS)
        POSEIDON_THROW("failed to initiate connection to '$2'\n"
                       "[`connect()` failed: $1]",
                       noadl::format_errno(err), addr);
    }
    this->m_cstate = connection_state_connecting;
  }

Socket_Address
Abstract_Stream_Socket::
get_remote_address()
const
  {
    // Try getting the remote address.
    Socket_Address::storage_type addrst;
    Socket_Address::size_type addrlen = sizeof(addrst);
    if(::getpeername(this->get_fd(), addrst, &addrlen) != 0)
      POSEIDON_THROW("could not get remote socket address\n"
                     "[`getpeername()` failed: $1]",
                     noadl::format_errno(errno));
    return { addrst, addrlen };
  }

bool
Abstract_Stream_Socket::
async_send(const void* data, size_t size)
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate > connection_state_established)
      return false;

    // Append data to the write queue.
    this->m_wqueue.putn(static_cast<const char*>(data), size);
    lock.unlock();

    // Notify the driver about availability of outgoing data.
    Network_Driver::notify_writable_internal(this);
    return true;
  }

bool
Abstract_Stream_Socket::
async_shutdown()
noexcept
  {
    Si_Mutex::unique_lock lock(this->m_mutex);
    if(this->m_cstate > connection_state_established)
      return false;

    // Initiate asynchronous shutdown.
    this->do_async_shutdown_nolock();
    lock.unlock();

    // Notify the driver about availability of outgoing data.
    Network_Driver::notify_writable_internal(this);
    return true;
  }

}  // namespace poseidon
<|endoftext|>


<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef SERIALIZER_LOG_CONFIG_HPP_
#define SERIALIZER_LOG_CONFIG_HPP_

#include <string>

#include "config/args.hpp"
#include "serializer/types.hpp"
#include "rpc/serialize_macros.hpp"

/* Configuration for the serializer that can change from run to run */

struct log_serializer_dynamic_config_t {
    log_serializer_dynamic_config_t() {
        gc_low_ratio = DEFAULT_GC_LOW_RATIO;
        gc_high_ratio = DEFAULT_GC_HIGH_RATIO;
        read_ahead = true;
        io_batch_factor = DEFAULT_IO_BATCH_FACTOR;
    }

    /* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect
    garbage until it reaches gc_low_ratio. */
    double gc_low_ratio, gc_high_ratio;

    /* The (minimal) batch size of i/o requests being taken from a single i/o account.
    It is a factor because the actual batch size is this factor multiplied by the
    i/o priority of the account. */
    int32_t io_batch_factor;

    /* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives */
    bool read_ahead;

    RDB_MAKE_ME_SERIALIZABLE_4(gc_low_ratio, gc_high_ratio, io_batch_factor, read_ahead);
};

/* This is equivalent to log_serializer_static_config_t below, but is an on-disk
structure. Changes to this change the on-disk database format! */
struct log_serializer_on_disk_static_config_t {
    uint64_t block_size_;
    uint64_t extent_size_;

    // Some helpers
    uint64_t blocks_per_extent() const { return extent_size_ / block_size_; }
    int extent_index(int64_t offset) const { return offset / extent_size_; }

    // Minimize calls to these.
    block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); }
    uint64_t extent_size() const { return extent_size_; }
};

/* Configuration for the serializer that is set when the database is created */
struct log_serializer_static_config_t : public log_serializer_on_disk_static_config_t {
    log_serializer_static_config_t() {
        extent_size_ = DEFAULT_EXTENT_SIZE;
        block_size_ = DEFAULT_BTREE_BLOCK_SIZE;
    }

    RDB_MAKE_ME_SERIALIZABLE_2(block_size_, extent_size_);
};

#endif /* SERIALIZER_LOG_CONFIG_HPP_ */

<commit_msg>Made extent_index return an unsigned int, not an int.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef SERIALIZER_LOG_CONFIG_HPP_
#define SERIALIZER_LOG_CONFIG_HPP_

#include <string>

#include "config/args.hpp"
#include "serializer/types.hpp"
#include "rpc/serialize_macros.hpp"

/* Configuration for the serializer that can change from run to run */

struct log_serializer_dynamic_config_t {
    log_serializer_dynamic_config_t() {
        gc_low_ratio = DEFAULT_GC_LOW_RATIO;
        gc_high_ratio = DEFAULT_GC_HIGH_RATIO;
        read_ahead = true;
        io_batch_factor = DEFAULT_IO_BATCH_FACTOR;
    }

    /* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect
    garbage until it reaches gc_low_ratio. */
    double gc_low_ratio, gc_high_ratio;

    /* The (minimal) batch size of i/o requests being taken from a single i/o account.
    It is a factor because the actual batch size is this factor multiplied by the
    i/o priority of the account. */
    int32_t io_batch_factor;

    /* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives */
    bool read_ahead;

    RDB_MAKE_ME_SERIALIZABLE_4(gc_low_ratio, gc_high_ratio, io_batch_factor, read_ahead);
};

/* This is equivalent to log_serializer_static_config_t below, but is an on-disk
structure. Changes to this change the on-disk database format! */
struct log_serializer_on_disk_static_config_t {
    uint64_t block_size_;
    uint64_t extent_size_;

    // Some helpers
    uint64_t blocks_per_extent() const { return extent_size_ / block_size_; }
    unsigned int extent_index(int64_t offset) const { return offset / extent_size_; }

    // Minimize calls to these.
    block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); }
    uint64_t extent_size() const { return extent_size_; }
};

/* Configuration for the serializer that is set when the database is created */
struct log_serializer_static_config_t : public log_serializer_on_disk_static_config_t {
    log_serializer_static_config_t() {
        extent_size_ = DEFAULT_EXTENT_SIZE;
        block_size_ = DEFAULT_BTREE_BLOCK_SIZE;
    }

    RDB_MAKE_ME_SERIALIZABLE_2(block_size_, extent_size_);
};

#endif /* SERIALIZER_LOG_CONFIG_HPP_ */

<|endoftext|>


<commit_before>#include <QTimer>

#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"

namespace {

const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec

}

SINGLETON_IMPL(ServerStatusService)

ServerStatusService::ServerStatusService(QObject *parent)
    : QObject(parent)
{
    refresh_timer_ = new QTimer(this);
    refresh_unconnected_timer_ = new QTimer(this);
    connect(refresh_timer_, SIGNAL(timeout()),
            this, SLOT(refresh()));
    connect(refresh_unconnected_timer_, SIGNAL(timeout()),
            this, SLOT(refreshUnconnected()));
    refresh();
}

void ServerStatusService::start()
{
    refresh_timer_->start(kRefreshInterval);
    refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}

void ServerStatusService::stop()
{
    refresh_timer_->stop();
    refresh_unconnected_timer_->stop();
}

void ServerStatusService::refresh(bool only_refresh_unconnected)
{
    const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
    for (size_t i = 0; i < accounts.size(); i++) {
        const QUrl& url = accounts[i].serverUrl;
        if (requests_.contains(url.host())) {
            return;
        }

        if (!statuses_.contains(url.host())) {
            statuses_[url.host()] = ServerStatus(url, false);
        }

        if (only_refresh_unconnected && isServerConnected(url)) {
            return;
        }
        pingServer(url);
    }
}

void ServerStatusService::pingServer(const QUrl& url)
{
    PingServerRequest *req = new PingServerRequest(url);
    connect(req, SIGNAL(success()),
            this, SLOT(onPingServerSuccess()));
    connect(req, SIGNAL(failed(const ApiError&)),
            this, SLOT(onPingServerFailed()));
    req->send();
    requests_[url.host()] = req;
}

void ServerStatusService::onPingServerSuccess()
{
    PingServerRequest *req = (PingServerRequest *)sender();
    statuses_[req->url().host()] = ServerStatus(req->url(), true);
    emit serverStatusChanged();
    requests_.take(req->url().host())->deleteLater();
}

void ServerStatusService::onPingServerFailed()
{
    PingServerRequest *req = (PingServerRequest *)sender();
    statuses_[req->url().host()] = ServerStatus(req->url(), false);
    emit serverStatusChanged();
    requests_.take(req->url().host())->deleteLater();
}

bool ServerStatusService::allServersConnected() const
{
    foreach (const ServerStatus& status, statuses()) {
        if (!status.connected) {
            return false;
        }
    }

    return true;
}

bool ServerStatusService::allServersDisconnected() const
{
    foreach (const ServerStatus& status, statuses()) {
        if (status.connected) {
            return false;
        }
    }

    return true;
}

bool ServerStatusService::isServerConnected(const QUrl& url) const
{
    return statuses_.value(url.host()).connected;
}
<commit_msg>Set default server connection to true.<commit_after>#include <QTimer>

#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"

namespace {

const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec

}

SINGLETON_IMPL(ServerStatusService)

ServerStatusService::ServerStatusService(QObject *parent)
    : QObject(parent)
{
    refresh_timer_ = new QTimer(this);
    refresh_unconnected_timer_ = new QTimer(this);
    connect(refresh_timer_, SIGNAL(timeout()),
            this, SLOT(refresh()));
    connect(refresh_unconnected_timer_, SIGNAL(timeout()),
            this, SLOT(refreshUnconnected()));
    refresh();
}

void ServerStatusService::start()
{
    refresh_timer_->start(kRefreshInterval);
    refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}

void ServerStatusService::stop()
{
    refresh_timer_->stop();
    refresh_unconnected_timer_->stop();
}

void ServerStatusService::refresh(bool only_refresh_unconnected)
{
    const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
    for (size_t i = 0; i < accounts.size(); i++) {
        const QUrl& url = accounts[i].serverUrl;
        if (requests_.contains(url.host())) {
            return;
        }

        if (!statuses_.contains(url.host())) {
            statuses_[url.host()] = ServerStatus(url, true);
        }

        if (only_refresh_unconnected && isServerConnected(url)) {
            return;
        }
        pingServer(url);
    }
}

void ServerStatusService::pingServer(const QUrl& url)
{
    PingServerRequest *req = new PingServerRequest(url);
    connect(req, SIGNAL(success()),
            this, SLOT(onPingServerSuccess()));
    connect(req, SIGNAL(failed(const ApiError&)),
            this, SLOT(onPingServerFailed()));
    req->send();
    requests_[url.host()] = req;
}

void ServerStatusService::onPingServerSuccess()
{
    PingServerRequest *req = (PingServerRequest *)sender();
    statuses_[req->url().host()] = ServerStatus(req->url(), true);
    emit serverStatusChanged();
    requests_.take(req->url().host())->deleteLater();
}

void ServerStatusService::onPingServerFailed()
{
    PingServerRequest *req = (PingServerRequest *)sender();
    statuses_[req->url().host()] = ServerStatus(req->url(), false);
    emit serverStatusChanged();
    requests_.take(req->url().host())->deleteLater();
}

bool ServerStatusService::allServersConnected() const
{
    foreach (const ServerStatus& status, statuses()) {
        if (!status.connected) {
            return false;
        }
    }

    return true;
}

bool ServerStatusService::allServersDisconnected() const
{
    foreach (const ServerStatus& status, statuses()) {
        if (status.connected) {
            return false;
        }
    }

    return true;
}

bool ServerStatusService::isServerConnected(const QUrl& url) const
{
    return statuses_.value(url.host()).connected;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SwXMLBlockImport.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 09:05:01 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;

sal_Char __READONLY_DATA sXML_np__block_list[] = "_block-list";
sal_Char __READONLY_DATA sXML_np__office[] = "_ooffice";
sal_Char __READONLY_DATA sXML_np__text[] = "_otext";

// #110680#
SwXMLBlockListImport::SwXMLBlockListImport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SwXMLTextBlocks &rBlocks )
:   SvXMLImport( xServiceFactory, 0 ),
    rBlockList (rBlocks)
{
    GetNamespaceMap().Add( OUString ( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__block_list ) ),
                           GetXMLToken ( XML_N_BLOCK_LIST ),
                           XML_NAMESPACE_BLOCKLIST );
}

SwXMLBlockListImport::~SwXMLBlockListImport ( void )
    throw ()
{
}

SvXMLImportContext *SwXMLBlockListImport::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if ( XML_NAMESPACE_BLOCKLIST == nPrefix &&
         IsXMLToken ( rLocalName, XML_BLOCK_LIST ) )
        pContext = new SwXMLBlockListContext( *this, nPrefix, rLocalName,
                                              xAttrList );
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}

// #110680#
SwXMLTextBlockImport::SwXMLTextBlockImport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SwXMLTextBlocks &rBlocks,
    String & rNewText,
    sal_Bool bNewTextOnly )
:   SvXMLImport(xServiceFactory, IMPORT_ALL ),
    rBlockList ( rBlocks ),
    bTextOnly ( bNewTextOnly ),
    m_rText ( rNewText )
{
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),
                            GetXMLToken(XML_N_OFFICE_OOO),
                            XML_NAMESPACE_OFFICE );
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),
                            GetXMLToken(XML_N_TEXT_OOO),
                            XML_NAMESPACE_TEXT );
}

SwXMLTextBlockImport::~SwXMLTextBlockImport ( void )
    throw()
{
}

SvXMLImportContext *SwXMLTextBlockImport::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if( XML_NAMESPACE_OFFICE == nPrefix &&
        IsXMLToken ( rLocalName, bTextOnly ? XML_DOCUMENT : XML_DOCUMENT_CONTENT ) )
        pContext = new SwXMLTextBlockDocumentContext( *this, nPrefix, rLocalName, xAttrList );
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}
void SAL_CALL SwXMLTextBlockImport::endDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException )
{
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.664); FILE MERGED 2005/09/05 13:40:34 rt 1.6.664.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwXMLBlockImport.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:42:45 $
 *
 *  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 _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;

sal_Char __READONLY_DATA sXML_np__block_list[] = "_block-list";
sal_Char __READONLY_DATA sXML_np__office[] = "_ooffice";
sal_Char __READONLY_DATA sXML_np__text[] = "_otext";

// #110680#
SwXMLBlockListImport::SwXMLBlockListImport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SwXMLTextBlocks &rBlocks )
:   SvXMLImport( xServiceFactory, 0 ),
    rBlockList (rBlocks)
{
    GetNamespaceMap().Add( OUString ( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__block_list ) ),
                           GetXMLToken ( XML_N_BLOCK_LIST ),
                           XML_NAMESPACE_BLOCKLIST );
}

SwXMLBlockListImport::~SwXMLBlockListImport ( void )
    throw ()
{
}

SvXMLImportContext *SwXMLBlockListImport::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if ( XML_NAMESPACE_BLOCKLIST == nPrefix &&
         IsXMLToken ( rLocalName, XML_BLOCK_LIST ) )
        pContext = new SwXMLBlockListContext( *this, nPrefix, rLocalName,
                                              xAttrList );
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}

// #110680#
SwXMLTextBlockImport::SwXMLTextBlockImport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SwXMLTextBlocks &rBlocks,
    String & rNewText,
    sal_Bool bNewTextOnly )
:   SvXMLImport(xServiceFactory, IMPORT_ALL ),
    rBlockList ( rBlocks ),
    bTextOnly ( bNewTextOnly ),
    m_rText ( rNewText )
{
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),
                            GetXMLToken(XML_N_OFFICE_OOO),
                            XML_NAMESPACE_OFFICE );
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),
                            GetXMLToken(XML_N_TEXT_OOO),
                            XML_NAMESPACE_TEXT );
}

SwXMLTextBlockImport::~SwXMLTextBlockImport ( void )
    throw()
{
}

SvXMLImportContext *SwXMLTextBlockImport::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if( XML_NAMESPACE_OFFICE == nPrefix &&
        IsXMLToken ( rLocalName, bTextOnly ? XML_DOCUMENT : XML_DOCUMENT_CONTENT ) )
        pContext = new SwXMLTextBlockDocumentContext( *this, nPrefix, rLocalName, xAttrList );
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}
void SAL_CALL SwXMLTextBlockImport::endDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException )
{
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: writerwordglue.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:07:20 $
 *
 *  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
 *
 ************************************************************************/

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
/// @HTML

#ifndef SW_WRITERWORDGLUE
#define SW_WRITERWORDGLUE

#ifndef WW_NEEDED_CAST_HXX
#   include "needed_cast.hxx"
#endif
#ifndef WW_TYPES
#   include "types.hxx"
#endif

class SwFrmFmt;
class SfxItemSet;
class SwDoc;
class SwTxtFmtColl;
class String;
class PoolItems;

namespace sw
{
    namespace types
    {
        /** A static_cast style cast for conversion of word types to writer's

            There are a number of places where the winword types are larger
            than the writer equivalents requiring a cast to silence warnings.
            To avoid throwing away this useful information writer_cast is used
            to identify where writer's types are smaller than word's.

            Based on needed_cast it will compile time assert if the cast
            becomes unnecessary at any time in the future.

            @tplparam
            Ret the desired return type

            @tplparam
            Param the type of the in param

            @param
            in the value to cast from Param to Ret

            @return in casted to type Ret
        */
        template<typename Ret, typename Param> Ret writer_cast(Param in)
        {
            return ww::needed_cast<Ret, Param>(in);
        }

        /** A static_cast style cast for conversion of writer types to word's

            There are a number of places where the writer types are larger than
            the winword equivalents requiring a cast to silence warnings.  To
            avoid throwing away this useful information writer_cast is used to
            identify where word's types are smaller than writers's.

            Based on needed_cast it will compile time assert if the cast
            becomes unnecessary at any time in the future.

            @tplparam
            Ret the desired return type

            @tplparam
            Param the type of the in param

            @param
            in the value to cast from Param to Ret

            @return in casted to type Ret
        */
        template<typename Ret, typename Param> Ret msword_cast(Param in)
        {
            return ww::needed_cast<Ret, Param>(in);
        }

        /** If a page dimension is close to a standard page size, snap to it.

            Commonly a page dimension is slightly different from a standard
            page size, so close that its likely a rounding error after
            creeping in. Use this to snap to standard sizes when within a
            trivial distance from a standard size.

            @param
            nSize the dimension to test against standard dimensions

            @return New dimension to use, equal to nSize unless within a
            trivial amount of a standard page dimension

            @author
            Caolán McNamara
        */
        long SnapPageDimension(long nSize) throw();
    }

    namespace util
    {
        /** See if two page formats can be expressed as a single word section

            Word doesn't have the idea of page descriptors and follow styles
            like writer does, the only thing it has is a section with a
            different title page. The only difference of the title page from
            the rest of the section is different headers/footers, everything
            else is the same.

            So this function compares two writer page fmts and sees if the
            follow frame and the title frame are the same from word persecptive
            except for the content of their headers.

            @return true if the rTitleFmt followed by rFollowFmt could be
            expressed in word as a single word Section with different title
            page enabled.

            @author
            Caolán McNamara

            @see #i4320#/#i14509#/#i11717# for examples
        */
        bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt,
            const SwFrmFmt &rFollowFmt);

        /** Make export a word section top/bottom values easy

            The top and bottom margins in word and writer are expressed in very
            different ways. This class provides the equivalent word values for
            header/footer distances from a given writer attrset of a page

            @author
            Caolán McNamara
        */
        class HdFtDistanceGlue
        {
        private:
            bool mbHasHeader;
            bool mbHasFooter;
        public:
            sal_uInt16 dyaHdrTop;
            sal_uInt16 dyaHdrBottom;
            sal_uInt16 dyaTop;
            sal_uInt16 dyaBottom;
            HdFtDistanceGlue(const SfxItemSet &rPage);
            bool HasHeader() const { return mbHasHeader; }
            bool HasFooter() const { return mbHasFooter; }

            /** Is the top of the page the same in both objects

                Ignoring the difference in header and footers, will the main
                document text have the same top/bottom bounds in word between
                both these objects.

                @param
                rOther the other HdFtDistanceGlue to compare against

                @return true if the main text areas top and bottom is at the
                same location, false otherwise.
            */
            bool EqualTopBottom(const HdFtDistanceGlue &rOther) const;

        };
    }
}

#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS thaiissues (1.4.808); FILE MERGED<commit_after>/*************************************************************************
 *
 *  $RCSfile: writerwordglue.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-11-16 09:35:26 $
 *
 *  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): cmc@openoffice.org
 *
 *
 ************************************************************************/

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
/// @HTML

#ifndef SW_WRITERWORDGLUE
#define SW_WRITERWORDGLUE

#ifndef WW_NEEDED_CAST_HXX
#   include "needed_cast.hxx"
#endif
#ifndef WW_TYPES
#   include "types.hxx"
#endif

class SwFrmFmt;
class SfxItemSet;
class SwDoc;
class SwTxtFmtColl;
class String;
class PoolItems;

namespace sw
{
    namespace types
    {
        /** A static_cast style cast for conversion of word types to writer's

            There are a number of places where the winword types are larger
            than the writer equivalents requiring a cast to silence warnings.
            To avoid throwing away this useful information writer_cast is used
            to identify where writer's types are smaller than word's.

            Based on needed_cast it will compile time assert if the cast
            becomes unnecessary at any time in the future.

            @tplparam
            Ret the desired return type

            @tplparam
            Param the type of the in param

            @param
            in the value to cast from Param to Ret

            @return in casted to type Ret
        */
        template<typename Ret, typename Param> Ret writer_cast(Param in)
        {
            return ww::needed_cast<Ret, Param>(in);
        }

        /** A static_cast style cast for conversion of writer types to word's

            There are a number of places where the writer types are larger than
            the winword equivalents requiring a cast to silence warnings.  To
            avoid throwing away this useful information writer_cast is used to
            identify where word's types are smaller than writers's.

            Based on needed_cast it will compile time assert if the cast
            becomes unnecessary at any time in the future.

            @tplparam
            Ret the desired return type

            @tplparam
            Param the type of the in param

            @param
            in the value to cast from Param to Ret

            @return in casted to type Ret
        */
        template<typename Ret, typename Param> Ret msword_cast(Param in)
        {
            return ww::needed_cast<Ret, Param>(in);
        }

        /** If a page dimension is close to a standard page size, snap to it.

            Commonly a page dimension is slightly different from a standard
            page size, so close that its likely a rounding error after
            creeping in. Use this to snap to standard sizes when within a
            trivial distance from a standard size.

            @param
            nSize the dimension to test against standard dimensions

            @return New dimension to use, equal to nSize unless within a
            trivial amount of a standard page dimension

            @author
            Caolán McNamara
        */
        long SnapPageDimension(long nSize) throw();
    }

    namespace util
    {
        /** See if two page formats can be expressed as a single word section

            Word doesn't have the idea of page descriptors and follow styles
            like writer does, the only thing it has is a section with a
            different title page. The only difference of the title page from
            the rest of the section is different headers/footers, everything
            else is the same.

            So this function compares two writer page fmts and sees if the
            follow frame and the title frame are the same from word persecptive
            except for the content of their headers.

            @return true if the rTitleFmt followed by rFollowFmt could be
            expressed in word as a single word Section with different title
            page enabled.

            @author
            Caolán McNamara

            @see #i4320#/#i14509#/#i11717# for examples
        */
        bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt,
            const SwFrmFmt &rFollowFmt);

        /** Make export a word section top/bottom values easy

            The top and bottom margins in word and writer are expressed in very
            different ways. This class provides the equivalent word values for
            header/footer distances from a given writer attrset of a page

            @author
            Caolán McNamara
        */
        class HdFtDistanceGlue
        {
        private:
            bool mbHasHeader;
            bool mbHasFooter;
        public:
            sal_uInt16 dyaHdrTop;
            sal_uInt16 dyaHdrBottom;
            sal_uInt16 dyaTop;
            sal_uInt16 dyaBottom;
            HdFtDistanceGlue(const SfxItemSet &rPage);
            bool HasHeader() const { return mbHasHeader; }
            bool HasFooter() const { return mbHasFooter; }

            /** Is the top of the page the same in both objects

                Ignoring the difference in header and footers, will the main
                document text have the same top/bottom bounds in word between
                both these objects.

                @param
                rOther the other HdFtDistanceGlue to compare against

                @return true if the main text areas top and bottom is at the
                same location, false otherwise.
            */
            bool EqualTopBottom(const HdFtDistanceGlue &rOther) const;

        };
    }
}

#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>pretty it up a little<commit_after><|endoftext|>


<commit_before>#include <Eigen/Dense>
#include <Eigen/Sparse>

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <chrono>

#include <unsupported/Eigen/SparseExtra>
#include <Eigen/Sparse>

#include <omp.h>

#include "macau.h"
#include "mvnormal.h"
#include "utils.h"
#include "latentprior.h"

using namespace std;
using namespace Eigen;

void Macau::addPrior(ILatentPrior* prior) {
  priors.push_back( prior );
}

void Macau::setPrecision(double p) {
  alpha = p;
}

void Macau::setSamples(int b, int n) {
  burnin = b;
  nsamples = n;
}

void Macau::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) {
  Y.resize(nrows, ncols);
  sparseFromIJV(Y, rows, cols, values, N);
  Yt = Y.transpose();
  mean_rating = Y.sum() / Y.nonZeros();
}

void Macau::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) {
  Ytest.resize(nrows, ncols);
  sparseFromIJV(Ytest, rows, cols, values, N);
}

double Macau::getRmseTest() { return rmse_test; }

void sparseFromIJV(SparseMatrix<double> &X, int* rows, int* cols, double* values, int N) {
  typedef Triplet<double> T;
  std::vector<T> tripletList;
  tripletList.reserve(N);
  for (int n = 0; n < N; n++) {
    tripletList.push_back(T(rows[n], cols[n], values[n]));
  }
  X.setFromTriplets(tripletList.begin(), tripletList.end());
}

void Macau::init() {
  unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
  if (priors.size() != 2) {
    throw std::runtime_error("Only 2 priors are supported.");
  }
  init_bmrng(seed1);
  MatrixXd* U = new MatrixXd(num_latent, Y.rows());
  MatrixXd* V = new MatrixXd(num_latent, Y.cols());
  U->setZero();
  V->setZero();
  samples.push_back(U);
  samples.push_back(V);
}

Macau::~Macau() {
  for (unsigned i = 0; i < samples.size(); i++) {
    delete samples[i];
  }
}

inline double sqr(double x) { return x*x; }

void Macau::run() {
  init();
  std::cout << "Sampling" << endl;

  const int num_rows = Y.rows();
  const int num_cols = Y.cols();
  VectorXd predictions = VectorXd::Zero( Ytest.nonZeros() );

  auto start = tick();
  for (int i = 0; i < burnin + nsamples; i++) {
    if (i == burnin) {
      printf(" ====== Burn-in complete, averaging samples ====== \n");
    }
    auto starti = tick();

    // sample latent vectors
    priors[0]->sample_latents(*(samples[0]), Yt, mean_rating, *(samples[1]), alpha, num_latent);
    priors[1]->sample_latents(*(samples[1]), Y,  mean_rating, *(samples[0]), alpha, num_latent);

    // Sample hyperparams
    priors[0]->update_prior(*(samples[0]));
    priors[1]->update_prior(*(samples[1]));

    auto eval = eval_rmse(Ytest, (i < burnin) ? 0 : (i - burnin + 1), predictions, *(samples[1]), *(samples[0]), mean_rating);

    auto endi = tick();
    auto elapsed = endi - start;
    double samples_per_sec = (i + 1) * (num_rows + num_cols) / elapsed;
    double elapsedi = endi - starti;

    printf("Iter %d: RMSE: %4.4f\tavg RMSE: %4.4f\tFU(%1.3e) FV(%1.3e) [took %0.1fs, Samples/sec: %6.1f]\n", i, eval.first, eval.second, samples[0]->norm(), samples[1]->norm(), elapsedi, samples_per_sec);
    rmse_test = eval.second;
  }
}

std::pair<double,double> eval_rmse(SparseMatrix<double> & P, const int n, VectorXd & predictions, const MatrixXd &sample_m, const MatrixXd &sample_u, double mean_rating)
{
  // TODO: parallelize
  double se = 0.0, se_avg = 0.0;
  unsigned idx = 0;
  for (int k = 0; k < P.outerSize(); ++k) {
    for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) {
      const double pred = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating;
      se += sqr(it.value() - pred);

      const double pred_avg = (n == 0) ? pred : (predictions[idx] + (pred - predictions[idx]) / n);
      se_avg += sqr(it.value() - pred_avg);
      predictions[idx++] = pred_avg;
    }
  }

  const unsigned N = P.nonZeros();
  const double rmse = sqrt( se / N );
  const double rmse_avg = sqrt( se_avg / N );
  return std::make_pair(rmse, rmse_avg);
}
<commit_msg>cleaned syntax<commit_after>#include <Eigen/Dense>
#include <Eigen/Sparse>

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <chrono>

#include <unsupported/Eigen/SparseExtra>
#include <Eigen/Sparse>

#include <omp.h>

#include "macau.h"
#include "mvnormal.h"
#include "utils.h"
#include "latentprior.h"

using namespace std;
using namespace Eigen;

void Macau::addPrior(ILatentPrior* prior) {
  priors.push_back( prior );
}

void Macau::setPrecision(double p) {
  alpha = p;
}

void Macau::setSamples(int b, int n) {
  burnin = b;
  nsamples = n;
}

void Macau::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) {
  Y.resize(nrows, ncols);
  sparseFromIJV(Y, rows, cols, values, N);
  Yt = Y.transpose();
  mean_rating = Y.sum() / Y.nonZeros();
}

void Macau::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) {
  Ytest.resize(nrows, ncols);
  sparseFromIJV(Ytest, rows, cols, values, N);
}

double Macau::getRmseTest() { return rmse_test; }

void sparseFromIJV(SparseMatrix<double> &X, int* rows, int* cols, double* values, int N) {
  typedef Triplet<double> T;
  std::vector<T> tripletList;
  tripletList.reserve(N);
  for (int n = 0; n < N; n++) {
    tripletList.push_back(T(rows[n], cols[n], values[n]));
  }
  X.setFromTriplets(tripletList.begin(), tripletList.end());
}

void Macau::init() {
  unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
  if (priors.size() != 2) {
    throw std::runtime_error("Only 2 priors are supported.");
  }
  init_bmrng(seed1);
  MatrixXd* U = new MatrixXd(num_latent, Y.rows());
  MatrixXd* V = new MatrixXd(num_latent, Y.cols());
  U->setZero();
  V->setZero();
  samples.push_back(U);
  samples.push_back(V);
}

Macau::~Macau() {
  for (unsigned i = 0; i < samples.size(); i++) {
    delete samples[i];
  }
}

inline double sqr(double x) { return x*x; }

void Macau::run() {
  init();
  std::cout << "Sampling" << endl;

  const int num_rows = Y.rows();
  const int num_cols = Y.cols();
  VectorXd predictions = VectorXd::Zero( Ytest.nonZeros() );

  auto start = tick();
  for (int i = 0; i < burnin + nsamples; i++) {
    if (i == burnin) {
      printf(" ====== Burn-in complete, averaging samples ====== \n");
    }
    auto starti = tick();

    // sample latent vectors
    priors[0]->sample_latents(*samples[0], Yt, mean_rating, *samples[1], alpha, num_latent);
    priors[1]->sample_latents(*samples[1], Y,  mean_rating, *samples[0], alpha, num_latent);

    // Sample hyperparams
    priors[0]->update_prior(*samples[0]);
    priors[1]->update_prior(*samples[1]);

    auto eval = eval_rmse(Ytest, (i < burnin) ? 0 : (i - burnin + 1), predictions, *samples[1], *samples[0], mean_rating);

    auto endi = tick();
    auto elapsed = endi - start;
    double samples_per_sec = (i + 1) * (num_rows + num_cols) / elapsed;
    double elapsedi = endi - starti;

    printf("Iter %d: RMSE: %4.4f\tavg RMSE: %4.4f\tFU(%1.3e) FV(%1.3e) [took %0.1fs, Samples/sec: %6.1f]\n", i, eval.first, eval.second, samples[0]->norm(), samples[1]->norm(), elapsedi, samples_per_sec);
    rmse_test = eval.second;
  }
}

std::pair<double,double> eval_rmse(SparseMatrix<double> & P, const int n, VectorXd & predictions, const MatrixXd &sample_m, const MatrixXd &sample_u, double mean_rating)
{
  // TODO: parallelize
  double se = 0.0, se_avg = 0.0;
  unsigned idx = 0;
  for (int k = 0; k < P.outerSize(); ++k) {
    for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) {
      const double pred = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating;
      se += sqr(it.value() - pred);

      const double pred_avg = (n == 0) ? pred : (predictions[idx] + (pred - predictions[idx]) / n);
      se_avg += sqr(it.value() - pred_avg);
      predictions[idx++] = pred_avg;
    }
  }

  const unsigned N = P.nonZeros();
  const double rmse = sqrt( se / N );
  const double rmse_avg = sqrt( se_avg / N );
  return std::make_pair(rmse, rmse_avg);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see http://glvis.org.
//
// GLVis 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) version 2.1 dated February 1999.

#ifndef GLVIS_VSSOLUTION
#define GLVIS_VSSOLUTION

#include "mfem.hpp"
using namespace mfem;

// Rendering large numbers of text objects for element or vertex
// numberings is slow.  Turn it off above some entity count.
#define MAX_RENDER_NUMBERING 1000

// Visualization header file

class VisualizationSceneSolution : public VisualizationSceneScalarData
{
protected:
   Vector *v_normals;
   GridFunction *rsol;

   int drawmesh, drawelems, drawnums;
   int displlist, linelist, lcurvelist;
   int bdrlist, drawbdr, draw_cp, cp_list;
   int e_nums_list, v_nums_list;

   void Init();

   void FindNewBox(double rx[], double ry[], double rval[]);

   void DrawCPLine(DenseMatrix &pointmat, Vector &values, Array<int> &ind);

   void GetRefinedDetJ(int i, const IntegrationRule &ir,
                       Vector &vals, DenseMatrix &tr);

   // redefined for vector solution
   virtual void GetRefinedValues(int i, const IntegrationRule &ir,
                                 Vector &vals, DenseMatrix &tr);
   virtual int GetRefinedValuesAndNormals(int i, const IntegrationRule &ir,
                                          Vector &vals, DenseMatrix &tr,
                                          DenseMatrix &normals);

   void DrawLevelCurves(Array<int> &RG, DenseMatrix &pointmat,
                        Vector &values, int sides, Array<double> &lvl,
                        int flat = 0);

   int GetAutoRefineFactor();

   // Used for drawing markers for element and vertex numberings
   double GetElementLengthScale(int k);

public:
   int shading, TimesToRefine, EdgeRefineFactor;

   int attr_to_show, bdr_attr_to_show;
   Array<int> el_attr_to_show, bdr_el_attr_to_show;

   VisualizationSceneSolution();
   VisualizationSceneSolution(Mesh &m, Vector &s, Vector *normals = NULL);

   virtual ~VisualizationSceneSolution();

   void SetGridFunction(GridFunction & u) { rsol = &u; }

   void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,
                           GridFunction *new_u = NULL);

   virtual void SetNewScalingFromBox();
   virtual void FindNewBox(bool prepare);
   virtual void FindNewValueRange(bool prepare);
   virtual void FindNewBoxAndValueRange(bool prepare)
   { FindNewBox(prepare); }
   virtual void FindMeshBox(bool prepare);

   virtual void ToggleLogscale(bool print);
   virtual void UpdateLevelLines() { PrepareLevelCurves(); }
   virtual void UpdateValueRange(bool prepare);

   void PrepareWithNormals();
   void PrepareFlat();
   void PrepareFlat2();

   virtual void PrepareLines();
   void PrepareLines2();
   void PrepareLines3();

   virtual void Prepare();
   void PrepareLevelCurves();
   void PrepareLevelCurves2();

   void PrepareBoundary();

   void PrepareNumbering();
   void PrepareElementNumbering();
   void PrepareElementNumbering1();
   void PrepareElementNumbering2();
   void PrepareVertexNumbering();
   void PrepareVertexNumbering1();
   void PrepareVertexNumbering2();

   void PrepareCP();

   virtual void Draw();

   void ToggleDrawBdr()
   { drawbdr = !drawbdr; }

   virtual void ToggleDrawElems();

   void ToggleDrawMesh() { drawmesh = (drawmesh+1)%3; }

   void ToggleDrawNumberings() { drawnums = (drawnums+1)%3; }

   virtual void SetShading(int, bool);
   void ToggleShading();

   void ToggleDrawCP() { draw_cp = !draw_cp; PrepareCP(); }

   virtual void SetRefineFactors(int, int);
   virtual void AutoRefine();
   virtual void ToggleAttributes(Array<int> &attr_list);
};

void DrawNumberMarker(const double x[3], double dx, int n);

void DrawTriangle(const double pts[][3], const double cv[],
                  const double minv, const double maxv);

void DrawQuad(const double pts[][3], const double cv[],
              const double minv, const double maxv);

void DrawPatch(const DenseMatrix &pts, Vector &vals, DenseMatrix &normals,
               const int n, const Array<int> &ind, const double minv,
               const double maxv, const int normals_opt = 0);

#endif
<commit_msg>fix prototype<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see http://glvis.org.
//
// GLVis 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) version 2.1 dated February 1999.

#ifndef GLVIS_VSSOLUTION
#define GLVIS_VSSOLUTION

#include "mfem.hpp"
using namespace mfem;

// Rendering large numbers of text objects for element or vertex
// numberings is slow.  Turn it off above some entity count.
#define MAX_RENDER_NUMBERING 1000

// Visualization header file

class VisualizationSceneSolution : public VisualizationSceneScalarData
{
protected:
   Vector *v_normals;
   GridFunction *rsol;

   int drawmesh, drawelems, drawnums;
   int displlist, linelist, lcurvelist;
   int bdrlist, drawbdr, draw_cp, cp_list;
   int e_nums_list, v_nums_list;

   void Init();

   void FindNewBox(double rx[], double ry[], double rval[]);

   void DrawCPLine(DenseMatrix &pointmat, Vector &values, Array<int> &ind);

   void GetRefinedDetJ(int i, const IntegrationRule &ir,
                       Vector &vals, DenseMatrix &tr);

   // redefined for vector solution
   virtual void GetRefinedValues(int i, const IntegrationRule &ir,
                                 Vector &vals, DenseMatrix &tr);
   virtual int GetRefinedValuesAndNormals(int i, const IntegrationRule &ir,
                                          Vector &vals, DenseMatrix &tr,
                                          DenseMatrix &normals);

   void DrawLevelCurves(Array<int> &RG, DenseMatrix &pointmat,
                        Vector &values, int sides, Array<double> &lvl,
                        int flat = 0);

   int GetAutoRefineFactor();

   // Used for drawing markers for element and vertex numberings
   double GetElementLengthScale(int k);

public:
   int shading, TimesToRefine, EdgeRefineFactor;

   int attr_to_show, bdr_attr_to_show;
   Array<int> el_attr_to_show, bdr_el_attr_to_show;

   VisualizationSceneSolution();
   VisualizationSceneSolution(Mesh &m, Vector &s, Vector *normals = NULL);

   virtual ~VisualizationSceneSolution();

   void SetGridFunction(GridFunction & u) { rsol = &u; }

   void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,
                           GridFunction *new_u = NULL);

   virtual void SetNewScalingFromBox();
   virtual void FindNewBox(bool prepare);
   virtual void FindNewValueRange(bool prepare);
   virtual void FindNewBoxAndValueRange(bool prepare)
   { FindNewBox(prepare); }
   virtual void FindMeshBox(bool prepare);

   virtual void ToggleLogscale(bool print);
   virtual void UpdateLevelLines() { PrepareLevelCurves(); }
   virtual void UpdateValueRange(bool prepare);

   void PrepareWithNormals();
   void PrepareFlat();
   void PrepareFlat2();

   virtual void PrepareLines();
   void PrepareLines2();
   void PrepareLines3();

   virtual void Prepare();
   void PrepareLevelCurves();
   void PrepareLevelCurves2();

   void PrepareBoundary();

   void PrepareNumbering();
   void PrepareElementNumbering();
   void PrepareElementNumbering1();
   void PrepareElementNumbering2();
   void PrepareVertexNumbering();
   void PrepareVertexNumbering1();
   void PrepareVertexNumbering2();

   void PrepareCP();

   virtual void Draw();

   void ToggleDrawBdr()
   { drawbdr = !drawbdr; }

   virtual void ToggleDrawElems();

   void ToggleDrawMesh() { drawmesh = (drawmesh+1)%3; }

   void ToggleDrawNumberings() { drawnums = (drawnums+1)%3; }

   virtual void SetShading(int, bool);
   void ToggleShading();

   void ToggleDrawCP() { draw_cp = !draw_cp; PrepareCP(); }

   virtual void SetRefineFactors(int, int);
   virtual void AutoRefine();
   virtual void ToggleAttributes(Array<int> &attr_list);
};

void DrawNumberedMarker(const double x[3], double dx, int n);

void DrawTriangle(const double pts[][3], const double cv[],
                  const double minv, const double maxv);

void DrawQuad(const double pts[][3], const double cv[],
              const double minv, const double maxv);

void DrawPatch(const DenseMatrix &pts, Vector &vals, DenseMatrix &normals,
               const int n, const Array<int> &ind, const double minv,
               const double maxv, const int normals_opt = 0);

#endif
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2017 nariakiiwatani

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 "IPAddress.h"
#include "ofConstants.h"

#if defined(TARGET_OSX) || defined(TARGET_OF_IOS) || defined(TARGET_LINUX)
#include <ifaddrs.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>

using namespace std;

std::vector<IPAddress::IPv4> IPAddress::getv4()
{
	struct ifaddrs *ifas, *ifa;
	if(getifaddrs(&ifas) != 0) {
		return {};
	}
	vector<IPv4> ret;
	for(ifa = ifas; ifa != nullptr; ifa=ifa->ifa_next) {
		if (ifa->ifa_addr->sa_family == AF_INET) {
			IPv4 result;
			result.name = ifa->ifa_name;
			auto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {
				char str[INET_ADDRSTRLEN] = {};
				dst_raw = ifa_addr->sin_addr.s_addr;
				inet_ntop(AF_INET, &dst_raw, str, sizeof(str));
				dst_str = str;
			};
			get_address((struct sockaddr_in *)ifa->ifa_addr, result.ip_raw, result.ip);
			get_address((struct sockaddr_in *)ifa->ifa_netmask, result.netmask_raw, result.netmask);
			if((ifa->ifa_flags & IFF_BROADCAST) != 0) {
				get_address((struct sockaddr_in *)ifa->ifa_dstaddr, result.broadcast_raw, result.broadcast);
			}
			else {
				result.broadcast_raw = 0;
				result.broadcast = "";
			}
			ret.push_back(result);
		}
	}
	freeifaddrs(ifas);
	return ret;
}

bool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const
{
	return (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);
}

#else
std::vector<IPAddress::IPv4> IPAddress::getv4() { return {}; }
bool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const { return false; }
#endif
<commit_msg>Get local IP addresses automatically on WIN32<commit_after>/*
The MIT License (MIT)

Copyright (c) 2017 nariakiiwatani

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 "IPAddress.h"
#include "ofConstants.h"

#if defined(TARGET_OSX) || defined(TARGET_OF_IOS) || defined(TARGET_LINUX)
#include <ifaddrs.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>

using namespace std;

std::vector<IPAddress::IPv4> IPAddress::getv4()
{
	struct ifaddrs *ifas, *ifa;
	if(getifaddrs(&ifas) != 0) {
		return {};
	}
	vector<IPv4> ret;
	for(ifa = ifas; ifa != nullptr; ifa=ifa->ifa_next) {
		if (ifa->ifa_addr->sa_family == AF_INET) {
			IPv4 result;
			result.name = ifa->ifa_name;
			auto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {
				char str[INET_ADDRSTRLEN] = {};
				dst_raw = ifa_addr->sin_addr.s_addr;
				inet_ntop(AF_INET, &dst_raw, str, sizeof(str));
				dst_str = str;
			};
			get_address((struct sockaddr_in *)ifa->ifa_addr, result.ip_raw, result.ip);
			get_address((struct sockaddr_in *)ifa->ifa_netmask, result.netmask_raw, result.netmask);
			if((ifa->ifa_flags & IFF_BROADCAST) != 0) {
				get_address((struct sockaddr_in *)ifa->ifa_dstaddr, result.broadcast_raw, result.broadcast);
			}
			else {
				result.broadcast_raw = 0;
				result.broadcast = "";
			}
			ret.push_back(result);
		}
	}
	freeifaddrs(ifas);
	return ret;
}

bool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const
{
	return (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);
}

#elif defined(TARGET_WIN32)
#include <ws2tcpip.h>
std::vector<IPAddress::IPv4> IPAddress::getv4()
{
	WSADATA ws_data;
	if(WSAStartup(WINSOCK_VERSION, &ws_data) != 0) {
		return {};
	}

	SOCKET socket = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
	if(socket == SOCKET_ERROR) {
		return {};
	}

	INTERFACE_INFO if_info[32];
	unsigned long num_bytes;
	if(WSAIoctl(socket, SIO_GET_INTERFACE_LIST, 0, 0, &if_info, sizeof(if_info), &num_bytes, 0, 0) == SOCKET_ERROR) {
		return {};
	}

	vector<IPv4> ret;
	int num_if = num_bytes/sizeof(INTERFACE_INFO);
	for(int i = 0, num = num_bytes/sizeof(INTERFACE_INFO); i < num; ++i) {
		INTERFACE_INFO info = if_info[i];
		u_long flags = info.iiFlags;

		IPv4 result;
		char name[256];
		if(getnameinfo(&info.iiAddress.Address, sizeof(info.iiAddress.Address), name, sizeof(name), NULL, 0, NI_DGRAM) != 0) {
			continue;
		}
		result.name = name;
		auto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {
			char str[INET_ADDRSTRLEN] = {};
			dst_raw = ifa_addr->sin_addr.s_addr;
			inet_ntop(AF_INET, &dst_raw, str, sizeof(str));
			dst_str = str;
		};
		get_address(&info.iiAddress.AddressIn, result.ip_raw, result.ip);
		get_address(&info.iiNetmask.AddressIn, result.netmask_raw, result.netmask);
		if((flags & IFF_BROADCAST) != 0) {
			get_address(&info.iiBroadcastAddress.AddressIn, result.broadcast_raw, result.broadcast);
		}
		else {
			result.broadcast_raw = 0;
			result.broadcast = "";
		}
		ret.push_back(result);
	}
	WSACleanup();
	return ret;
}
bool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const
{
	return (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);
}
#else
std::vector<IPAddress::IPv4> IPAddress::getv4() { return {}; }
bool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const { return false; }
#endif
<|endoftext|>