<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qaccelerationsensor.h>

QTM_BEGIN_NAMESPACE

/*!
    \class QAccelerationReading
    \ingroup sensors

    \preliminary
    \brief The QAccelerationReading class represents one reading from the
           acceleration sensor.

    The acceleration sensor returns acceleration values along 3 axes.
    The scale of the values is milli-Gs. The axes are arranged as follows.

\code
             +z
              |
              |      +y
              |     /
              |----/----
             /| NOKIA  /|
            //|--/--- / |
           // | /   //  /
          //  |/   //  /
         //   '--------------- +x
        //       //  /
       //       //  /
      /---------/  /
     /    O    /  /
    /         /  /
    ----------  /
    |_________!/
\endcode

    A monoblock device sitting at rest, face up on a desk will experience
    the force of gravity as approximately -1000 on the Z axis.
*/

/*!
    \fn QAccelerationReading::QAccelerationReading()
    \internal
*/

/*!
    \fn QAccelerationReading::QAccelerationReading(QTime timestamp, int x, int y, int z)
    \internal
*/

/*!
    \fn QAccelerationReading::QAccelerationReading(const QAccelerationReading &other)
    \internal
*/

/*!
    \fn QAccelerationReading::~QAccelerationReading()
    \internal
*/

/*!
    \fn QAccelerationReading::timestamp() const

    Returns the time when the reading was made.
*/

/*!
    \fn QAccelerationReading::x() const

    Returns the acceleration for the X axis.
*/

/*!
    \fn QAccelerationReading::y() const

    Returns the acceleration for the Y axis.
*/

/*!
    \fn QAccelerationReading::z() const

    Returns the acceleration for the Z axis.
*/

// =====================================================================

/*!
    \class QAccelerationListener
    \ingroup sensors

    \preliminary
    \brief The QAccelerationListener class provides an efficient
           callback facility for asynchronous notifications of
           acceleration changes.

    Since the accelerometer is typically accessed very frequently it may
    not by suitable to use signals and slots. The QAccelerationListener
    interface provides a way for the sensor to notify your class that a
    new acceleration reading is available more efficiently.
*/

/*!
    \fn QAccelerationListener::accelerationChanged(const QAccelerationReading &reading)

    This function is called when a new acceleration \a reading is available.
*/

// =====================================================================

/*!
    \class QAccelerationSensor
    \ingroup sensors

    \preliminary
    \brief The QAccelerationSensor class reports on linear acceleration
           along the X, Y and Z axes.

    The acceleration sensor returns acceleration values along 3 axes.
    The scale of the values is milli-Gs. The axes are arranged as follows.

\code
             +z
              |
              |      +y
              |     /
              |----/----
             /| NOKIA  /|
            //|--/--- / |
           // | /   //  /
          //  |/   //  /
         //   '--------------- +x
        //       //  /
       //       //  /
      /---------/  /
     /    O    /  /
    /         /  /
    ----------  /
    |_________!/
\endcode

    A monoblock device sitting at rest, face up on a desk will experience
    the force of gravity as approximately -1000 on the Z axis.

    \sa QAccelerationReading
*/

/*!
    Construct a sensor instance with specified \a parent.
    If the \a id is passed the sensor will connect to that
    specific sensor, otherwise the default will be used.
*/
QAccelerationSensor::QAccelerationSensor(QObject *parent, const QSensorId &id)
    : QSensor(parent)
{
    connectToBackend(id);
}

/*!
    \variable QAccelerationSensor::typeId
*/
const QString QAccelerationSensor::typeId("qt.Acceleration");

/*!
    \fn QAccelerationSensor::type() const
    \reimp
*/

/*!
    Add a \a listener to the sensor.
    The listener will be invoked every time a new reading is available.

    Note that the sensor does not take ownership of the listener.
    It is the caller's responsibility to ensure the listener remains valid
    until the sensor is destroyed or the listener is removed via
    QAccelerationSensor::removeListener().
*/
void QAccelerationSensor::addListener(QAccelerationListener *listener)
{
    Q_UNUSED(listener)
}

/*!
    Remove a \a listener from the sensor.
    If \a listener is 0, all listeners will be removed.
*/
void QAccelerationSensor::removeListener(QAccelerationListener *listener)
{
    Q_UNUSED(listener)
}

/*!
    Returns the current acceleration reading.
*/
QAccelerationReading QAccelerationSensor::currentReading() const
{
    return QAccelerationReading();
}

/*!
    \fn QAccelerationSensor::accelerationChanged(const QAccelerationReading &reading)

    This signal is emitted when a new acceleration \a reading comes in.
    Note that this is done after the listeners have been called.
    If a listener blocks the reading then this signal will not be emitted.

    Also note that this signal should not be used if you are requesting
    high-frequency updates as signal delivery is quite slow.
*/

void QAccelerationSensor::newReadingAvailable()
{
    /*
    QAccelerationReading reading = currentReading();
    foreach (QAccelerationListener *listener, m_listeners)
        listener->accelerationChanged(reading);
    */
}

#include "moc_qaccelerationsensor.cpp"
QTM_END_NAMESPACE

<commit_msg>fix out of sync documentation<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qaccelerationsensor.h>

QTM_BEGIN_NAMESPACE

/*!
    \class QAccelerationReading
    \ingroup sensors

    \preliminary
    \brief The QAccelerationReading class represents one reading from the
           acceleration sensor.

    The acceleration sensor returns acceleration values along 3 axes.
    The scale of the values is milli-Gs. The axes are arranged as follows.

\code
             +z
              |
              |      +y
              |     /
              |----/----
             /| NOKIA  /|
            //|--/--- / |
           // | /   //  /
          //  |/   //  /
         //   '--------------- +x
        //       //  /
       //       //  /
      /---------/  /
     /    O    /  /
    /         /  /
    ----------  /
    |_________!/
\endcode

    A monoblock device sitting at rest, face up on a desk will experience
    the force of gravity as approximately -1000 on the Z axis.
*/

/*!
    \fn QAccelerationReading::QAccelerationReading()
    \internal
*/

/*!
    \fn QAccelerationReading::QAccelerationReading(QTime timestamp, int x, int y, int z)
    \internal
*/

/*!
    \fn QAccelerationReading::QAccelerationReading(const QAccelerationReading &other)
    \internal
*/

/*!
    \fn QAccelerationReading::~QAccelerationReading()
    \internal
*/

/*!
    \fn QAccelerationReading::timestamp() const

    Returns the time when the reading was made.
*/

/*!
    \fn QAccelerationReading::x() const

    Returns the acceleration for the X axis.
*/

/*!
    \fn QAccelerationReading::y() const

    Returns the acceleration for the Y axis.
*/

/*!
    \fn QAccelerationReading::z() const

    Returns the acceleration for the Z axis.
*/

// =====================================================================

/*!
    \class QAccelerationListener
    \ingroup sensors

    \preliminary
    \brief The QAccelerationListener class provides an efficient
           callback facility for asynchronous notifications of
           acceleration changes.

    Since the accelerometer is typically accessed very frequently it may
    not by suitable to use signals and slots. The QAccelerationListener
    interface provides a way for the sensor to notify your class that a
    new acceleration reading is available more efficiently.
*/

/*!
    \fn QAccelerationListener::accelerationChanged(const QAccelerationReading &reading)

    This function is called when a new acceleration \a reading is available.
*/

// =====================================================================

/*!
    \class QAccelerationSensor
    \ingroup sensors

    \preliminary
    \brief The QAccelerationSensor class reports on linear acceleration
           along the X, Y and Z axes.

    The acceleration sensor returns acceleration values along 3 axes.
    The scale of the values is milli-Gs. The axes are arranged as follows.

\code
             +z
              |
              |      +y
              |     /
              |----/----
             /| NOKIA  /|
            //|--/--- / |
           // | /   //  /
          //  |/   //  /
         //   '--------------- +x
        //       //  /
       //       //  /
      /---------/  /
     /    O    /  /
    /         /  /
    ----------  /
    |_________!/
\endcode

    A monoblock device sitting at rest, face up on a desk will experience
    the force of gravity as approximately -1000 on the Z axis.

    \sa QAccelerationReading
*/

/*!
    Construct a sensor instance with specified \a parent.
    If the \a id is passed the sensor will connect to that
    specific sensor, otherwise the default will be used.
*/
QAccelerationSensor::QAccelerationSensor(QObject *parent, const QSensorId &id)
    : QSensor(parent)
{
    connectToBackend(id);
}

/*!
    \variable QAccelerationSensor::typeId
*/
const QString QAccelerationSensor::typeId("qt.Acceleration");

/*!
    \fn QAccelerationSensor::type() const
    \reimp
*/

/*!
    Add a \a listener to the sensor.
    The listener will be invoked every time a new reading is available.

    Note that the sensor does not take ownership of the listener.
    It is the caller's responsibility to ensure the listener remains valid
    until the sensor is destroyed or the listener is removed via
    QAccelerationSensor::removeListener().
*/
void QAccelerationSensor::addListener(QAccelerationListener *listener)
{
    Q_UNUSED(listener)
}

/*!
    Remove a \a listener from the sensor.
    If \a listener is 0, all listeners will be removed.
*/
void QAccelerationSensor::removeListener(QAccelerationListener *listener)
{
    Q_UNUSED(listener)
}

/*!
    Returns the current acceleration reading.
*/
QAccelerationReading QAccelerationSensor::currentReading() const
{
    return QAccelerationReading();
}

/*!
    \fn QAccelerationSensor::accelerationChanged(const QAccelerationReading &reading)

    This signal is emitted when a new acceleration \a reading comes in.

    Note that this signal should not be used if you are requesting
    high-frequency updates as signal delivery is quite slow.
*/

void QAccelerationSensor::newReadingAvailable()
{
    /*
    QAccelerationReading reading = currentReading();
    foreach (QAccelerationListener *listener, m_listeners)
        listener->accelerationChanged(reading);
    */
}

#include "moc_qaccelerationsensor.cpp"
QTM_END_NAMESPACE

<|endoftext|>


<commit_before>// ------------------------------------------------------------------------
// eca-audio-time.cpp: Generic class for representing time in audio
//                     environment.
// Copyright (C) 2000 Kai Vehmanen (kaiv@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#include <cstdio>
#include <cmath>

#include <kvu_numtostr.h>

#include "eca-audio-time.h"

ECA_AUDIO_TIME::ECA_AUDIO_TIME(SAMPLE_SPECS::sample_pos_t samples, SAMPLE_SPECS::sample_rate_t sample_rate) {
  set_samples_per_second(sample_rate);
  set_samples(samples);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(double time_in_seconds) {
  set_seconds(time_in_seconds);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(format_type type, const std::string& time) {
  set(type, time);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(void) : samples_rep(0), sample_rate_rep(44100) { }

void ECA_AUDIO_TIME::set(format_type type, const std::string& time) {
  switch(type)
    {
    case format_hour_min_sec: { }
    case format_min_sec: { }
    case format_seconds: { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(sample_rate_rep * atof(time.c_str())); }
    case format_samples: { samples_rep = atol(time.c_str()); }

    default: { }
    }
}

void ECA_AUDIO_TIME::set_seconds(double seconds) {
  samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(seconds * sample_rate_rep);
}

void ECA_AUDIO_TIME::set_samples(SAMPLE_SPECS::sample_pos_t samples) { samples_rep = samples; }
void ECA_AUDIO_TIME::set_samples_per_second(SAMPLE_SPECS::sample_rate_t srate)  { sample_rate_rep = srate; }

std::string ECA_AUDIO_TIME::to_string(format_type type) const {
  switch(type)
    {
    case format_hour_min_sec:
      {
	return("");
      }
    case format_min_sec:
      {
	return("");
      }
    case format_seconds: { return(kvu_numtostr(seconds(), 3)); }
    case format_samples: { return(kvu_numtostr(samples_rep)); }

    default: { }
    }
  return("");
}

double ECA_AUDIO_TIME::seconds(void) const {
  return(static_cast<double>(samples_rep) / sample_rate_rep);
}

SAMPLE_SPECS::sample_rate_t ECA_AUDIO_TIME::samples_per_second(void) const  { return(sample_rate_rep); }
SAMPLE_SPECS::sample_pos_t ECA_AUDIO_TIME::samples(void) const { return(samples_rep); }
<commit_msg>Add fixmes.<commit_after>// ------------------------------------------------------------------------
// eca-audio-time.cpp: Generic class for representing time in audio
//                     environment.
// Copyright (C) 2000 Kai Vehmanen (kaiv@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#include <cstdio>
#include <cmath>

#include <kvu_numtostr.h>

#include "eca-audio-time.h"

ECA_AUDIO_TIME::ECA_AUDIO_TIME(SAMPLE_SPECS::sample_pos_t samples,
			       SAMPLE_SPECS::sample_rate_t sample_rate)
{
  set_samples_per_second(sample_rate);
  set_samples(samples);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(double time_in_seconds)
{
  set_seconds(time_in_seconds);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(format_type type,
			       const std::string& time)
{
  set(type, time);
}

ECA_AUDIO_TIME::ECA_AUDIO_TIME(void) : samples_rep(0),
				       sample_rate_rep(44100)
{
}

void ECA_AUDIO_TIME::set(format_type type, const std::string& time)
{
  /* FIXME: not implemented! */

  switch(type)
    {
    case format_hour_min_sec: { }
    case format_min_sec: { }
    case format_seconds: { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(sample_rate_rep * atof(time.c_str())); }
    case format_samples: { samples_rep = atol(time.c_str()); }

    default: { }
    }
}

void ECA_AUDIO_TIME::set_seconds(double seconds)
{
  samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(seconds * sample_rate_rep);
}

void ECA_AUDIO_TIME::set_samples(SAMPLE_SPECS::sample_pos_t samples) { samples_rep = samples; }
void ECA_AUDIO_TIME::set_samples_per_second(SAMPLE_SPECS::sample_rate_t srate)  { sample_rate_rep = srate; }

std::string ECA_AUDIO_TIME::to_string(format_type type) const
{
  /* FIXME: not implemented */

  switch(type)
    {
    case format_hour_min_sec:
      {
	return("");
      }
    case format_min_sec:
      {
	return("");
      }
    case format_seconds: { return(kvu_numtostr(seconds(), 3)); }
    case format_samples: { return(kvu_numtostr(samples_rep)); }

    default: { }
    }
  return("");
}

double ECA_AUDIO_TIME::seconds(void) const
{
  return(static_cast<double>(samples_rep) / sample_rate_rep);
}

SAMPLE_SPECS::sample_rate_t ECA_AUDIO_TIME::samples_per_second(void) const  { return(sample_rate_rep); }
SAMPLE_SPECS::sample_pos_t ECA_AUDIO_TIME::samples(void) const { return(samples_rep); }
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file qp_spline_path_optimizer.cc
 **/
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"

#include "modules/common/util/file.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_generator.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;

QpSplinePathOptimizer::QpSplinePathOptimizer()
    : PathOptimizer("QpSplinePathOptimizer") {}

bool QpSplinePathOptimizer::Init(const PlanningConfig& config) {
  qp_spline_path_config_ = config.em_planner_config().qp_spline_path_config();
  std::vector<double> init_knots;
  spline_generator_.reset(new Spline1dGenerator(init_knots, 5));
  is_init_ = true;
  return true;
}

Status QpSplinePathOptimizer::Process(const SpeedData& speed_data,
                                      const ReferenceLine& reference_line,
                                      const common::TrajectoryPoint& init_point,
                                      PathData* const path_data) {
  if (!is_init_) {
    AERROR << "Please call Init() before Process.";
    return Status(ErrorCode::PLANNING_ERROR, "Not init.");
  }
  QpSplinePathGenerator path_generator(spline_generator_.get(), reference_line,
                                       qp_spline_path_config_);
  path_generator.SetDebugLogger(reference_line_info_->mutable_debug());

  if (!path_generator.Generate(
          reference_line_info_->path_decision()->path_obstacles().Items(),
          speed_data, init_point, path_data)) {
    const std::string msg = "failed to generate spline path!";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  return Status::OK();
}

}  // namespace planning
}  // namespace apollo
<commit_msg>planning: fix QP path order const with config value.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file qp_spline_path_optimizer.cc
 **/
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"

#include "modules/common/util/file.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_generator.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;

QpSplinePathOptimizer::QpSplinePathOptimizer()
    : PathOptimizer("QpSplinePathOptimizer") {}

bool QpSplinePathOptimizer::Init(const PlanningConfig& config) {
  qp_spline_path_config_ = config.em_planner_config().qp_spline_path_config();
  std::vector<double> init_knots;
  spline_generator_.reset(new Spline1dGenerator(init_knots,
      qp_spline_path_config_.spline_order()));
  is_init_ = true;
  return true;
}

Status QpSplinePathOptimizer::Process(const SpeedData& speed_data,
                                      const ReferenceLine& reference_line,
                                      const common::TrajectoryPoint& init_point,
                                      PathData* const path_data) {
  if (!is_init_) {
    AERROR << "Please call Init() before Process.";
    return Status(ErrorCode::PLANNING_ERROR, "Not init.");
  }
  QpSplinePathGenerator path_generator(spline_generator_.get(), reference_line,
                                       qp_spline_path_config_);
  path_generator.SetDebugLogger(reference_line_info_->mutable_debug());

  if (!path_generator.Generate(
          reference_line_info_->path_decision()->path_obstacles().Items(),
          speed_data, init_point, path_data)) {
    const std::string msg = "failed to generate spline path!";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  return Status::OK();
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>#include "HeatExchangeCoefficientPartitioning.h"

template<>
InputParameters validParams<HeatExchangeCoefficientPartitioning>()
{
  InputParameters params = validParams<GeneralUserObject>();
  params.addParam<Real>("k", 5, "Steepness of the exponential function");
  params.addParam<Real>("lower", 0.001, "Lower cut-off limit");
  params.addParam<Real>("upper", 0.999, "Upper cut-off limit");

  return params;
}

HeatExchangeCoefficientPartitioning::HeatExchangeCoefficientPartitioning(const std::string & name, InputParameters parameters) :
    GeneralUserObject(name, parameters),
    _k(getParam<Real>("k")),
    _lower(getParam<Real>("lower")),
    _upper(getParam<Real>("upper"))
{
}

HeatExchangeCoefficientPartitioning::~HeatExchangeCoefficientPartitioning()
{
}

Real
HeatExchangeCoefficientPartitioning::getPartition(Real alpha_liquid, Real dalpha_liquid_dt) const
{
  Real c = 1;

  if ((alpha_liquid < _lower))
  {
    if (dalpha_liquid_dt < 0)
      c = 1 - (1 - std::exp(-_k * (0.001 - alpha_liquid) / 0.001));
    else
      c = 1 - std::exp(-_k * alpha_liquid / 0.001);
  }
  else if ((alpha_liquid > _upper))
  {
    if (dalpha_liquid_dt > 0)
      c = 1 - (1 - std::exp(-_k * (alpha_liquid - 0.999) / 0.001));
    else
      c = 1 - std::exp(-_k * (1 - alpha_liquid) / 0.001);
  }
  else
    c = 1.;

  return c;
}
<commit_msg>Fixing the heat exchange coefficient partitioning user object<commit_after>#include "HeatExchangeCoefficientPartitioning.h"

template<>
InputParameters validParams<HeatExchangeCoefficientPartitioning>()
{
  InputParameters params = validParams<GeneralUserObject>();
  params.addParam<Real>("k", 5, "Steepness of the exponential function");
  params.addParam<Real>("lower", 0.001, "Lower cut-off limit");
  params.addParam<Real>("upper", 0.999, "Upper cut-off limit");

  return params;
}

HeatExchangeCoefficientPartitioning::HeatExchangeCoefficientPartitioning(const std::string & name, InputParameters parameters) :
    GeneralUserObject(name, parameters),
    _k(getParam<Real>("k")),
    _lower(getParam<Real>("lower")),
    _upper(getParam<Real>("upper"))
{
}

HeatExchangeCoefficientPartitioning::~HeatExchangeCoefficientPartitioning()
{
}

Real
HeatExchangeCoefficientPartitioning::getPartition(Real alpha_liquid, Real dalpha_liquid_dt) const
{
  Real c = 1;

  if ((alpha_liquid < _lower))
  {
    if (dalpha_liquid_dt < 0)
      c = 1 - (1 - std::exp(-_k * (_lower - alpha_liquid) / _lower));
    else
      c = 1 - std::exp(-_k * alpha_liquid / _lower);
  }
  else if ((alpha_liquid > _upper))
  {
    if (dalpha_liquid_dt > 0)
      c = 1 - (1 - std::exp(-_k * (alpha_liquid - _upper) / _lower));
    else
      c = 1 - std::exp(-_k * (1 - alpha_liquid) / _lower);
  }
  else
    c = 1.;

  return c;
}
<|endoftext|>


<commit_before>/*
  This file is part of libkdepim.

  Copyright (c) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

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

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

#include <qdatetime.h>
#include <qpopupmenu.h>

#include <klocale.h>

#include "kdatepickerpopup.h"

KDatePickerPopup::KDatePickerPopup( int items, const QDate &date, QWidget *parent,
                                    const char *name )
  : QPopupMenu( parent, name )
{
  mItems = items;

  mDatePicker = new KDatePicker();
  mDatePicker->setCloseButton( false );

  connect( mDatePicker, SIGNAL( dateEntered( QDate ) ),
           SLOT( slotDateChanged( QDate ) ) );
  connect( mDatePicker, SIGNAL( dateSelected( QDate ) ),
           SLOT( slotDateChanged( QDate ) ) );

  mDatePicker->setDate( date );

  buildMenu();
}

void KDatePickerPopup::buildMenu()
{
  if ( isVisible() ) return;
  clear();

  if ( mItems & DatePicker ) {
    insertItem( mDatePicker );

    if ( ( mItems & NoDate ) || ( mItems & Words ) )
      insertSeparator();
  }

  if ( mItems & Words ) {
    insertItem( i18n("&Today"), this, SLOT( slotToday() ) );
    insertItem( i18n("To&morrow"), this, SLOT( slotTomorrow() ) );
    insertItem( i18n("&Friday"), this, SLOT( slotFriday() ) );
    insertItem( i18n("&Sunday"), this, SLOT( slotSunday() ) );
    insertItem( i18n("Next &Week"), this, SLOT( slotNextWeek() ) );
    insertItem( i18n("Next M&onth"), this, SLOT( slotNextMonth() ) );

    if ( mItems & NoDate )
      insertSeparator();
  }

  if ( mItems & NoDate )
    insertItem( i18n("No Date"), this, SLOT( slotNoDate() ) );
}

KDatePickerPopup::~KDatePickerPopup()
{
  delete mDatePicker;
}

KDatePicker *KDatePickerPopup::datePicker() const
{
  return mDatePicker;
}

#if 0
void KDatePickerPopup::setItems( int items )
{
  mItems = items;
  buildMenu();
}
#endif

void KDatePickerPopup::slotDateChanged( QDate date )
{
  emit dateChanged( date );
  hide();
}

void KDatePickerPopup::slotToday()
{
  emit dateChanged( QDate::currentDate() );
}

void KDatePickerPopup::slotTomorrow()
{
  emit dateChanged( QDate::currentDate().addDays( 1 ) );
}

void KDatePickerPopup::slotFriday()
{
  QDate date = QDate::currentDate();
  int day = date.dayOfWeek();
  if ( day < 6 )
    date = date.addDays( 5 - day );
  else
    date = date.addDays( 5 - day + 7 );

  emit dateChanged( date );
}

void KDatePickerPopup::slotSunday()
{
  QDate date = QDate::currentDate();
  emit dateChanged( date.addDays( 7 - date.dayOfWeek() ) );
}

void KDatePickerPopup::slotNoDate()
{
  emit dateChanged( QDate() );
}

void KDatePickerPopup::slotNextWeek()
{
  emit dateChanged( QDate::currentDate().addDays( 7 ) );
}

void KDatePickerPopup::slotNextMonth()
{
  emit dateChanged( QDate::currentDate().addMonths( 1 ) );
}

#include "kdatepickerpopup.moc"
<commit_msg>setDate() implemented.<commit_after>/*
  This file is part of libkdepim.

  Copyright (c) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

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

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

#include <qdatetime.h>
#include <qpopupmenu.h>

#include <klocale.h>

#include "kdatepickerpopup.h"

KDatePickerPopup::KDatePickerPopup( int items, const QDate &date, QWidget *parent,
                                    const char *name )
  : QPopupMenu( parent, name )
{
  mItems = items;

  mDatePicker = new KDatePicker();
  mDatePicker->setCloseButton( false );

  connect( mDatePicker, SIGNAL( dateEntered( QDate ) ),
           SLOT( slotDateChanged( QDate ) ) );
  connect( mDatePicker, SIGNAL( dateSelected( QDate ) ),
           SLOT( slotDateChanged( QDate ) ) );

  mDatePicker->setDate( date );

  buildMenu();
}

void KDatePickerPopup::buildMenu()
{
  if ( isVisible() ) return;
  clear();

  if ( mItems & DatePicker ) {
    insertItem( mDatePicker );

    if ( ( mItems & NoDate ) || ( mItems & Words ) )
      insertSeparator();
  }

  if ( mItems & Words ) {
    insertItem( i18n("&Today"), this, SLOT( slotToday() ) );
    insertItem( i18n("To&morrow"), this, SLOT( slotTomorrow() ) );
    insertItem( i18n("&Friday"), this, SLOT( slotFriday() ) );
    insertItem( i18n("&Sunday"), this, SLOT( slotSunday() ) );
    insertItem( i18n("Next &Week"), this, SLOT( slotNextWeek() ) );
    insertItem( i18n("Next M&onth"), this, SLOT( slotNextMonth() ) );

    if ( mItems & NoDate )
      insertSeparator();
  }

  if ( mItems & NoDate )
    insertItem( i18n("No Date"), this, SLOT( slotNoDate() ) );
}

KDatePickerPopup::~KDatePickerPopup()
{
  delete mDatePicker;
}

KDatePicker *KDatePickerPopup::datePicker() const
{
  return mDatePicker;
}

void KDatePickerPopup::setDate( const QDate &date )
{
  mDatePicker->setDate( date );
}

#if 0
void KDatePickerPopup::setItems( int items )
{
  mItems = items;
  buildMenu();
}
#endif

void KDatePickerPopup::slotDateChanged( QDate date )
{
  emit dateChanged( date );
  hide();
}

void KDatePickerPopup::slotToday()
{
  emit dateChanged( QDate::currentDate() );
}

void KDatePickerPopup::slotTomorrow()
{
  emit dateChanged( QDate::currentDate().addDays( 1 ) );
}

void KDatePickerPopup::slotFriday()
{
  QDate date = QDate::currentDate();
  int day = date.dayOfWeek();
  if ( day < 6 )
    date = date.addDays( 5 - day );
  else
    date = date.addDays( 5 - day + 7 );

  emit dateChanged( date );
}

void KDatePickerPopup::slotSunday()
{
  QDate date = QDate::currentDate();
  emit dateChanged( date.addDays( 7 - date.dayOfWeek() ) );
}

void KDatePickerPopup::slotNoDate()
{
  emit dateChanged( QDate() );
}

void KDatePickerPopup::slotNextWeek()
{
  emit dateChanged( QDate::currentDate().addDays( 7 ) );
}

void KDatePickerPopup::slotNextMonth()
{
  emit dateChanged( QDate::currentDate().addMonths( 1 ) );
}

#include "kdatepickerpopup.moc"
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 midnightBITS
 *
 * 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 "pch.h"
#include <http_connection.hpp>
#include <types.hpp>
#include <iostream>

namespace net
{
	namespace http
	{
		void connection_manager::start(connection_ptr c)
		{
			m_connections.insert(c);
			c->start();
		}

		void connection_manager::stop(connection_ptr c)
		{
			m_connections.erase(c);
			c->stop();
		}

		void connection_manager::stop_all()
		{
			for (auto c : m_connections)
				c->stop();
			m_connections.clear();
		}

		connection::connection(boost::asio::ip::tcp::socket && socket, connection_manager& manager, request_handler& handler)
			: m_socket(std::move(socket))
			, m_manager(manager)
			, m_handler(handler)
			, m_pos(0)
		{
		}

		void connection::read_some_more()
		{
			auto self(shared_from_this());
			m_socket.async_read_some(boost::asio::buffer(m_buffer),
				[this, self](boost::system::error_code ec, std::size_t bytes_transferred)
			{
				if (!ec)
				{
					const char* data = m_buffer.data();
					auto end = data + bytes_transferred;
					auto ret = m_parser.parse(data, end);

					if (ret == parser::finished)
					{
						auto header = m_parser.header();
						std::cout << header;
						m_handler.handle(header, m_response);
						send_reply();
					}
					else if (ret == parser::error)
					{
						m_handler.make_404(m_response);
						send_reply();
					}
					else
						read_some_more();
				}
				else if (ec != boost::asio::error::operation_aborted)
				{
					m_manager.stop(shared_from_this());
				}
			});
		}

		void connection::continue_sending(connection_ptr self, response_buffer buffer, boost::system::error_code ec, std::size_t)
		{
			if (!ec)
			{
				if (buffer.advance(self->m_response_chunk))
				{
					boost::asio::async_write(
						self->m_socket, boost::asio::buffer(self->m_response_chunk),
						[self, buffer](boost::system::error_code ec, std::size_t size)
					{
						continue_sending(self, buffer, ec, size);
					});
					return;
				}
				else
				{
					// Initiate graceful connection closure.
					boost::system::error_code ignored_ec;
					self->m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
				}
			}

			if (ec != boost::asio::error::operation_aborted)
			{
				self->m_manager.stop(self->shared_from_this());
			}
		}

		void connection::send_reply()
		{
			auto self(shared_from_this());
			continue_sending(self, m_response.get_data(), boost::system::error_code(), 0);
		}
	}
}
<commit_msg>Shorter debug output<commit_after>/*
 * Copyright (C) 2013 midnightBITS
 *
 * 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 "pch.h"
#include <http_connection.hpp>
#include <types.hpp>
#include <iostream>

namespace net
{
	namespace http
	{
		void connection_manager::start(connection_ptr c)
		{
			m_connections.insert(c);
			c->start();
		}

		void connection_manager::stop(connection_ptr c)
		{
			m_connections.erase(c);
			c->stop();
		}

		void connection_manager::stop_all()
		{
			for (auto c : m_connections)
				c->stop();
			m_connections.clear();
		}

		connection::connection(boost::asio::ip::tcp::socket && socket, connection_manager& manager, request_handler& handler)
			: m_socket(std::move(socket))
			, m_manager(manager)
			, m_handler(handler)
			, m_pos(0)
		{
		}

		void connection::read_some_more()
		{
			auto self(shared_from_this());
			m_socket.async_read_some(boost::asio::buffer(m_buffer),
				[this, self](boost::system::error_code ec, std::size_t bytes_transferred)
			{
				if (!ec)
				{
					const char* data = m_buffer.data();
					auto end = data + bytes_transferred;
					auto ret = m_parser.parse(data, end);

					if (ret == parser::finished)
					{
						auto header = m_parser.header();
						auto ua = header.find("user-agent");
						std::ostringstream o;
						o << (http_request_line&) header;
						if (ua != header.end())
						{
							o << "   [ " << ua->value();
							auto pui = header.find("x-av-physical-unit-info");
							auto ci = header.find("x-av-client-info");
							if (pui != header.end() || ci != header.end())
							{
								o << " | ";
								if (pui != header.end())
								{
									o << pui->value();
									if (ci != header.end())
										o << " | ";
								}
								if (ci != header.end())
								{
									o << ci->value();
								}
							}
							o << " ]\n";
						}
						std::cout << o.str();
						m_handler.handle(header, m_response);
						send_reply();
					}
					else if (ret == parser::error)
					{
						m_handler.make_404(m_response);
						send_reply();
					}
					else
						read_some_more();
				}
				else if (ec != boost::asio::error::operation_aborted)
				{
					m_manager.stop(shared_from_this());
				}
			});
		}

		void connection::continue_sending(connection_ptr self, response_buffer buffer, boost::system::error_code ec, std::size_t)
		{
			if (!ec)
			{
				if (buffer.advance(self->m_response_chunk))
				{
					boost::asio::async_write(
						self->m_socket, boost::asio::buffer(self->m_response_chunk),
						[self, buffer](boost::system::error_code ec, std::size_t size)
					{
						continue_sending(self, buffer, ec, size);
					});
					return;
				}
				else
				{
					// Initiate graceful connection closure.
					boost::system::error_code ignored_ec;
					self->m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
				}
			}

			if (ec != boost::asio::error::operation_aborted)
			{
				self->m_manager.stop(self->shared_from_this());
			}
		}

		void connection::send_reply()
		{
			auto self(shared_from_this());
			continue_sending(self, m_response.get_data(), boost::system::error_code(), 0);
		}
	}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file nvdimm_utils.H
/// @brief Subroutines to support nvdimm backup/restore process
///
// *HWP HWP Owner: Tsung Yeung <tyeung@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <generic/memory/lib/utils/find.H>

namespace mss
{

namespace nvdimm
{

///
/// @brief Helper for self_refresh_exit().
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
/// @note Uses memdiag to read the port to force CKE back to high.
/// Stolen from mss_lab_memdiags.C
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_exit_helper( const fapi2::Target<T>& i_target );

///
/// @brief Disable refresh and put target into self-refresh
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_entry( const fapi2::Target<T>& i_target );

///
/// @brief Take the target out of self-refresh and restart refresh
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_exit( const fapi2::Target<T>& i_target );

///
/// @brief Latch write vref at per-dram basis
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///

template< fapi2::TargetType T >
fapi2::ReturnCode pda_vref_latch( const fapi2::Target<T>& i_target );

///
/// @brief Full post-restore transition for NVDIMM
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///

template< fapi2::TargetType T >
fapi2::ReturnCode post_restore_transition( const fapi2::Target<T>& i_target );

}//ns nvdimm

}//ns mss
<commit_msg>P9: Disable Maint Address Mode After Self-Refresh Exit on NVDIMM<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file nvdimm_utils.H
/// @brief Subroutines to support nvdimm backup/restore process
///
// *HWP HWP Owner: Tsung Yeung <tyeung@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <generic/memory/lib/utils/find.H>

namespace mss
{

namespace nvdimm
{

///
/// @brief Disable maintenance address mode
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///
template< fapi2::TargetType T >
fapi2::ReturnCode maint_addr_mode_off( const fapi2::Target<T>& i_target );

///
/// @brief Helper for self_refresh_exit().
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
/// @note Uses memdiag to read the port to force CKE back to high.
/// Stolen from mss_lab_memdiags.C
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_exit_helper( const fapi2::Target<T>& i_target );

///
/// @brief Disable refresh and put target into self-refresh
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_entry( const fapi2::Target<T>& i_target );

///
/// @brief Take the target out of self-refresh and restart refresh
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///
template< fapi2::TargetType T >
fapi2::ReturnCode self_refresh_exit( const fapi2::Target<T>& i_target );

///
/// @brief Latch write vref at per-dram basis
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///

template< fapi2::TargetType T >
fapi2::ReturnCode pda_vref_latch( const fapi2::Target<T>& i_target );

///
/// @brief Full post-restore transition for NVDIMM
/// @tparam T the target type associated with this subroutine
/// @param[in] i_target the target associated with this subroutine
/// @return FAPI2_RC_SUCCESS iff setup was successful
///

template< fapi2::TargetType T >
fapi2::ReturnCode post_restore_transition( const fapi2::Target<T>& i_target );

}//ns nvdimm

}//ns mss
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer                    //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

// includes  -------------------------------------------------------------------
#include <swift2d/graphics/HeatEffect.hpp>

#include <swift2d/components/DrawableComponent.hpp>
#include <swift2d/graphics/RendererPool.hpp>

namespace swift {

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

HeatEffect::HeatEffect(RenderContext const& ctx) {
  if (ctx.heat_effect) {

    auto create_texture = [&](
      oglplus::Texture& tex, int width, int height,
      oglplus::enums::PixelDataInternalFormat i_format,
      oglplus::enums::PixelDataFormat         p_format) {

      ctx.gl.Bound(oglplus::Texture::Target::_2D, tex)
        .Image2D(0, i_format, width, height,
          0, p_format, oglplus::PixelDataType::Float, nullptr)
        .MaxLevel(0)
        .MinFilter(oglplus::TextureMinFilter::Linear)
        .MagFilter(oglplus::TextureMagFilter::Linear)
        .WrapS(oglplus::TextureWrap::MirroredRepeat)
        .WrapT(oglplus::TextureWrap::MirroredRepeat);
    };

    create_texture(
      heat_buffer_, ctx.g_buffer_size.x()/8, ctx.g_buffer_size.y()/8,
      oglplus::PixelDataInternalFormat::RG,
      oglplus::PixelDataFormat::RG
    );

    heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw);
    oglplus::Framebuffer::AttachColorTexture(
      oglplus::Framebuffer::Target::Draw, 0, heat_buffer_, 0
    );

    GLfloat clear[2] = {0.5f, 0.5f};
    ctx.gl.ClearColorBuffer(0, clear);
  }
}

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

void HeatEffect::process(ConstSerializedScenePtr const& scene,
                         RenderContext const& ctx) {

  if (!scene->renderers().heat_particle_systems.empty()) {

    ctx.gl.BlendFunc(
      oglplus::BlendFunction::SrcAlpha,
      oglplus::BlendFunction::OneMinusSrcAlpha
    );

    ctx.gl.Viewport(ctx.g_buffer_size.x()/8, ctx.g_buffer_size.y()/8);

    heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw);
    ctx.gl.DrawBuffer(oglplus::FramebufferColorAttachment::_0);

    GLfloat clear[2] = {0.5f, 0.5f};
    ctx.gl.ClearColorBuffer(0, clear);

    scene->renderers().process_heat(ctx);
  }
}

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

int HeatEffect::bind_buffers(int start, RenderContext const& ctx) {
  oglplus::Texture::Active(start);
  ctx.gl.Bind(ose::_2D(), heat_buffer_);
  return start + 1;
}

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

}
<commit_msg>increased heatbuffer resolution<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer                    //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

// includes  -------------------------------------------------------------------
#include <swift2d/graphics/HeatEffect.hpp>

#include <swift2d/components/DrawableComponent.hpp>
#include <swift2d/graphics/RendererPool.hpp>

namespace swift {

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

HeatEffect::HeatEffect(RenderContext const& ctx) {
  if (ctx.heat_effect) {

    auto create_texture = [&](
      oglplus::Texture& tex, int width, int height,
      oglplus::enums::PixelDataInternalFormat i_format,
      oglplus::enums::PixelDataFormat         p_format) {

      ctx.gl.Bound(oglplus::Texture::Target::_2D, tex)
        .Image2D(0, i_format, width, height,
          0, p_format, oglplus::PixelDataType::Float, nullptr)
        .MaxLevel(0)
        .MinFilter(oglplus::TextureMinFilter::Linear)
        .MagFilter(oglplus::TextureMagFilter::Linear)
        .WrapS(oglplus::TextureWrap::MirroredRepeat)
        .WrapT(oglplus::TextureWrap::MirroredRepeat);
    };

    create_texture(
      heat_buffer_, ctx.g_buffer_size.x()/4, ctx.g_buffer_size.y()/4,
      oglplus::PixelDataInternalFormat::RG,
      oglplus::PixelDataFormat::RG
    );

    heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw);
    oglplus::Framebuffer::AttachColorTexture(
      oglplus::Framebuffer::Target::Draw, 0, heat_buffer_, 0
    );

    GLfloat clear[2] = {0.5f, 0.5f};
    ctx.gl.ClearColorBuffer(0, clear);
  }
}

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

void HeatEffect::process(ConstSerializedScenePtr const& scene,
                         RenderContext const& ctx) {

  if (!scene->renderers().heat_particle_systems.empty()) {

    ctx.gl.BlendFunc(
      oglplus::BlendFunction::SrcAlpha,
      oglplus::BlendFunction::OneMinusSrcAlpha
    );

    ctx.gl.Viewport(ctx.g_buffer_size.x()/4, ctx.g_buffer_size.y()/4);

    heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw);
    ctx.gl.DrawBuffer(oglplus::FramebufferColorAttachment::_0);

    GLfloat clear[2] = {0.5f, 0.5f};
    ctx.gl.ClearColorBuffer(0, clear);

    scene->renderers().process_heat(ctx);
  }
}

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

int HeatEffect::bind_buffers(int start, RenderContext const& ctx) {
  oglplus::Texture::Active(start);
  ctx.gl.Bind(ose::_2D(), heat_buffer_);
  return start + 1;
}

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

}
<|endoftext|>


<commit_before>#include <bts/chain/operations.hpp>

namespace bts { namespace chain {

/**
 *  Valid symbols have between 3 and 17 upper case characters
 *  with at most a single "." that is not the first or last character.
 */
bool is_valid_symbol( const string& symbol )
{
   if( symbol.size() > 17 ) return false;
   if( symbol.size() < 3  ) return false;
   int dot_count = 0;
   for( auto c : symbol )
   {
      if( c == '.' ) ++dot_count;
      else if( c < 'A' || c > 'Z' ) return false;
   }
   if( symbol[0] == '.' || symbol[symbol.size()-1] == '.' )
      return false;
   return dot_count <= 1;
}

/**
 *  Valid names are all lower case, start with [a-z] and may
 *  have "." or "-" in the name along with a single '/'.  The
 *  next character after a "/", "." or "-" cannot be [0-9] or
 *  another '.', '-'.
 *
 */
bool is_valid_name( const string& s )
{
   if( s.size() == 0  ) return true;
   if( s.size() <  3  ) return false;
   if( s.size() >= 64 ) return false;

   int num_slash = 0;
   char prev = ' ';
   for( auto c : s )
   {
      if( c >= 'a' && c <= 'z' ){}
      else if( c >= '0' && c <= '9' )
      {
         if( prev == ' ' || prev == '.' || prev == '-' || prev == '/' ) return false;
      }
      else switch( c )
      {
            case '/':
               if( ++num_slash > 1 ) return false;
            case '.':
            case '-':
               if( prev == ' ' || prev == '/' || prev == '.' || prev == '-' ) return false;
              break;
            default:
              return false;
      }
      prev = c;
   }
   switch( s.back() )
   {
      case '/': case '-': case '.':
         return false;
      default:
         return true;
   }
}
bool is_premium_name( const string& n )
{
   return false;
}
bool is_cheap_name( const string& n )
{
   for( auto c : n )
   {
      if( c >= '0' && c <= '9' ) return true;
      if( c == '.' || c == '-' || c == '/' ) return true;
   }
   return false;
}

share_type account_create_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at(account_create_fee_type);

   if( name.size() )
   {
      uint32_t s = name.size();
      if( is_premium_name( name ) )    s = 2;
      else if( is_cheap_name( name ) ) s = 63;
      while( s <= 8 ) {  bts_fee_required *= 10; ++s; }

   }
   return bts_fee_required;
}
share_type account_update_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   return schedule.at(account_create_fee_type);
}
void account_update_operation::validate()const
{
   FC_ASSERT( fee.amount > 0 );
   FC_ASSERT( owner || active || voting_key || memo_key || vote );

   if( vote && vote->size() > 1 )
   {
      for( int i = 1; i < vote->size(); ++i )
         FC_ASSERT( vote->at(i-1) < vote->at(i) );
   }
}

share_type asset_create_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at(asset_create_fee_type);

   uint32_t s = symbol.size();
   while( s <= 6 ) {  bts_fee_required *= 30; ++s; }

   return bts_fee_required;
}

share_type transfer_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at( transfer_fee_type );
   bts_fee_required += share_type((memo.size() * schedule.at( data_fee_type ).value)/1024);
   return bts_fee_required;
}

struct key_data_validate
{
   typedef void result_type;
   void operator()( const address& a )const { FC_ASSERT( a != address() ); }
   void operator()( const public_key_type& a )const { FC_ASSERT( a != public_key_type() ); }
};
void key_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   key_data.visit( key_data_validate() );
}

void account_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( is_valid_name( name ) );
   auto pos = name.find( '/' );
   if( pos != string::npos )
   {
      FC_ASSERT( owner.weight_threshold == 1 );
      FC_ASSERT( owner.auths.size() == 1 );
   }
}

share_type account_publish_feeds_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at( publish_feed_fee_type );
   return bts_fee_required;
}

void account_publish_feeds_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   optional<price> prev;
   for( auto item : feeds )
   {
      FC_ASSERT( item.base.amount >= share_type(0) ); // prevent divide by 0
      FC_ASSERT( item.quote.amount >= share_type(0) ); // prevent divide by 0
      if( prev )
      {
         FC_ASSERT( !(prev->base.asset_id == item.base.asset_id && prev->quote.asset_id == item.quote.asset_id) );
      }
      else prev = item;
   }
}

void transfer_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( from != to );
   FC_ASSERT( amount.amount > 0 );
}

void  asset_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( is_valid_symbol( symbol ) );
   FC_ASSERT( max_supply <= BTS_MAX_SHARE_SUPPLY );
   FC_ASSERT( max_supply > 0 );
   FC_ASSERT( market_fee_percent <= BTS_MAX_MARKET_FEE_PERCENT );
   FC_ASSERT( permissions <= market_issued );
   FC_ASSERT( flags <= market_issued );
   FC_ASSERT( core_exchange_rate.quote.asset_id == asset_id_type() );
   FC_ASSERT( core_exchange_rate.base.asset_id == asset_id_type() );
   FC_ASSERT( core_exchange_rate.base.amount > 0 );
   FC_ASSERT( core_exchange_rate.quote.amount > 0 );

   FC_ASSERT( !(flags & ~permissions ) );
   if( permissions & market_issued )
   {
      FC_ASSERT( !(permissions & ~(white_list) ) );
      FC_ASSERT( !(permissions & ~(override_authority) ) );
      FC_ASSERT( !(permissions & ~(halt_transfer) ) );
   }
}

void asset_update_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( permissions <= market_issued );
   FC_ASSERT( flags <= market_issued );
   if( core_exchange_rate )
   {
      FC_ASSERT( core_exchange_rate->base.amount >= share_type(0) );
      FC_ASSERT( core_exchange_rate->base.asset_id == asset_id_type() );
      FC_ASSERT( core_exchange_rate->quote.amount >= share_type(0) );
      FC_ASSERT( core_exchange_rate->quote.asset_id == asset_to_update );
   }
}

share_type asset_update_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( asset_update_fee_type );
}

void asset_issue_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( asset_to_issue.amount.value <= BTS_MAX_SHARE_SUPPLY );
   FC_ASSERT( asset_to_issue.amount.value > 0 );
   FC_ASSERT( asset_to_issue.asset_id != 0 );
}

share_type asset_issue_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( asset_issue_fee_type );
}

share_type delegate_create_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( delegate_create_fee_type ) ;
}
share_type delegate_update_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( delegate_update_fee_type ) ;
}

void delegate_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( pay_rate <= 100 );
   for( auto fee : fee_schedule ) FC_ASSERT( fee.value > 0 );
   FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT );
   FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT );
   FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL );
}
void delegate_update_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( pay_rate <= 100 || pay_rate == 255 );
   FC_ASSERT( fee_schedule || signing_key || pay_rate <= 100 );
   if( fee_schedule ) for( auto fee : *fee_schedule ) FC_ASSERT( fee.value > 0 );

   FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT );
   FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT );
   FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL );
}

void asset_fund_fee_pool_operation::validate() const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( fee.asset_id == asset_id_type() );
   FC_ASSERT( amount > 0 );
}

share_type asset_fund_fee_pool_operation::calculate_fee(const fee_schedule_type& k) const
{
   return k.at( asset_fund_fee_pool_fee_type );
}

} } // namespace bts::chain
<commit_msg>Disallow max trx exp time less than block interval<commit_after>#include <bts/chain/operations.hpp>

namespace bts { namespace chain {

/**
 *  Valid symbols have between 3 and 17 upper case characters
 *  with at most a single "." that is not the first or last character.
 */
bool is_valid_symbol( const string& symbol )
{
   if( symbol.size() > 17 ) return false;
   if( symbol.size() < 3  ) return false;
   int dot_count = 0;
   for( auto c : symbol )
   {
      if( c == '.' ) ++dot_count;
      else if( c < 'A' || c > 'Z' ) return false;
   }
   if( symbol[0] == '.' || symbol[symbol.size()-1] == '.' )
      return false;
   return dot_count <= 1;
}

/**
 *  Valid names are all lower case, start with [a-z] and may
 *  have "." or "-" in the name along with a single '/'.  The
 *  next character after a "/", "." or "-" cannot be [0-9] or
 *  another '.', '-'.
 *
 */
bool is_valid_name( const string& s )
{
   if( s.size() == 0  ) return true;
   if( s.size() <  3  ) return false;
   if( s.size() >= 64 ) return false;

   int num_slash = 0;
   char prev = ' ';
   for( auto c : s )
   {
      if( c >= 'a' && c <= 'z' ){}
      else if( c >= '0' && c <= '9' )
      {
         if( prev == ' ' || prev == '.' || prev == '-' || prev == '/' ) return false;
      }
      else switch( c )
      {
            case '/':
               if( ++num_slash > 1 ) return false;
            case '.':
            case '-':
               if( prev == ' ' || prev == '/' || prev == '.' || prev == '-' ) return false;
              break;
            default:
              return false;
      }
      prev = c;
   }
   switch( s.back() )
   {
      case '/': case '-': case '.':
         return false;
      default:
         return true;
   }
}
bool is_premium_name( const string& n )
{
   return false;
}
bool is_cheap_name( const string& n )
{
   for( auto c : n )
   {
      if( c >= '0' && c <= '9' ) return true;
      if( c == '.' || c == '-' || c == '/' ) return true;
   }
   return false;
}

share_type account_create_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at(account_create_fee_type);

   if( name.size() )
   {
      uint32_t s = name.size();
      if( is_premium_name( name ) )    s = 2;
      else if( is_cheap_name( name ) ) s = 63;
      while( s <= 8 ) {  bts_fee_required *= 10; ++s; }

   }
   return bts_fee_required;
}
share_type account_update_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   return schedule.at(account_create_fee_type);
}
void account_update_operation::validate()const
{
   FC_ASSERT( fee.amount > 0 );
   FC_ASSERT( owner || active || voting_key || memo_key || vote );

   if( vote && vote->size() > 1 )
   {
      for( int i = 1; i < vote->size(); ++i )
         FC_ASSERT( vote->at(i-1) < vote->at(i) );
   }
}

share_type asset_create_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at(asset_create_fee_type);

   uint32_t s = symbol.size();
   while( s <= 6 ) {  bts_fee_required *= 30; ++s; }

   return bts_fee_required;
}

share_type transfer_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at( transfer_fee_type );
   bts_fee_required += share_type((memo.size() * schedule.at( data_fee_type ).value)/1024);
   return bts_fee_required;
}

struct key_data_validate
{
   typedef void result_type;
   void operator()( const address& a )const { FC_ASSERT( a != address() ); }
   void operator()( const public_key_type& a )const { FC_ASSERT( a != public_key_type() ); }
};
void key_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   key_data.visit( key_data_validate() );
}

void account_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( is_valid_name( name ) );
   auto pos = name.find( '/' );
   if( pos != string::npos )
   {
      FC_ASSERT( owner.weight_threshold == 1 );
      FC_ASSERT( owner.auths.size() == 1 );
   }
}

share_type account_publish_feeds_operation::calculate_fee( const fee_schedule_type& schedule )const
{
   auto bts_fee_required = schedule.at( publish_feed_fee_type );
   return bts_fee_required;
}

void account_publish_feeds_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   optional<price> prev;
   for( auto item : feeds )
   {
      FC_ASSERT( item.base.amount >= share_type(0) ); // prevent divide by 0
      FC_ASSERT( item.quote.amount >= share_type(0) ); // prevent divide by 0
      if( prev )
      {
         FC_ASSERT( !(prev->base.asset_id == item.base.asset_id && prev->quote.asset_id == item.quote.asset_id) );
      }
      else prev = item;
   }
}

void transfer_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( from != to );
   FC_ASSERT( amount.amount > 0 );
}

void  asset_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( is_valid_symbol( symbol ) );
   FC_ASSERT( max_supply <= BTS_MAX_SHARE_SUPPLY );
   FC_ASSERT( max_supply > 0 );
   FC_ASSERT( market_fee_percent <= BTS_MAX_MARKET_FEE_PERCENT );
   FC_ASSERT( permissions <= market_issued );
   FC_ASSERT( flags <= market_issued );
   FC_ASSERT( core_exchange_rate.quote.asset_id == asset_id_type() );
   FC_ASSERT( core_exchange_rate.base.asset_id == asset_id_type() );
   FC_ASSERT( core_exchange_rate.base.amount > 0 );
   FC_ASSERT( core_exchange_rate.quote.amount > 0 );

   FC_ASSERT( !(flags & ~permissions ) );
   if( permissions & market_issued )
   {
      FC_ASSERT( !(permissions & ~(white_list) ) );
      FC_ASSERT( !(permissions & ~(override_authority) ) );
      FC_ASSERT( !(permissions & ~(halt_transfer) ) );
   }
}

void asset_update_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( permissions <= market_issued );
   FC_ASSERT( flags <= market_issued );
   if( core_exchange_rate )
   {
      FC_ASSERT( core_exchange_rate->base.amount >= share_type(0) );
      FC_ASSERT( core_exchange_rate->base.asset_id == asset_id_type() );
      FC_ASSERT( core_exchange_rate->quote.amount >= share_type(0) );
      FC_ASSERT( core_exchange_rate->quote.asset_id == asset_to_update );
   }
}

share_type asset_update_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( asset_update_fee_type );
}

void asset_issue_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( asset_to_issue.amount.value <= BTS_MAX_SHARE_SUPPLY );
   FC_ASSERT( asset_to_issue.amount.value > 0 );
   FC_ASSERT( asset_to_issue.asset_id != 0 );
}

share_type asset_issue_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( asset_issue_fee_type );
}

share_type delegate_create_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( delegate_create_fee_type ) ;
}
share_type delegate_update_operation::calculate_fee( const fee_schedule_type& k )const
{
   return k.at( delegate_update_fee_type ) ;
}

void delegate_create_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( pay_rate <= 100 );
   for( auto fee : fee_schedule ) FC_ASSERT( fee.value > 0 );
   FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT );
   FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT );
   FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL );
   FC_ASSERT( max_sec_until_expiration > block_interval_sec );
}
void delegate_update_operation::validate()const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( pay_rate <= 100 || pay_rate == 255 );
   FC_ASSERT( fee_schedule || signing_key || pay_rate <= 100 );
   if( fee_schedule ) for( auto fee : *fee_schedule ) FC_ASSERT( fee.value > 0 );

   FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT );
   FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT );
   FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL );
   FC_ASSERT( max_sec_until_expiration > block_interval_sec );
}

void asset_fund_fee_pool_operation::validate() const
{
   FC_ASSERT( fee.amount >= 0 );
   FC_ASSERT( fee.asset_id == asset_id_type() );
   FC_ASSERT( amount > 0 );
}

share_type asset_fund_fee_pool_operation::calculate_fee(const fee_schedule_type& k) const
{
   return k.at( asset_fund_fee_pool_fee_type );
}

} } // namespace bts::chain
<|endoftext|>


<commit_before>#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/Registry>

#include <sstream>
#include "ZipArchive.h"

class ReaderWriterZIP : public osgDB::ReaderWriter
{
    public:

        ReaderWriterZIP()
        {
            supportsExtension("zip","Zip archive format");
            osgDB::Registry::instance()->addArchiveExtension("zip");
        }

        virtual const char* className() const { return "ZIP Database Reader/Writer"; }

        virtual ReadResult openArchive(const std::string& file,ArchiveStatus status, unsigned int indexBlockSize = 4096, const Options* options = NULL) const
        {

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile(file, options);
            if (fileName.empty())
            {
                //we do not support writing so the file must exist
                return ReadResult::FILE_NOT_FOUND;
            }

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options =  options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            osg::ref_ptr<ZipArchive> archive = new ZipArchive;
            if (!archive->open(fileName, osgDB::ReaderWriter::READ, local_options.get()))
            {
                return ReadResult(ReadResult::FILE_NOT_HANDLED);
            }

            return archive.get();
        }

        /** open an archive for reading.*/
        virtual ReadResult openArchive(std::istream& fin, const Options* options) const
        {
            osg::ref_ptr<ZipArchive> archive = new ZipArchive;
            if (!archive->open(fin, options))
            {
                return ReadResult(ReadResult::FILE_NOT_HANDLED);
            }

            return archive.get();
        }

        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ);

            if (!result.validArchive()) return result;

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            local_options->setDatabasePath(file);

            //todo- what should we read here?
            osgDB::ReaderWriter::ReadResult result_2 = result.getArchive()->readNode(result.getArchive()->getMasterFileName(),local_options.get());

            if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES))
            {
                // register the archive so that it is cached for future use.
                osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive());
            }

            return result_2;

        }

        virtual ReadResult readNode(std::istream& fin,const osgDB::ReaderWriter::Options* options) const
        {

            osgDB::ReaderWriter::ReadResult result = openArchive(fin, options);

            if (!result.validArchive()) return result;

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            //todo- what should the database path be?
            //local_options->setDatabasePath(file);

            //todo- what should we read here?
            osgDB::ReaderWriter::ReadResult result_2 = result.getArchive()->readNode(result.getArchive()->getMasterFileName(),local_options.get());

            //todo- what to do to cache the archive here?
            //if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES))
            //{
            //   // register the archive so that it is cached for future use.
            //   osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive());
            //}

            return result_2;
        }

        virtual ReadResult readImage(const std::string& file,const Options* options) const
        {
           ReadResult result = openArchive(file,osgDB::Archive::READ);

           if (!result.validArchive()) return result;

           // copy the incoming options if possible so that plugin options can be applied to files
           // inside the archive
           osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

           local_options->setDatabasePath(file);

           ReadResult result_2 = result.getArchive()->readImage(result.getArchive()->getMasterFileName(),local_options.get());

           if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES))
           {
              // register the archive so that it is cached for future use.
              osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive());
           }

           return result_2;
        }

};

// now register with sgRegistry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(zip, ReaderWriterZIP)
<commit_msg>Added better handling of archives in ReaderWriterZip::readNode() so that if there is no master file definition it loads all the available nodes in the zip archive and returns an osg::Group containing all the nodes if there is more than one, or just returns the node if there is just one.  Also implemented this functionality for ReaderWriterZip::readImage().<commit_after>#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/Registry>

#include <sstream>
#include "ZipArchive.h"

class ReaderWriterZIP : public osgDB::ReaderWriter
{
    public:

        ReaderWriterZIP()
        {
            supportsExtension("zip","Zip archive format");
            osgDB::Registry::instance()->addArchiveExtension("zip");
        }

        virtual const char* className() const { return "ZIP Database Reader/Writer"; }

        virtual ReadResult openArchive(const std::string& file,ArchiveStatus status, unsigned int indexBlockSize = 4096, const Options* options = NULL) const
        {

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile(file, options);
            if (fileName.empty())
            {
                //we do not support writing so the file must exist
                return ReadResult::FILE_NOT_FOUND;
            }

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options =  options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            osg::ref_ptr<ZipArchive> archive = new ZipArchive;
            if (!archive->open(fileName, osgDB::ReaderWriter::READ, local_options.get()))
            {
                return ReadResult(ReadResult::FILE_NOT_HANDLED);
            }

            return archive.get();
        }

        /** open an archive for reading.*/
        virtual ReadResult openArchive(std::istream& fin, const Options* options) const
        {
            osg::ref_ptr<ZipArchive> archive = new ZipArchive;
            if (!archive->open(fin, options))
            {
                return ReadResult(ReadResult::FILE_NOT_HANDLED);
            }

            return archive.get();
        }

        osgDB::ReaderWriter::ReadResult readNodeFromArchive(osgDB::Archive& archive, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result(osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND);

            if (!archive.getMasterFileName().empty())
            {
                result = archive.readNode(archive.getMasterFileName(), options);
            }
            else
            {
                osgDB::Archive::FileNameList fileNameList;
                if (archive.getFileNames(fileNameList))
                {
                    typedef std::list< osg::ref_ptr<osg::Node> > Nodes;
                    Nodes nodes;
                    for(osgDB::Archive::FileNameList::iterator itr = fileNameList.begin();
                        itr != fileNameList.end();
                        ++itr)
                    {
                        result = archive.readNode(*itr, options);
                        if (result.validNode()) nodes.push_back(result.getNode());
                    }

                    if (!nodes.empty())
                    {
                        if (nodes.size()==1)
                        {
                            result = osgDB::ReaderWriter::ReadResult(nodes.front().get());
                        }
                        else
                        {
                            osg::ref_ptr<osg::Group> group = new osg::Group;
                            for(Nodes::iterator itr = nodes.begin();
                                itr != nodes.end();
                                ++itr)
                            {
                                group->addChild(itr->get());
                            }
                            result = osgDB::ReaderWriter::ReadResult(group.get());
                        }
                    }
                }
            }
            return result;
        }

        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ);

            if (!result.validArchive()) return result;

            osg::ref_ptr<osgDB::Archive> archive = result.getArchive();

            if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES))
            {
                // register the archive so that it is cached for future use.
                osgDB::Registry::instance()->addToArchiveCache(file, archive.get());
            }

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            local_options->setDatabasePath(file);

            return readNodeFromArchive(*archive, local_options.get());
        }

        virtual ReadResult readNode(std::istream& fin,const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = openArchive(fin, options);

            if (!result.validArchive()) return result;

            osg::ref_ptr<osgDB::Archive> archive = result.getArchive();

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            return readNodeFromArchive(*archive, local_options.get());
        }

        osgDB::ReaderWriter::ReadResult readImageFromArchive(osgDB::Archive& archive, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result(osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND);

            if (!archive.getMasterFileName().empty())
            {
                result = archive.readImage(archive.getMasterFileName(), options);
            }
            else
            {
                osgDB::Archive::FileNameList fileNameList;
                if (archive.getFileNames(fileNameList))
                {
                    for(osgDB::Archive::FileNameList::iterator itr = fileNameList.begin();
                        itr != fileNameList.end() && !result.validImage();
                        ++itr)
                    {
                        result = archive.readImage(*itr, options);
                    }
                }
            }
            return result;
        }

        virtual ReadResult readImage(const std::string& file,const Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ);

            if (!result.validArchive()) return result;

            osg::ref_ptr<osgDB::Archive> archive = result.getArchive();

            if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES))
            {
                // register the archive so that it is cached for future use.
                osgDB::Registry::instance()->addToArchiveCache(file, archive.get());
            }

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            local_options->setDatabasePath(file);

            return readImageFromArchive(*archive, local_options.get());
        }

        virtual ReadResult readImage(std::istream& fin,const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = openArchive(fin, options);

            if (!result.validArchive()) return result;

            osg::ref_ptr<osgDB::Archive> archive = result.getArchive();

            // copy the incoming options if possible so that plugin options can be applied to files
            // inside the archive
            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options?
                options->cloneOptions() :
                new osgDB::ReaderWriter::Options;

            return readImageFromArchive(*archive, local_options.get());
        }
};

// now register with sgRegistry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(zip, ReaderWriterZIP)
<|endoftext|>


<commit_before>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/sync/ModelSync.h"

#include "uwhd/model/GameModel.h"

#include <cstring>
#include <string>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <memory>
#include <cassert>

static const int MAX_EVENTS = 16;

using namespace uwhtimer;

class SocketSyncClient : public ModelSync, GameModelManager {
public:
  SocketSyncClient(const std::string &Host, const std::string &Port);

  virtual void Init() override;

  virtual void PushModel(GameModel M) override;

  virtual GameModel PullModel() override;

  virtual void setMgr(GameModelManager *M) override { assert(false); }

  virtual GameModelManager &getMgr() override { return *this; }

  virtual void setModel(GameModel Model) override;

private:
  std::string Host;
  std::string Port;
  int SockFD;
};

SocketSyncClient::SocketSyncClient(const std::string &Host,
                                   const std::string &Port)
    : Host(Host), Port(Port) {
}

void SocketSyncClient::Init() {
  SockFD = socket(AF_INET, SOCK_STREAM, 0);

  if (SockFD < 0) {
    perror("Error opening socket");
    exit(1);
  }

  struct hostent *server = gethostbyname(Host.c_str());

  if (server == nullptr) {
    fprintf(stderr, "ERROR, no such host\n");
    exit(0);
  }

  struct sockaddr_in serv_addr;
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
  serv_addr.sin_port = htons(atoi(Port.c_str()));

  if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
    perror("ERROR connecting");
    exit(1);
  }

  const char *test = "SB2W1T13E";
  write(SockFD, test, strlen(test));
}

void SocketSyncClient::PushModel(GameModel M) {

}

GameModel SocketSyncClient::PullModel() {
  return GameModel();
}

void SocketSyncClient::setModel(GameModel Model) {
  std::string Ser = Model.serialize();
  write(SockFD, Ser.c_str(), Ser.size());
}

std::unique_ptr<ModelSync>
uwhtimer::CreateSocketClient(const std::string &Host,
                             const std::string &Port) {
  return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port));
}
<commit_msg>Print messages on send<commit_after>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/sync/ModelSync.h"

#include "uwhd/model/GameModel.h"

#include <cstring>
#include <string>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <memory>
#include <cassert>
#include <iostream>

static const int MAX_EVENTS = 16;

using namespace uwhtimer;

class SocketSyncClient : public ModelSync, GameModelManager {
public:
  SocketSyncClient(const std::string &Host, const std::string &Port);

  virtual void Init() override;

  virtual void PushModel(GameModel M) override;

  virtual GameModel PullModel() override;

  virtual void setMgr(GameModelManager *M) override { assert(false); }

  virtual GameModelManager &getMgr() override { return *this; }

  virtual void setModel(GameModel Model) override;

private:
  std::string Host;
  std::string Port;
  int SockFD;
};

SocketSyncClient::SocketSyncClient(const std::string &Host,
                                   const std::string &Port)
    : Host(Host), Port(Port) {
}

void SocketSyncClient::Init() {
  SockFD = socket(AF_INET, SOCK_STREAM, 0);

  if (SockFD < 0) {
    perror("Error opening socket");
    exit(1);
  }

  struct hostent *server = gethostbyname(Host.c_str());

  if (server == nullptr) {
    fprintf(stderr, "ERROR, no such host\n");
    exit(0);
  }

  struct sockaddr_in serv_addr;
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
  serv_addr.sin_port = htons(atoi(Port.c_str()));

  if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
    perror("ERROR connecting");
    exit(1);
  }
}

void SocketSyncClient::PushModel(GameModel M) {

}

GameModel SocketSyncClient::PullModel() {
  return GameModel();
}

void SocketSyncClient::setModel(GameModel Model) {
  std::string Ser = Model.serialize();
  std::cout << "Sending: '" << Ser << "'\n";
  write(SockFD, Ser.c_str(), Ser.size());
}

std::unique_ptr<ModelSync>
uwhtimer::CreateSocketClient(const std::string &Host,
                             const std::string &Port) {
  return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port));
}
<|endoftext|>


<commit_before>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/sync/ModelSync.h"

#include "uwhd/model/GameModel.h"

#include <cstring>
#include <string>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <memory>
#include <cassert>
#include <iostream>

static const int MAX_EVENTS = 16;

using namespace uwhtimer;

class SocketSyncClient : public ModelSync, GameModelManager {
public:
  SocketSyncClient(const std::string &Host, const std::string &Port);

  virtual void Init() override;

  virtual void PushModel(GameModel M) override;

  virtual GameModel PullModel() override;

  virtual void setMgr(GameModelManager *M) override { assert(false); }

  virtual GameModelManager &getMgr() override { return *this; }

  virtual void setModel(GameModel Model) override;

private:
  std::string Host;
  std::string Port;
  int SockFD;
};

SocketSyncClient::SocketSyncClient(const std::string &Host,
                                   const std::string &Port)
    : Host(Host), Port(Port) {
}

void SocketSyncClient::Init() {
  SockFD = socket(AF_INET, SOCK_STREAM, 0);

  if (SockFD < 0) {
    perror("Error opening socket");
    exit(1);
  }

  struct hostent *server = gethostbyname(Host.c_str());

  if (server == nullptr) {
    fprintf(stderr, "ERROR, no such host\n");
    exit(0);
  }

  struct sockaddr_in serv_addr;
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
  serv_addr.sin_port = htons(atoi(Port.c_str()));

  if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
    perror("ERROR connecting");
    exit(1);
  }
}

void SocketSyncClient::PushModel(GameModel M) {

}

GameModel SocketSyncClient::PullModel() {
  return GameModel();
}

void SocketSyncClient::setModel(GameModel Model) {
  std::string Ser = Model.serialize();
  std::cout << "Sending: '" << Ser << "'\n";
  write(SockFD, Ser.c_str(), Ser.size());
  GameModelManager::setModel(Model);
}

std::unique_ptr<ModelSync>
uwhtimer::CreateSocketClient(const std::string &Host,
                             const std::string &Port) {
  return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port));
}
<commit_msg>Make client start a new connection for every transaction<commit_after>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/sync/ModelSync.h"

#include "uwhd/model/GameModel.h"

#include <cstring>
#include <string>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <memory>
#include <cassert>
#include <iostream>

static const int MAX_EVENTS = 16;

using namespace uwhtimer;

class SocketSyncClient : public ModelSync, GameModelManager {
public:
  SocketSyncClient(const std::string &Host, const std::string &Port);

  virtual void Init() override;

  virtual void PushModel(GameModel M) override;

  virtual GameModel PullModel() override;

  virtual void setMgr(GameModelManager *M) override { assert(false); }

  virtual GameModelManager &getMgr() override { return *this; }

  virtual void setModel(GameModel Model) override;

private:
  std::string Host;
  std::string Port;
};

SocketSyncClient::SocketSyncClient(const std::string &Host,
                                   const std::string &Port)
    : Host(Host), Port(Port) {
}

void SocketSyncClient::Init() {
}

void SocketSyncClient::PushModel(GameModel M) {

}

GameModel SocketSyncClient::PullModel() {
  return GameModel();
}

void SocketSyncClient::setModel(GameModel Model) {
  int SockFD = socket(AF_INET, SOCK_STREAM, 0);

  if (SockFD < 0) {
    perror("Error opening socket");
    exit(1);
  }

  struct hostent *server = gethostbyname(Host.c_str());

  if (server == nullptr) {
    fprintf(stderr, "ERROR, no such host\n");
    exit(0);
  }

  struct sockaddr_in serv_addr;
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
  serv_addr.sin_port = htons(atoi(Port.c_str()));

  if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
    perror("ERROR connecting");
    exit(1);
  }

  std::string Ser = Model.serialize();
  std::cout << "Sending: '" << Ser << "'\n";
  write(SockFD, Ser.c_str(), Ser.size());
  GameModelManager::setModel(Model);

  close(SockFD);
}

std::unique_ptr<ModelSync>
uwhtimer::CreateSocketClient(const std::string &Host,
                             const std::string &Port) {
  return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port));
}
<|endoftext|>