<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: statusbar.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-07 14:31:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
#define __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_
#include <uielement/statusbarmanager.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <vcl/status.hxx>

namespace framework
{

class FrameworkStatusBar : public StatusBar
{
    public:

        FrameworkStatusBar( Window*           pParent,
                            WinBits           nWinBits );
        virtual ~FrameworkStatusBar();

        void         SetStatusBarManager( StatusBarManager* pStatusBarManager );

        virtual void StateChanged( StateChangedType nType );
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        virtual void UserDraw(const UserDrawEvent& rUDEvt);
        virtual void Command( const CommandEvent &rEvt );
        virtual void MouseMove( const MouseEvent& rMEvt );
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );

    private:
        StatusBarManager*       m_pMgr;
        sal_Bool                m_bShow : 1,
                                m_bLock : 1;
};

}

#endif // __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.20); FILE MERGED 2008/04/01 10:57:58 thb 1.4.20.2: #i85898# Stripping all external header guards 2008/03/28 15:34:57 rt 1.4.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: statusbar.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
#define __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <uielement/statusbarmanager.hxx>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <vcl/status.hxx>

namespace framework
{

class FrameworkStatusBar : public StatusBar
{
    public:

        FrameworkStatusBar( Window*           pParent,
                            WinBits           nWinBits );
        virtual ~FrameworkStatusBar();

        void         SetStatusBarManager( StatusBarManager* pStatusBarManager );

        virtual void StateChanged( StateChangedType nType );
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        virtual void UserDraw(const UserDrawEvent& rUDEvt);
        virtual void Command( const CommandEvent &rEvt );
        virtual void MouseMove( const MouseEvent& rMEvt );
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );

    private:
        StatusBarManager*       m_pMgr;
        sal_Bool                m_bShow : 1,
                                m_bLock : 1;
};

}

#endif // __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
<|endoftext|>


<commit_before><?hh // strict
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * Hprose/HttpService.hh                                  *
 *                                                        *
 * hprose http service library for hack.                  *
 *                                                        *
 * LastModified: Mar 14, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

namespace Hprose {
    class HttpService extends Service {
        private static Map<int, string> $errorTable = Map {
            E_ERROR => 'Error',
            E_WARNING => 'Warning',
            E_PARSE => 'Parse Error',
            E_NOTICE => 'Notice',
            E_CORE_ERROR => 'Core Error',
            E_CORE_WARNING => 'Core Warning',
            E_COMPILE_ERROR => 'Compile Error',
            E_COMPILE_WARNING => 'Compile Warning',
            E_DEPRECATED => 'Deprecated',
            E_USER_ERROR => 'User Error',
            E_USER_WARNING => 'User Warning',
            E_USER_NOTICE => 'User Notice',
            E_USER_DEPRECATED => 'User Deprecated',
            E_STRICT => 'Runtime Notice',
            E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
        };
        private bool $crossDomain = false;
        private bool $P3P = false;
        private bool $get = true;
        private Map<string, bool> $origins = Map {};
        public ?(function(\stdClass): void) $onSendHeader = null;

        private function sendHeader(\stdClass $context): void {
            if ($this->onSendHeader !== null) {
                $sendHeader = $this->onSendHeader;
                $sendHeader($context);
            }
            header("Content-Type: text/plain");
            if ($this->P3P) {
                header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD ' .
                       'IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi ' .
                       'UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV ' .
                       'INT DEM CNT STA POL HEA PRE GOV"');
            }
            if ($this->crossDomain) {
                // UNSAFE
                if (array_key_exists('HTTP_ORIGIN', $_SERVER) &&
                    $_SERVER['HTTP_ORIGIN'] != "null") {
                    $origin = $_SERVER['HTTP_ORIGIN'];
                    if (count($this->origins) === 0 || $this->origins->contains(strtolower($origin))) {
                        header("Access-Control-Allow-Origin: " . $origin);
                        header("Access-Control-Allow-Credentials: true");
                    }
                }
                else {
                    header('Access-Control-Allow-Origin: *');
                }
            }
        }
        public function isCrossDomainEnabled(): bool {
            return $this->crossDomain;
        }
        public function setCrossDomainEnabled(bool $enable = true): void {
            $this->crossDomain = $enable;
        }
        public function isP3PEnabled(): bool {
            return $this->P3P;
        }
        public function setP3PEnabled(bool $enable = true): void {
            $this->P3P = $enable;
        }
        public function isGetEnabled(): bool {
            return $this->get;
        }
        public function setGetEnabled(bool $enable = true): void {
            $this->get = $enable;
        }
        public function addAccessControlAllowOrigin(string $origin): void {
            $count = count($origin);
            if (($count > 0) && ($origin[$count - 1] === "/")) {
                $origin = substr($origin, 0, -1);
            }
            $this->origins[strtolower($origin)] = true;
        }
        public function removeAccessControlAllowOrigin(string $origin): void {
            $count = count($origin);
            if (($count > 0) && ($origin[$count - 1] === "/")) {
                $origin = substr($origin, 0, -1);
            }
            $this->origins->remove(strtolower($origin));
        }
        public function handle(): void {
            $request = file_get_contents("php://input");

            $context = new \stdClass();
            $context->server = $this;
            $context->userdata = new \stdClass();

            set_error_handler(($errno, $errstr, $errfile, $errline) ==> {
                if ($this->debug) {
                    $errstr .= " in $errfile on line $errline";
                }
                $error = self::$errorTable[$errno] . ": " . $errstr;
                exit($this->sendError($error, $context));
            }, $this->error_types);

            ob_start($data ==> {
                $match = array();
                if (preg_match('/<b>.*? error<\/b>:(.*?)<br/', $data, $match)) {
                    if ($this->debug) {
                        $error = preg_replace('/<.*?>/', '', $match[1]);
                    }
                    else {
                        $error = preg_replace('/ in <b>.*<\/b>$/', '', $match[1]);
                    }
                    return $this->sendError(trim($error), $context);
                }
                return $this->outputFilter($data, $context);
            });

            ob_implicit_flush(0);
            @ob_clean();
            $this->sendHeader($context);
            $result = '';
            // UNSAFE
            if (($_SERVER['REQUEST_METHOD'] == 'GET') && $this->get) {
                $result = $this->doFunctionList($context);
            }
            elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $result = $this->defaultHandle($request, $context);
            }
            @ob_end_clean();
            exit($result);
        }
    }
    class HttpServer extends HttpService {
        public function start(): void {
            $this->handle();
        }
    }
}
<commit_msg>Changed exit to echo.<commit_after><?hh // strict
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * Hprose/HttpService.hh                                  *
 *                                                        *
 * hprose http service library for hack.                  *
 *                                                        *
 * LastModified: Mar 28, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

namespace Hprose {
    class HttpService extends Service {
        private static Map<int, string> $errorTable = Map {
            E_ERROR => 'Error',
            E_WARNING => 'Warning',
            E_PARSE => 'Parse Error',
            E_NOTICE => 'Notice',
            E_CORE_ERROR => 'Core Error',
            E_CORE_WARNING => 'Core Warning',
            E_COMPILE_ERROR => 'Compile Error',
            E_COMPILE_WARNING => 'Compile Warning',
            E_DEPRECATED => 'Deprecated',
            E_USER_ERROR => 'User Error',
            E_USER_WARNING => 'User Warning',
            E_USER_NOTICE => 'User Notice',
            E_USER_DEPRECATED => 'User Deprecated',
            E_STRICT => 'Runtime Notice',
            E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
        };
        private bool $crossDomain = false;
        private bool $P3P = false;
        private bool $get = true;
        private Map<string, bool> $origins = Map {};
        public ?(function(\stdClass): void) $onSendHeader = null;

        private function sendHeader(\stdClass $context): void {
            if ($this->onSendHeader !== null) {
                $sendHeader = $this->onSendHeader;
                $sendHeader($context);
            }
            header("Content-Type: text/plain");
            if ($this->P3P) {
                header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD ' .
                       'IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi ' .
                       'UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV ' .
                       'INT DEM CNT STA POL HEA PRE GOV"');
            }
            if ($this->crossDomain) {
                // UNSAFE
                if (array_key_exists('HTTP_ORIGIN', $_SERVER) &&
                    $_SERVER['HTTP_ORIGIN'] != "null") {
                    $origin = $_SERVER['HTTP_ORIGIN'];
                    if (count($this->origins) === 0 || $this->origins->contains(strtolower($origin))) {
                        header("Access-Control-Allow-Origin: " . $origin);
                        header("Access-Control-Allow-Credentials: true");
                    }
                }
                else {
                    header('Access-Control-Allow-Origin: *');
                }
            }
        }
        public function isCrossDomainEnabled(): bool {
            return $this->crossDomain;
        }
        public function setCrossDomainEnabled(bool $enable = true): void {
            $this->crossDomain = $enable;
        }
        public function isP3PEnabled(): bool {
            return $this->P3P;
        }
        public function setP3PEnabled(bool $enable = true): void {
            $this->P3P = $enable;
        }
        public function isGetEnabled(): bool {
            return $this->get;
        }
        public function setGetEnabled(bool $enable = true): void {
            $this->get = $enable;
        }
        public function addAccessControlAllowOrigin(string $origin): void {
            $count = count($origin);
            if (($count > 0) && ($origin[$count - 1] === "/")) {
                $origin = substr($origin, 0, -1);
            }
            $this->origins[strtolower($origin)] = true;
        }
        public function removeAccessControlAllowOrigin(string $origin): void {
            $count = count($origin);
            if (($count > 0) && ($origin[$count - 1] === "/")) {
                $origin = substr($origin, 0, -1);
            }
            $this->origins->remove(strtolower($origin));
        }
        public function handle(): void {
            $request = file_get_contents("php://input");

            $context = new \stdClass();
            $context->server = $this;
            $context->userdata = new \stdClass();

            set_error_handler(($errno, $errstr, $errfile, $errline) ==> {
                if ($this->debug) {
                    $errstr .= " in $errfile on line $errline";
                }
                $error = self::$errorTable[$errno] . ": " . $errstr;
                echo $this->sendError($error, $context);
            }, $this->error_types);

            ob_start($data ==> {
                $match = array();
                if (preg_match('/<b>.*? error<\/b>:(.*?)<br/', $data, $match)) {
                    if ($this->debug) {
                        $error = preg_replace('/<.*?>/', '', $match[1]);
                    }
                    else {
                        $error = preg_replace('/ in <b>.*<\/b>$/', '', $match[1]);
                    }
                    return $this->sendError(trim($error), $context);
                }
                return $this->outputFilter($data, $context);
            });

            ob_implicit_flush(0);
            @ob_clean();
            $this->sendHeader($context);
            $result = '';
            // UNSAFE
            if (($_SERVER['REQUEST_METHOD'] == 'GET') && $this->get) {
                $result = $this->doFunctionList($context);
            }
            elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $result = $this->defaultHandle($request, $context);
            }
            @ob_end_clean();
            echo $result;
        }
    }
    class HttpServer extends HttpService {
        public function start(): void {
            $this->handle();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Make sure ScopeMeasure has a name to let it survive till end of scope<commit_after><|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Jan Kotanski <jan.kotanski@desy.de>
// Created on: Nov 12, 2018
//

#include <gtest/gtest.h>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/node/group.hpp>
#include <h5cpp/dataspace/hyperslab.hpp>
#include <boost/filesystem.hpp>
#ifndef _MSC_VER
#include <sys/time.h>
#endif

using namespace hdf5;
namespace fs = boost::filesystem;

struct DatasetWriteSpeedTest : public testing::Test
{
  long long unsigned int xdim = 867;
  long long unsigned int ydim = 700;
  long long unsigned int nframe = 33;
  hdf5::file::File f;
  hdf5::node::Group root;
  hdf5::dataspace::Simple space;
  hdf5::dataspace::Simple fullspace;
  hdf5::dataspace::Simple memspace;
  property::DatasetCreationList dcpl;
  property::DatasetCreationList dcpl2;
  property::LinkCreationList lcpl;
  property::DatasetAccessList dapl;
  std::vector<unsigned short int> frame;
  std::vector<unsigned short int> allframes;
  dataspace::Hyperslab framespace;
  property::DatasetTransferList dtpl;

  DatasetWriteSpeedTest()
  {
#if H5_VERSION_GE(1, 10, 0)
    property::FileCreationList fcpl;
    property::FileAccessList fapl;
    fapl.library_version_bounds(property::LibVersion::LATEST,
                                property::LibVersion::LATEST);
    f = file::create("dataset_write_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl);
#else
    f = file::create("dataset_write_speed.h5", file::AccessFlags::TRUNCATE);
#endif
    root = f.root();
    space =  {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED}};
    fullspace =  {{nframe, xdim, ydim}, {dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED}};
    memspace = {{xdim, ydim}, {dataspace::Simple::UNLIMITED,
			       dataspace::Simple::UNLIMITED}};

    dcpl.layout(property::DatasetLayout::CHUNKED);
    dcpl.chunk({1, xdim, ydim});
    frame = std::vector<unsigned short int>(xdim * ydim);
    framespace = dataspace::Hyperslab({{0, 0, 0}, {1, xdim, ydim}});
    dcpl2.layout(property::DatasetLayout::CHUNKED);
    dcpl2.chunk({nframe, xdim, ydim});
    allframes = std::vector<unsigned short int>(nframe * xdim * ydim);

  }

protected:
  virtual void SetUp()
  {
    }

  virtual void TearDown() {
    fs::remove("dataset_write_speed.h5");
  }
};

#ifndef _MSC_VER
TEST_F(DatasetWriteSpeedTest, write_hyperslab)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  auto dtype = datatype::create<unsigned short int>();
  node::Dataset data0 = node::Dataset(root, "data0", dtype, space, lcpl, dcpl, dapl);
  gettimeofday(&stime0, NULL);
  for(long long unsigned int i = 0; i != nframe; i++){
    data0.extent(0, 1);
    framespace.offset({i, 0, 0});
    dataspace::Dataspace file_space = data0.dataspace();
    file_space.selection(dataspace::SelectionOperation::SET, framespace);
    data0.write(frame, dtype, memspace, file_space, dtpl);
  }
  gettimeofday(&etime0, NULL);

  node::Dataset data1 = node::Dataset(root,
				      "data1",
				      datatype::create<unsigned short int>(),
				      space,lcpl,dcpl,dapl);

  gettimeofday(&stime1, NULL);

  for(long long unsigned int i = 0; i != nframe; i++){
    data1.extent(0, 1);
    framespace.offset({i, 0, 0});

    data1.write(frame, framespace);
  }
  gettimeofday(&etime1, NULL);

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  // std::cerr << time0 <<  std::endl;
  // std::cerr << time1 <<  std::endl;
  EXPECT_GT(14 * time1, time0);
  EXPECT_GT(14 * time0, time1);
}

TEST_F(DatasetWriteSpeedTest, write)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  auto dtype = datatype::create<unsigned short int>();
  node::Dataset data0 = node::Dataset(root, "data2", dtype, space, lcpl, dcpl, dapl);
  gettimeofday(&stime0, NULL);
  for(long long unsigned int i = 0; i != nframe; i++){
    data0.extent(0, 1);
    framespace.offset({i, 0, 0});
    dataspace::Dataspace file_space = data0.dataspace();
    file_space.selection(dataspace::SelectionOperation::SET, framespace);
    data0.write(frame, dtype, memspace, file_space, dtpl);
  }
  gettimeofday(&etime0, NULL);

  node::Dataset data1 = node::Dataset(root,
				      "data3",
				      datatype::create<unsigned short int>(),
				      fullspace, lcpl, dcpl, dapl);

  gettimeofday(&stime1, NULL);

  data1.write(allframes);
  gettimeofday(&etime1, NULL);

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  // std::cerr << time0 <<  std::endl;
  // std::cerr << time1 <<  std::endl;
  EXPECT_GT(14 * time1, time0);
  EXPECT_GT(14 * time0, time1);
}

#endif
<commit_msg>remove dcpl2<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Jan Kotanski <jan.kotanski@desy.de>
// Created on: Nov 12, 2018
//

#include <gtest/gtest.h>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/node/group.hpp>
#include <h5cpp/dataspace/hyperslab.hpp>
#include <boost/filesystem.hpp>
#ifndef _MSC_VER
#include <sys/time.h>
#endif

using namespace hdf5;
namespace fs = boost::filesystem;

struct DatasetWriteSpeedTest : public testing::Test
{
  long long unsigned int xdim = 867;
  long long unsigned int ydim = 700;
  long long unsigned int nframe = 33;
  hdf5::file::File f;
  hdf5::node::Group root;
  hdf5::dataspace::Simple space;
  hdf5::dataspace::Simple fullspace;
  hdf5::dataspace::Simple memspace;
  property::DatasetCreationList dcpl;
  property::LinkCreationList lcpl;
  property::DatasetAccessList dapl;
  std::vector<unsigned short int> frame;
  std::vector<unsigned short int> allframes;
  dataspace::Hyperslab framespace;
  property::DatasetTransferList dtpl;

  DatasetWriteSpeedTest()
  {
#if H5_VERSION_GE(1, 10, 0)
    property::FileCreationList fcpl;
    property::FileAccessList fapl;
    fapl.library_version_bounds(property::LibVersion::LATEST,
                                property::LibVersion::LATEST);
    f = file::create("dataset_write_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl);
#else
    f = file::create("dataset_write_speed.h5", file::AccessFlags::TRUNCATE);
#endif
    root = f.root();
    space =  {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED}};
    fullspace =  {{nframe, xdim, ydim}, {dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED,
				dataspace::Simple::UNLIMITED}};
    memspace = {{xdim, ydim}, {dataspace::Simple::UNLIMITED,
			       dataspace::Simple::UNLIMITED}};

    dcpl.layout(property::DatasetLayout::CHUNKED);
    dcpl.chunk({1, xdim, ydim});
    frame = std::vector<unsigned short int>(xdim * ydim);
    framespace = dataspace::Hyperslab({{0, 0, 0}, {1, xdim, ydim}});
    allframes = std::vector<unsigned short int>(nframe * xdim * ydim);

  }

protected:
  virtual void SetUp()
  {
    }

  virtual void TearDown() {
    fs::remove("dataset_write_speed.h5");
  }
};

#ifndef _MSC_VER
TEST_F(DatasetWriteSpeedTest, write_hyperslab)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  auto dtype = datatype::create<unsigned short int>();
  node::Dataset data0 = node::Dataset(root, "data0", dtype, space, lcpl, dcpl, dapl);
  gettimeofday(&stime0, NULL);
  for(long long unsigned int i = 0; i != nframe; i++){
    data0.extent(0, 1);
    framespace.offset({i, 0, 0});
    dataspace::Dataspace file_space = data0.dataspace();
    file_space.selection(dataspace::SelectionOperation::SET, framespace);
    data0.write(frame, dtype, memspace, file_space, dtpl);
  }
  gettimeofday(&etime0, NULL);

  node::Dataset data1 = node::Dataset(root,
				      "data1",
				      datatype::create<unsigned short int>(),
				      space,lcpl,dcpl,dapl);

  gettimeofday(&stime1, NULL);

  for(long long unsigned int i = 0; i != nframe; i++){
    data1.extent(0, 1);
    framespace.offset({i, 0, 0});

    data1.write(frame, framespace);
  }
  gettimeofday(&etime1, NULL);

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  // std::cerr << time0 <<  std::endl;
  // std::cerr << time1 <<  std::endl;
  EXPECT_GT(14 * time1, time0);
  EXPECT_GT(14 * time0, time1);
}

TEST_F(DatasetWriteSpeedTest, write)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  auto dtype = datatype::create<unsigned short int>();
  node::Dataset data0 = node::Dataset(root, "data2", dtype, space, lcpl, dcpl, dapl);
  gettimeofday(&stime0, NULL);
  for(long long unsigned int i = 0; i != nframe; i++){
    data0.extent(0, 1);
    framespace.offset({i, 0, 0});
    dataspace::Dataspace file_space = data0.dataspace();
    file_space.selection(dataspace::SelectionOperation::SET, framespace);
    data0.write(frame, dtype, memspace, file_space, dtpl);
  }
  gettimeofday(&etime0, NULL);

  node::Dataset data1 = node::Dataset(root,
				      "data3",
				      datatype::create<unsigned short int>(),
				      fullspace, lcpl, dcpl, dapl);

  gettimeofday(&stime1, NULL);

  data1.write(allframes);
  gettimeofday(&etime1, NULL);

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  // std::cerr << time0 <<  std::endl;
  // std::cerr << time1 <<  std::endl;
  EXPECT_GT(14 * time1, time0);
  EXPECT_GT(14 * time0, time1);
}

#endif
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ethernet_client class @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "ethernet.hpp"

#include "common/delay.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ethernet_client class
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ethernet_client {

		ethernet&	ethernet_;

		uint32_t	cepid_;
		uint16_t	port_;

		uint16_t	close_count_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		ethernet_client(ethernet& e) : ethernet_(e), cepid_(0), port_(0),
			close_count_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  デストラクター
		*/
		//-----------------------------------------------------------------//
		~ethernet_client() {
			stop();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ethernet を参照
			@return ethernet
		*/
		//-----------------------------------------------------------------//
		ethernet& at_ethernet() { return ethernet_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  ethernet を参照
			@return ethernet
		*/
		//-----------------------------------------------------------------//
		const ethernet& get_ethernet() const { return ethernet_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  ポート番号を取得
			@return ポート番号
		*/
		//-----------------------------------------------------------------//
		uint16_t get_port() const { return port_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  CEP ID を取得
			@return CEP ID
		*/
		//-----------------------------------------------------------------//
		uint32_t get_cepid() const { return cepid_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  コネクション
			@param[in]	ip		接続先の IP アドレス
			@param[in]	port	接続ポート
			@param[in]	timeout	タイムアウト、単位１０ミリ秒（標準で１０秒）
			@return 接続できた場合「true」
		*/
		//-----------------------------------------------------------------//
		bool connect(const ip_address& ip, uint16_t port, int32_t timeout = 1000)
		{
			if(cepid_ == 0) {
				cepid_ = ethernet_.create(port);
				if(cepid_ == 0) return false;
				close_count_ = tcp_get_close_count(cepid_);
			}

			bool ret = false;
			if(!connected()) {
				static T_IPV4EP adr;
				adr.ipaddr =  (static_cast<uint32_t>(ip[0]) << 24)
							| (static_cast<uint32_t>(ip[1]) << 16)
							| (static_cast<uint32_t>(ip[2]) << 8)
							| (static_cast<uint32_t>(ip[3]));
				adr.portno = port;
				int ercd = tcp_con_cep(cepid_, NADR, &adr, timeout);
				static int ercd_ = 0;
				if(ercd_ != ercd) {
					utils::format("Client connection state: %d\n") % ercd;
					ercd_ = ercd;
				}
				if(ercd == E_OK) {
					ret = true;
				} else if(ercd == E_QOVR) {
///					ethernet_.reset(cepid_);
				}

				if(close_count_ != tcp_get_close_count(cepid_)) {
//					utils::format("Error close (timeout)\n");
					stop();  // 強制終了
				}

			} else {
				ret = true;
			}
			return ret;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  接続確認
			@return 接続中なら「true」
		*/
		//-----------------------------------------------------------------//
		bool connected()
		{
			return ethernet_.connected(cepid_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  読み込み
			@param[out]	buff	読み込み先
			@param[in]	size	読み込みサイズ
			@return 読み込みサイズ（負の場合エラー）
		*/
		//-----------------------------------------------------------------//
		int read(void* buff, size_t size)
		{
			return ethernet_.read(cepid_, buff, size);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	buff	書き込み元
			@param[in]	size	サイズ
			@return 書き込みサイズ（負の場合エラー）
		*/
		//-----------------------------------------------------------------//
		int32_t write(const void* buffer, uint32_t size)
		{
			return ethernet_.write(cepid_, buffer, size);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  有効なデータがあるか
			@return 有効なデータ数
		*/
		//-----------------------------------------------------------------//
		int available()
		{
			return ethernet_.available(cepid_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  停止
		*/
		//-----------------------------------------------------------------//
        void stop()
		{
			tcp_sht_cep(cepid_, TMO_FEVR);
			tcp_cls_cep(cepid_, TMO_FEVR);
			ethernet::CEP& cep = ethernet_.at_cep(cepid_);
			cep.call_flag = false;
			end();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  終了
		*/
		//-----------------------------------------------------------------//
		void end()
		{
			tcp_init(cepid_);
			ethernet_.end_connection(cepid_);
			cepid_ = 0;
		}
	};
}

<commit_msg>update port number at constructor<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ethernet_client class @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "ethernet.hpp"

#include "common/delay.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ethernet_client class
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ethernet_client {

		ethernet&	ethernet_;

		uint32_t	cepid_;
		uint16_t	port_;

		uint16_t	close_count_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	e	インサーネットへの参照
			@param[in]	port	ポート番号
		*/
		//-----------------------------------------------------------------//
		ethernet_client(ethernet& e, uint16_t port) : ethernet_(e), cepid_(0), port_(port),
			close_count_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  デストラクター
		*/
		//-----------------------------------------------------------------//
		~ethernet_client() {
			stop();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ethernet を参照
			@return ethernet
		*/
		//-----------------------------------------------------------------//
		ethernet& at_ethernet() { return ethernet_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  ethernet を参照
			@return ethernet
		*/
		//-----------------------------------------------------------------//
		const ethernet& get_ethernet() const { return ethernet_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  ポート番号を取得
			@return ポート番号
		*/
		//-----------------------------------------------------------------//
		uint16_t get_port() const { return port_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  CEP ID を取得
			@return CEP ID
		*/
		//-----------------------------------------------------------------//
		uint32_t get_cepid() const { return cepid_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  コネクション
			@param[in]	ip		接続先の IP アドレス
			@param[in]	port	接続ポート
			@param[in]	timeout	タイムアウト、単位１０ミリ秒（標準で１０秒）
			@return 接続できた場合「true」
		*/
		//-----------------------------------------------------------------//
		bool connect(const ip_address& ip, uint16_t port, int32_t timeout = 1000)
		{
			if(cepid_ == 0) {
				cepid_ = ethernet_.create(port_);
				if(cepid_ == 0) return false;
				close_count_ = tcp_get_close_count(cepid_);
			}

			bool ret = false;
			if(!connected()) {
				static T_IPV4EP adr;
				adr.ipaddr =  (static_cast<uint32_t>(ip[0]) << 24)
							| (static_cast<uint32_t>(ip[1]) << 16)
							| (static_cast<uint32_t>(ip[2]) << 8)
							| (static_cast<uint32_t>(ip[3]));
				adr.portno = port;
				int ercd = tcp_con_cep(cepid_, NADR, &adr, timeout);
				static int ercd_ = 0;
				if(ercd_ != ercd) {
					utils::format("Client connection state: %d\n") % ercd;
					ercd_ = ercd;
				}
				if(ercd == E_OK) {
					ret = true;
				} else if(ercd == E_QOVR) {
///					ethernet_.reset(cepid_);
				}

				if(close_count_ != tcp_get_close_count(cepid_)) {
//					utils::format("Error close (timeout)\n");
					stop();  // 強制終了
				}

			} else {
				ret = true;
			}
			return ret;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  接続確認
			@return 接続中なら「true」
		*/
		//-----------------------------------------------------------------//
		bool connected()
		{
			return ethernet_.connected(cepid_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  読み込み
			@param[out]	buff	読み込み先
			@param[in]	size	読み込みサイズ
			@return 読み込みサイズ（負の場合エラー）
		*/
		//-----------------------------------------------------------------//
		int read(void* buff, size_t size)
		{
			return ethernet_.read(cepid_, buff, size);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	buff	書き込み元
			@param[in]	size	サイズ
			@return 書き込みサイズ（負の場合エラー）
		*/
		//-----------------------------------------------------------------//
		int32_t write(const void* buffer, uint32_t size)
		{
			return ethernet_.write(cepid_, buffer, size);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  有効なデータがあるか
			@return 有効なデータ数
		*/
		//-----------------------------------------------------------------//
		int available()
		{
			return ethernet_.available(cepid_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  停止
		*/
		//-----------------------------------------------------------------//
        void stop()
		{
			tcp_sht_cep(cepid_, TMO_FEVR);
			tcp_cls_cep(cepid_, TMO_FEVR);
			ethernet::CEP& cep = ethernet_.at_cep(cepid_);
			cep.call_flag = false;
			end();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  終了
		*/
		//-----------------------------------------------------------------//
		void end()
		{
			tcp_init(cepid_);
			ethernet_.end_connection(cepid_);
			cepid_ = 0;
		}
	};
}

<|endoftext|>


<commit_before>#include "dsa_common.h"
#include "core/session.h"
#include "network/ws/ws_client_connection.h"
#include "util/app.h"
#include "util/enable_shared.h"
#include "web_server/web_server.h"

#include "../async_test.h"
#include "../test_config.h"

#include "gtest/gtest.h"

using namespace dsa;

TEST(WebServerTest, basic_flow) {
  auto app = make_shared_<App>();

// auto web_server = make_shared_<WebServer>(&app, cert);

  // server
  auto web_server = std::make_shared<WebServer>(*app);
  web_server->start();

  // client
  const string_ dsid_prefix = "ws_";
  const string_ ws_host = "127.0.0.1";
  uint16_t ws_port = 8080;
  TestConfig test_config(app, false);
  LinkStrandRef link_strand(std::move(test_config.strand));

  // Simplified websocket client
  auto client = make_shared_<WsClientConnection>(link_strand, dsid_prefix, ws_host,
                                           ws_port);
  client->set_session(make_ref_<Session>(link_strand, ""));
  client->connect(60);

  ASYNC_EXPECT_TRUE(500, *link_strand, [&]() {
    if (client->session()->is_connected()) {
      return true;
    }
  });

  app->close();

  //  WAIT_EXPECT_TRUE(500, [&]() -> bool { return app->is_stopped(); });

  if (!app->is_stopped()) {
    app->force_stop();
  }

  test_config.destroy();
  app->wait();

    /*
  web_server->listen(port = 80);
  web_server->listen_secure(port=443);

  web_server->add_ws_handler(.... [](){
  new WsConnection();
    */
}

<commit_msg>stop calling app->force_stop to avoid memory leaks<commit_after>#include "dsa_common.h"
#include "core/session.h"
#include "network/ws/ws_client_connection.h"
#include "util/app.h"
#include "util/enable_shared.h"
#include "web_server/web_server.h"

#include "../async_test.h"
#include "../test_config.h"

#include "gtest/gtest.h"

using namespace dsa;

TEST(WebServerTest, basic_flow) {
  auto app = make_shared_<App>();

// auto web_server = make_shared_<WebServer>(&app, cert);

  // server
  auto web_server = std::make_shared<WebServer>(*app);
  web_server->start();

  // client
  const string_ dsid_prefix = "ws_";
  const string_ ws_host = "127.0.0.1";
  uint16_t ws_port = 8080;
  TestConfig test_config(app, false);
  LinkStrandRef link_strand(std::move(test_config.strand));

  // Simplified websocket client
  auto client = make_shared_<WsClientConnection>(link_strand, dsid_prefix, ws_host,
                                           ws_port);
  client->set_session(make_ref_<Session>(link_strand, ""));
  client->connect(60);

  ASYNC_EXPECT_TRUE(500, *link_strand, [&]() {
    if (client->session()->is_connected()) {
      return true;
    }
    return false;
  });

  app->close();

  test_config.destroy();
  //  app->wait();

    /*
  web_server->listen(port = 80);
  web_server->listen_secure(port=443);

  web_server->add_ws_handler(.... [](){
  new WsConnection();
    */
}

<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

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

registerMooseObject("MooseTestApp", ReadTripleIndex);

InputParameters
ReadTripleIndex::validParams()
{
  InputParameters params = GeneralUserObject::validParams();
  params.addRequiredParam<std::vector<std::vector<std::vector<Real>>>>(
      "real_tri", "A triple-indexed vector of real numbers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<unsigned int>>>>(
      "uint_tri", "A triple-indexed vector of unsigned integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<int>>>>(
      "int_tri", "A triple-indexed vector of integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<long>>>>(
      "long_tri", "A triple-indexed vector of long integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<SubdomainID>>>>(
      "subid_tri", "A triple-indexed vector of SubdomainID.");
  params.addRequiredParam<std::vector<std::vector<std::vector<BoundaryID>>>>(
      "bid_tri", "A triple-indexed vector of BoundaryID.");
  params.addRequiredParam<std::vector<std::vector<std::vector<std::string>>>>(
      "str_tri", "A triple-indexed vector of std::string.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FileName>>>>(
      "file_tri", "A triple-indexed vector of FileName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FileNameNoExtension>>>>(
      "file_no_tri", "A triple-indexed vector of FileNameNoExtension.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MeshFileName>>>>(
      "mesh_file_tri", "A triple-indexed vector of MeshFileName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<SubdomainName>>>>(
      "subdomain_name_tri", "A triple-indexed vector of SubdomainName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<BoundaryName>>>>(
      "boundary_name_tri", "A triple-indexed vector of BoundaryName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FunctionName>>>>(
      "function_name_tri", "A triple-indexed vector of FunctionName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<UserObjectName>>>>(
      "userobject_name_tri", "A triple-indexed vector of UserObjectName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<IndicatorName>>>>(
      "indicator_name_tri", "A triple-indexed vector of IndicatorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MarkerName>>>>(
      "marker_name_tri", "A triple-indexed vector of MarkerName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MultiAppName>>>>(
      "multiapp_name_tri", "A triple-indexed vector of MultiAppName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<PostprocessorName>>>>(
      "postprocessor_name_tri", "A triple-indexed vector of PostprocessorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<VectorPostprocessorName>>>>(
      "vector_postprocessor_name_tri", "A triple-indexed vector of VectorPostprocessorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<OutputName>>>>(
      "output_name_tri", "A triple-indexed vector of OutputName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MaterialPropertyName>>>>(
      "material_property_name_tri", "A triple-indexed vector of MaterialPropertyName.");
  return params;
}

ReadTripleIndex::ReadTripleIndex(const InputParameters & params)
  : GeneralUserObject(params),
    _real_tri(getParam<std::vector<std::vector<std::vector<Real>>>>("real_tri")),
    _uint_tri(getParam<std::vector<std::vector<std::vector<unsigned int>>>>("uint_tri")),
    _int_tri(getParam<std::vector<std::vector<std::vector<int>>>>("int_tri")),
    _long_tri(getParam<std::vector<std::vector<std::vector<long>>>>("long_tri")),
    _subid_tri(getParam<std::vector<std::vector<std::vector<SubdomainID>>>>("subid_tri")),
    _bid_tri(getParam<std::vector<std::vector<std::vector<BoundaryID>>>>("bid_tri")),
    _str_tri(getParam<std::vector<std::vector<std::vector<std::string>>>>("str_tri")),
    _file_tri(getParam<std::vector<std::vector<std::vector<FileName>>>>("file_tri")),
    _file_no_tri(
        getParam<std::vector<std::vector<std::vector<FileNameNoExtension>>>>("file_no_tri")),
    _mesh_file_tri(getParam<std::vector<std::vector<std::vector<MeshFileName>>>>("mesh_file_tri")),
    _subdomain_name_tri(
        getParam<std::vector<std::vector<std::vector<SubdomainName>>>>("subdomain_name_tri")),
    _boundary_name_tri(
        getParam<std::vector<std::vector<std::vector<BoundaryName>>>>("boundary_name_tri")),
    _function_name_tri(
        getParam<std::vector<std::vector<std::vector<FunctionName>>>>("function_name_tri")),
    _userobject_name_tri(
        getParam<std::vector<std::vector<std::vector<UserObjectName>>>>("userobject_name_tri")),
    _indicator_name_tri(
        getParam<std::vector<std::vector<std::vector<IndicatorName>>>>("indicator_name_tri")),
    _marker_name_tri(
        getParam<std::vector<std::vector<std::vector<MarkerName>>>>("marker_name_tri")),
    _multiapp_name_tri(
        getParam<std::vector<std::vector<std::vector<MultiAppName>>>>("multiapp_name_tri")),
    _postprocessor_name_tri(getParam<std::vector<std::vector<std::vector<PostprocessorName>>>>(
        "postprocessor_name_tri")),
    _vector_postprocessor_name_tri(
        getParam<std::vector<std::vector<std::vector<VectorPostprocessorName>>>>(
            "vector_postprocessor_name_tri")),
    _output_name_tri(
        getParam<std::vector<std::vector<std::vector<OutputName>>>>("output_name_tri")),
    _material_property_name_tri(
        getParam<std::vector<std::vector<std::vector<MaterialPropertyName>>>>(
            "material_property_name_tri"))
{
  const std::vector<std::vector<std::vector<Real>>> reference_values = {
      {{1.1}, {2.1, 2.2, 2.3}, {3.1, 3.2}},
      {{11.1, 11.2}},
      {{21.1, 21.2}, {22.1}, {23.1, 23.2, 23.3}}};

  // check real
  TripleIndexNumberVectorChecker(_real_tri, "real_tri", reference_values);

  // check unsigned int
  TripleIndexNumberVectorChecker(_uint_tri, "uint_tri", reference_values, false, false, 10.0);

  // check int
  TripleIndexNumberVectorChecker(_int_tri, "int_tri", reference_values, true, true, 10.0);

  // check long
  TripleIndexNumberVectorChecker(_long_tri, "long_tri", reference_values, true, false, 10.0);

  // check SubdomainID
  TripleIndexNumberVectorChecker(_subid_tri, "subid_tri", reference_values, false, false, 10.0, 30.0);

  // check BoundaryID
  TripleIndexNumberVectorChecker(_bid_tri, "bid_tri", reference_values, false, false, 10.0, 35.0);

  // check std::string
  TripleIndexStringVectorChecker(_str_tri, "str_tri", "string", reference_values);

  // check FileName
  TripleIndexStringVectorChecker(_file_tri, "file_tri", "file", reference_values);

  // check FileNameNoExtension
  TripleIndexStringVectorChecker(_file_no_tri, "file_no_tri", "file_no", reference_values);

  // check MeshFileName
  TripleIndexStringVectorChecker(_mesh_file_tri, "mesh_file_tri", "mesh_file", reference_values);

  // check SubdomainName
  TripleIndexStringVectorChecker(
      _subdomain_name_tri, "subdomain_name_tri", "subdomain_name", reference_values);

  // check BoundaryName
  TripleIndexStringVectorChecker(
      _boundary_name_tri, "boundary_name_tri", "boundary_name", reference_values);

  // check FunctionName
  TripleIndexStringVectorChecker(
      _function_name_tri, "function_name_tri", "function_name", reference_values);

  // check UserObjectName
  TripleIndexStringVectorChecker(
      _userobject_name_tri, "userobject_name_tri", "userobject_name", reference_values);

  // check IndicatorName
  TripleIndexStringVectorChecker(
      _indicator_name_tri, "indicator_name_tri", "indicator_name", reference_values);

  // check MarkerName
  TripleIndexStringVectorChecker(
      _marker_name_tri, "marker_name_tri", "marker_name", reference_values);

  // check MultiAppName
  TripleIndexStringVectorChecker(
      _multiapp_name_tri, "multiapp_name_tri", "multiapp_name", reference_values);

  // check PostprocessorName
  TripleIndexStringVectorChecker(
      _postprocessor_name_tri, "postprocessor_name_tri", "postprocessor_name", reference_values);

  // check VectorPostprocessorName
  TripleIndexStringVectorChecker(_vector_postprocessor_name_tri,
                                 "vector_postprocessor_name_tri",
                                 "vector_postprocessor_name",
                                 reference_values);

  // check OutputName
  TripleIndexStringVectorChecker(
      _output_name_tri, "output_name_tri", "output_name", reference_values);

  // check MaterialPropertyName
  TripleIndexStringVectorChecker(_material_property_name_tri,
                                 "material_property_name_tri",
                                 "material_property_name",
                                 reference_values);
}

template <typename T>
void
ReadTripleIndex::TripleIndexNumberVectorChecker(
    const std::vector<std::vector<std::vector<T>>> triple_index_vector,
    const std::string vector_name,
    const std::vector<std::vector<std::vector<Real>>> reference_values,
    const bool index_flip,
    const bool flip_direction,
    const Real scale_factor,
    const Real offset_value)
{
  if (triple_index_vector.size() != reference_values.size())
    mooseError("Error reading ", vector_name, ".");
  for (unsigned int i = 0; i < triple_index_vector.size(); i++)
  {
    if (triple_index_vector[i].size() != reference_values[i].size())
      mooseError("Error reading ", vector_name, ".");
    for (unsigned int j = 0; j < triple_index_vector[i].size(); j++)
    {
      if (triple_index_vector[i][j].size() != reference_values[i][j].size())
        mooseError("Error reading ", vector_name, ".");
      for (unsigned int k = 0; k < triple_index_vector[i][j].size(); k++)
        if (triple_index_vector[i][j][k] !=
            static_cast<T>((reference_values[i][j][k] * scale_factor + offset_value) *
                           (index_flip
                                ? (flip_direction ? ((i % 2 ? 1.0 : -1.0) * (j % 2 ? 1.0 : -1.0))
                                                  : ((i % 2 ? 1.0 : -1.0) * (j % 2 ? -1.0 : 1.0)))
                                : 1.0)))
          mooseError("Error reading ", vector_name, ".");
    }
  }
}

template <typename T>
void
ReadTripleIndex::TripleIndexStringVectorChecker(
    const T triple_index_vector,
    const std::string vector_name,
    const std::string prefix,
    const std::vector<std::vector<std::vector<Real>>> reference_values)
{
  if (triple_index_vector.size() != reference_values.size())
    mooseError("Error reading ", vector_name, ".");
  for (unsigned int i = 0; i < triple_index_vector.size(); i++)
  {
    if (triple_index_vector[i].size() != reference_values[i].size())
      mooseError("Error reading ", vector_name, ".");
    for (unsigned int j = 0; j < triple_index_vector[i].size(); j++)
    {
      if (triple_index_vector[i][j].size() != reference_values[i][j].size())
        mooseError("Error reading ", vector_name, ".");
      for (unsigned int k = 0; k < triple_index_vector[i][j].size(); k++)
      {
        std::stringstream ss;
        ss << prefix << i << j << k;
        if (triple_index_vector[i][j][k] != ss.str())
          mooseError("Error reading ", vector_name, ".");
      }
    }
  }
}
<commit_msg>clang format fix ref #21930<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

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

registerMooseObject("MooseTestApp", ReadTripleIndex);

InputParameters
ReadTripleIndex::validParams()
{
  InputParameters params = GeneralUserObject::validParams();
  params.addRequiredParam<std::vector<std::vector<std::vector<Real>>>>(
      "real_tri", "A triple-indexed vector of real numbers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<unsigned int>>>>(
      "uint_tri", "A triple-indexed vector of unsigned integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<int>>>>(
      "int_tri", "A triple-indexed vector of integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<long>>>>(
      "long_tri", "A triple-indexed vector of long integers.");
  params.addRequiredParam<std::vector<std::vector<std::vector<SubdomainID>>>>(
      "subid_tri", "A triple-indexed vector of SubdomainID.");
  params.addRequiredParam<std::vector<std::vector<std::vector<BoundaryID>>>>(
      "bid_tri", "A triple-indexed vector of BoundaryID.");
  params.addRequiredParam<std::vector<std::vector<std::vector<std::string>>>>(
      "str_tri", "A triple-indexed vector of std::string.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FileName>>>>(
      "file_tri", "A triple-indexed vector of FileName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FileNameNoExtension>>>>(
      "file_no_tri", "A triple-indexed vector of FileNameNoExtension.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MeshFileName>>>>(
      "mesh_file_tri", "A triple-indexed vector of MeshFileName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<SubdomainName>>>>(
      "subdomain_name_tri", "A triple-indexed vector of SubdomainName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<BoundaryName>>>>(
      "boundary_name_tri", "A triple-indexed vector of BoundaryName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<FunctionName>>>>(
      "function_name_tri", "A triple-indexed vector of FunctionName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<UserObjectName>>>>(
      "userobject_name_tri", "A triple-indexed vector of UserObjectName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<IndicatorName>>>>(
      "indicator_name_tri", "A triple-indexed vector of IndicatorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MarkerName>>>>(
      "marker_name_tri", "A triple-indexed vector of MarkerName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MultiAppName>>>>(
      "multiapp_name_tri", "A triple-indexed vector of MultiAppName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<PostprocessorName>>>>(
      "postprocessor_name_tri", "A triple-indexed vector of PostprocessorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<VectorPostprocessorName>>>>(
      "vector_postprocessor_name_tri", "A triple-indexed vector of VectorPostprocessorName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<OutputName>>>>(
      "output_name_tri", "A triple-indexed vector of OutputName.");
  params.addRequiredParam<std::vector<std::vector<std::vector<MaterialPropertyName>>>>(
      "material_property_name_tri", "A triple-indexed vector of MaterialPropertyName.");
  return params;
}

ReadTripleIndex::ReadTripleIndex(const InputParameters & params)
  : GeneralUserObject(params),
    _real_tri(getParam<std::vector<std::vector<std::vector<Real>>>>("real_tri")),
    _uint_tri(getParam<std::vector<std::vector<std::vector<unsigned int>>>>("uint_tri")),
    _int_tri(getParam<std::vector<std::vector<std::vector<int>>>>("int_tri")),
    _long_tri(getParam<std::vector<std::vector<std::vector<long>>>>("long_tri")),
    _subid_tri(getParam<std::vector<std::vector<std::vector<SubdomainID>>>>("subid_tri")),
    _bid_tri(getParam<std::vector<std::vector<std::vector<BoundaryID>>>>("bid_tri")),
    _str_tri(getParam<std::vector<std::vector<std::vector<std::string>>>>("str_tri")),
    _file_tri(getParam<std::vector<std::vector<std::vector<FileName>>>>("file_tri")),
    _file_no_tri(
        getParam<std::vector<std::vector<std::vector<FileNameNoExtension>>>>("file_no_tri")),
    _mesh_file_tri(getParam<std::vector<std::vector<std::vector<MeshFileName>>>>("mesh_file_tri")),
    _subdomain_name_tri(
        getParam<std::vector<std::vector<std::vector<SubdomainName>>>>("subdomain_name_tri")),
    _boundary_name_tri(
        getParam<std::vector<std::vector<std::vector<BoundaryName>>>>("boundary_name_tri")),
    _function_name_tri(
        getParam<std::vector<std::vector<std::vector<FunctionName>>>>("function_name_tri")),
    _userobject_name_tri(
        getParam<std::vector<std::vector<std::vector<UserObjectName>>>>("userobject_name_tri")),
    _indicator_name_tri(
        getParam<std::vector<std::vector<std::vector<IndicatorName>>>>("indicator_name_tri")),
    _marker_name_tri(
        getParam<std::vector<std::vector<std::vector<MarkerName>>>>("marker_name_tri")),
    _multiapp_name_tri(
        getParam<std::vector<std::vector<std::vector<MultiAppName>>>>("multiapp_name_tri")),
    _postprocessor_name_tri(getParam<std::vector<std::vector<std::vector<PostprocessorName>>>>(
        "postprocessor_name_tri")),
    _vector_postprocessor_name_tri(
        getParam<std::vector<std::vector<std::vector<VectorPostprocessorName>>>>(
            "vector_postprocessor_name_tri")),
    _output_name_tri(
        getParam<std::vector<std::vector<std::vector<OutputName>>>>("output_name_tri")),
    _material_property_name_tri(
        getParam<std::vector<std::vector<std::vector<MaterialPropertyName>>>>(
            "material_property_name_tri"))
{
  const std::vector<std::vector<std::vector<Real>>> reference_values = {
      {{1.1}, {2.1, 2.2, 2.3}, {3.1, 3.2}},
      {{11.1, 11.2}},
      {{21.1, 21.2}, {22.1}, {23.1, 23.2, 23.3}}};

  // check real
  TripleIndexNumberVectorChecker(_real_tri, "real_tri", reference_values);

  // check unsigned int
  TripleIndexNumberVectorChecker(_uint_tri, "uint_tri", reference_values, false, false, 10.0);

  // check int
  TripleIndexNumberVectorChecker(_int_tri, "int_tri", reference_values, true, true, 10.0);

  // check long
  TripleIndexNumberVectorChecker(_long_tri, "long_tri", reference_values, true, false, 10.0);

  // check SubdomainID
  TripleIndexNumberVectorChecker(
      _subid_tri, "subid_tri", reference_values, false, false, 10.0, 30.0);

  // check BoundaryID
  TripleIndexNumberVectorChecker(_bid_tri, "bid_tri", reference_values, false, false, 10.0, 35.0);

  // check std::string
  TripleIndexStringVectorChecker(_str_tri, "str_tri", "string", reference_values);

  // check FileName
  TripleIndexStringVectorChecker(_file_tri, "file_tri", "file", reference_values);

  // check FileNameNoExtension
  TripleIndexStringVectorChecker(_file_no_tri, "file_no_tri", "file_no", reference_values);

  // check MeshFileName
  TripleIndexStringVectorChecker(_mesh_file_tri, "mesh_file_tri", "mesh_file", reference_values);

  // check SubdomainName
  TripleIndexStringVectorChecker(
      _subdomain_name_tri, "subdomain_name_tri", "subdomain_name", reference_values);

  // check BoundaryName
  TripleIndexStringVectorChecker(
      _boundary_name_tri, "boundary_name_tri", "boundary_name", reference_values);

  // check FunctionName
  TripleIndexStringVectorChecker(
      _function_name_tri, "function_name_tri", "function_name", reference_values);

  // check UserObjectName
  TripleIndexStringVectorChecker(
      _userobject_name_tri, "userobject_name_tri", "userobject_name", reference_values);

  // check IndicatorName
  TripleIndexStringVectorChecker(
      _indicator_name_tri, "indicator_name_tri", "indicator_name", reference_values);

  // check MarkerName
  TripleIndexStringVectorChecker(
      _marker_name_tri, "marker_name_tri", "marker_name", reference_values);

  // check MultiAppName
  TripleIndexStringVectorChecker(
      _multiapp_name_tri, "multiapp_name_tri", "multiapp_name", reference_values);

  // check PostprocessorName
  TripleIndexStringVectorChecker(
      _postprocessor_name_tri, "postprocessor_name_tri", "postprocessor_name", reference_values);

  // check VectorPostprocessorName
  TripleIndexStringVectorChecker(_vector_postprocessor_name_tri,
                                 "vector_postprocessor_name_tri",
                                 "vector_postprocessor_name",
                                 reference_values);

  // check OutputName
  TripleIndexStringVectorChecker(
      _output_name_tri, "output_name_tri", "output_name", reference_values);

  // check MaterialPropertyName
  TripleIndexStringVectorChecker(_material_property_name_tri,
                                 "material_property_name_tri",
                                 "material_property_name",
                                 reference_values);
}

template <typename T>
void
ReadTripleIndex::TripleIndexNumberVectorChecker(
    const std::vector<std::vector<std::vector<T>>> triple_index_vector,
    const std::string vector_name,
    const std::vector<std::vector<std::vector<Real>>> reference_values,
    const bool index_flip,
    const bool flip_direction,
    const Real scale_factor,
    const Real offset_value)
{
  if (triple_index_vector.size() != reference_values.size())
    mooseError("Error reading ", vector_name, ".");
  for (unsigned int i = 0; i < triple_index_vector.size(); i++)
  {
    if (triple_index_vector[i].size() != reference_values[i].size())
      mooseError("Error reading ", vector_name, ".");
    for (unsigned int j = 0; j < triple_index_vector[i].size(); j++)
    {
      if (triple_index_vector[i][j].size() != reference_values[i][j].size())
        mooseError("Error reading ", vector_name, ".");
      for (unsigned int k = 0; k < triple_index_vector[i][j].size(); k++)
        if (triple_index_vector[i][j][k] !=
            static_cast<T>((reference_values[i][j][k] * scale_factor + offset_value) *
                           (index_flip
                                ? (flip_direction ? ((i % 2 ? 1.0 : -1.0) * (j % 2 ? 1.0 : -1.0))
                                                  : ((i % 2 ? 1.0 : -1.0) * (j % 2 ? -1.0 : 1.0)))
                                : 1.0)))
          mooseError("Error reading ", vector_name, ".");
    }
  }
}

template <typename T>
void
ReadTripleIndex::TripleIndexStringVectorChecker(
    const T triple_index_vector,
    const std::string vector_name,
    const std::string prefix,
    const std::vector<std::vector<std::vector<Real>>> reference_values)
{
  if (triple_index_vector.size() != reference_values.size())
    mooseError("Error reading ", vector_name, ".");
  for (unsigned int i = 0; i < triple_index_vector.size(); i++)
  {
    if (triple_index_vector[i].size() != reference_values[i].size())
      mooseError("Error reading ", vector_name, ".");
    for (unsigned int j = 0; j < triple_index_vector[i].size(); j++)
    {
      if (triple_index_vector[i][j].size() != reference_values[i][j].size())
        mooseError("Error reading ", vector_name, ".");
      for (unsigned int k = 0; k < triple_index_vector[i][j].size(); k++)
      {
        std::stringstream ss;
        ss << prefix << i << j << k;
        if (triple_index_vector[i][j][k] != ss.str())
          mooseError("Error reading ", vector_name, ".");
      }
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Delete empty Serializer.cpp.<commit_after><|endoftext|>


<commit_before><commit_msg>Types test #250<commit_after><|endoftext|>


<commit_before>/*++
Copyright (c) 2014 Microsoft Corporation

Module Name:

    inc_sat_solver.cpp

Abstract:

    incremental solver based on SAT core.

Author:

    Nikolaj Bjorner (nbjorner) 2014-7-30

Notes:

--*/

#include "solver.h"
#include "tactical.h"
#include "sat_solver.h"
#include "tactic2solver.h"
#include "nnf_tactic.h"
#include "aig_tactic.h"
#include "propagate_values_tactic.h"
#include "max_bv_sharing_tactic.h"
#include "card2bv_tactic.h"
#include "bit_blaster_tactic.h"
#include "simplify_tactic.h"
#include "goal2sat.h"
#include "ast_pp.h"

// incremental SAT solver.
class inc_sat_solver : public solver {
    ast_manager&    m;
    sat::solver     m_solver;
    goal2sat        m_goal2sat;
    params_ref      m_params;
    expr_ref_vector m_fmls;
    expr_ref_vector m_core;
    atom2bool_var   m_map;
    model_ref       m_model;
    model_converter_ref m_mc;
    tactic_ref      m_preprocess;
    unsigned        m_num_scopes;
    sat::literal_vector m_asms;
    goal_ref_buffer     m_subgoals;
    proof_converter_ref m_pc;
    model_converter_ref m_mc2;
    expr_dependency_ref m_dep_core;

    typedef obj_map<expr, sat::literal> dep2asm_t;
public:
    inc_sat_solver(ast_manager& m, params_ref const& p):
        m(m), m_solver(p,0), m_params(p),
        m_fmls(m), m_core(m), m_map(m),
        m_num_scopes(0),
        m_dep_core(m) {
        m_params.set_bool("elim_vars", false);
        m_solver.updt_params(m_params);
        params_ref simp2_p = p;
        simp2_p.set_bool("som", true);
        simp2_p.set_bool("pull_cheap_ite", true);
        simp2_p.set_bool("push_ite_bv", false);
        simp2_p.set_bool("local_ctx", true);
        simp2_p.set_uint("local_ctx_limit", 10000000);
        simp2_p.set_bool("flat", true); // required by som
        simp2_p.set_bool("hoist_mul", false); // required by som
        m_preprocess =
            and_then(mk_card2bv_tactic(m, m_params),
                     mk_simplify_tactic(m),
                     mk_propagate_values_tactic(m),
                     using_params(mk_simplify_tactic(m), simp2_p),
                     mk_max_bv_sharing_tactic(m),
                     mk_bit_blaster_tactic(m),
                     mk_aig_tactic(),
                     using_params(mk_simplify_tactic(m), simp2_p));

    }

    virtual ~inc_sat_solver() {}

    virtual void set_progress_callback(progress_callback * callback) {
    }
    virtual lbool check_sat(unsigned num_assumptions, expr * const * assumptions) {
        m_solver.pop_to_base_level();
        dep2asm_t dep2asm;

        m_model = 0;
        lbool r = internalize_formulas();
        if (r != l_true) return r;
        r = internalize_assumptions(num_assumptions, assumptions, dep2asm);
        if (r != l_true) return r;
        extract_assumptions(dep2asm, m_asms);
        r = m_solver.check(m_asms.size(), m_asms.c_ptr());
        switch (r) {
        case l_true:
            check_assumptions(dep2asm);
            break;
        case l_false:
            // TBD: expr_dependency core is not accounted for.
            if (num_assumptions > 0) {
                extract_core(dep2asm);
            }
            break;
        default:
            break;
        }
        return r;
    }
    virtual void set_cancel(bool f) {
        m_goal2sat.set_cancel(f);
        m_solver.set_cancel(f);
        m_preprocess->set_cancel(f);
    }
    virtual void push() {
        m_solver.user_push();
        ++m_num_scopes;
    }
    virtual void pop(unsigned n) {
        if (n < m_num_scopes) {   // allow inc_sat_solver to
            n = m_num_scopes;     // take over for another solver.
        }
        SASSERT(n >= m_num_scopes);
        m_solver.user_pop(n);
        m_num_scopes -= n;
    }
    virtual unsigned get_scope_level() const {
        return m_num_scopes;
    }
    virtual void assert_expr(expr * t, expr * a) {
        if (a) {
            m_fmls.push_back(m.mk_implies(a, t));
        }
        else {
            m_fmls.push_back(t);
        }
    }
    virtual void assert_expr(expr * t) {
        m_fmls.push_back(t);
    }
    virtual void set_produce_models(bool f) {}
    virtual void collect_param_descrs(param_descrs & r) {
        goal2sat::collect_param_descrs(r);
        sat::solver::collect_param_descrs(r);
    }
    virtual void updt_params(params_ref const & p) {
        m_params = p;
        m_params.set_bool("elim_vars", false);
        m_solver.updt_params(m_params);
    }

    virtual void collect_statistics(statistics & st) const {
        m_preprocess->collect_statistics(st);
        m_solver.collect_statistics(st);
    }
    virtual void get_unsat_core(ptr_vector<expr> & r) {
        r.reset();
        r.append(m_core.size(), m_core.c_ptr());
    }
    virtual void get_model(model_ref & m) {
        if (!m_model.get()) {
            extract_model();
        }
        m = m_model;
    }
    virtual proof * get_proof() {
        UNREACHABLE();
        return 0;
    }
    virtual std::string reason_unknown() const {
        return "no reason given";
    }
    virtual void get_labels(svector<symbol> & r) {
        UNREACHABLE();
    }

private:

    lbool internalize_goal(goal_ref& g, dep2asm_t& dep2asm) {
        m_mc2.reset();
        m_pc.reset();
        m_dep_core.reset();
        m_subgoals.reset();
        SASSERT(g->models_enabled());
        SASSERT(!g->proofs_enabled());
        TRACE("opt", g->display(tout););
        try {
            (*m_preprocess)(g, m_subgoals, m_mc2, m_pc, m_dep_core);
        }
        catch (tactic_exception & ex) {
            IF_VERBOSE(0, verbose_stream() << "exception in tactic " << ex.msg() << "\n";);
            return l_undef;
        }
        m_mc = concat(m_mc.get(), m_mc2.get());
        if (m_subgoals.size() != 1) {
            IF_VERBOSE(0, verbose_stream() << "size of subgoals is not 1, it is: " << m_subgoals.size() << "\n";);
            return l_undef;
        }
        g = m_subgoals[0];
        TRACE("opt", g->display_with_dependencies(tout););
        m_goal2sat(*g, m_params, m_solver, m_map, dep2asm, true);
        return l_true;
    }

    lbool internalize_assumptions(unsigned sz, expr* const* asms, dep2asm_t& dep2asm) {
        if (sz == 0) {
            return l_true;
        }
        goal_ref g = alloc(goal, m, true, true); // models and cores are enabled.
        for (unsigned i = 0; i < sz; ++i) {
            g->assert_expr(asms[i], m.mk_leaf(asms[i]));
        }
        return internalize_goal(g, dep2asm);
    }

    lbool internalize_formulas() {
        if (m_fmls.empty()) {
            return l_true;
        }
        dep2asm_t dep2asm;
        goal_ref g = alloc(goal, m, true, false); // models, maybe cores are enabled
        for (unsigned i = 0; i < m_fmls.size(); ++i) {
            g->assert_expr(m_fmls[i].get());
        }
        m_fmls.reset();
        return internalize_goal(g, dep2asm);
    }

    void extract_assumptions(dep2asm_t& dep2asm, sat::literal_vector& asms) {
        asms.reset();
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            asms.push_back(it->m_value);
        }
    }

    void extract_core(dep2asm_t& dep2asm) {
        u_map<expr*> asm2dep;
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            asm2dep.insert(it->m_value.index(), it->m_key);
        }
        sat::literal_vector const& core = m_solver.get_core();

        m_core.reset();
        for (unsigned i = 0; i < core.size(); ++i) {
            expr* e;
            if (asm2dep.find(core[i].index(), e)) {
                if (core[i].sign()) {
                    e = m.mk_not(e);
                }
                m_core.push_back(e);
            }
        }
        TRACE("opt",
              dep2asm_t::iterator it = dep2asm.begin();
              dep2asm_t::iterator end = dep2asm.end();
              for (; it != end; ++it) {
                  tout << mk_pp(it->m_key, m) << " |-> " << it->m_value << "\n";
              }
              tout << "core: ";
              for (unsigned i = 0; i < core.size(); ++i) {
                  tout << core[i] << ": " << mk_pp(m_core[i].get(), m) << " ";
              }
              tout << "\n";
              );

    }

    void check_assumptions(dep2asm_t& dep2asm) {
        sat::model const & ll_m = m_solver.get_model();
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            sat::literal lit = it->m_value;
            lbool polarity = lit.sign()?l_false:l_true;
            lbool value = sat::value_at(lit.var(), ll_m);
            if (value != polarity) {
                IF_VERBOSE(0, verbose_stream() << mk_pp(it->m_key, m) << " evaluates to " << value << "\n";
                           verbose_stream() << m_asms << "\n";
                           m_solver.display_assignment(verbose_stream());
                           m_solver.display(verbose_stream()););
                throw default_exception("bad state");
            }
        }
    }

    // TBD: this is super-expensive because of the
    // bit-blasting model converter.

    void extract_model() {
        TRACE("sat", tout << "retrieve model\n";);
        model_ref md = alloc(model, m);
        sat::model const & ll_m = m_solver.get_model();
        atom2bool_var::iterator it  = m_map.begin();
        atom2bool_var::iterator end = m_map.end();
        for (; it != end; ++it) {
            expr * n   = it->m_key;
            if (is_app(n) && to_app(n)->get_num_args() > 0) {
                continue;
            }
            sat::bool_var v = it->m_value;
            switch (sat::value_at(v, ll_m)) {
            case l_true:
                md->register_decl(to_app(n)->get_decl(), m.mk_true());
                break;
            case l_false:
                md->register_decl(to_app(n)->get_decl(), m.mk_false());
                break;
            default:
                break;
            }
        }
        m_model = md;
        if (m_mc) {
            (*m_mc)(m_model);
        }
        SASSERT(m_model);
        // IF_VERBOSE(0, model_smt2_pp(verbose_stream(), m, *(m_model.get()), 0););

    }
};

solver* mk_inc_sat_solver(ast_manager& m, params_ref& p) {
    return alloc(inc_sat_solver, m, p);
}
<commit_msg>add missing code<commit_after>/*++
Copyright (c) 2014 Microsoft Corporation

Module Name:

    inc_sat_solver.cpp

Abstract:

    incremental solver based on SAT core.

Author:

    Nikolaj Bjorner (nbjorner) 2014-7-30

Notes:

--*/

#include "solver.h"
#include "tactical.h"
#include "sat_solver.h"
#include "tactic2solver.h"
#include "nnf_tactic.h"
#include "aig_tactic.h"
#include "propagate_values_tactic.h"
#include "max_bv_sharing_tactic.h"
#include "card2bv_tactic.h"
#include "bit_blaster_tactic.h"
#include "simplify_tactic.h"
#include "goal2sat.h"
#include "ast_pp.h"

// incremental SAT solver.
class inc_sat_solver : public solver {
    ast_manager&    m;
    sat::solver     m_solver;
    goal2sat        m_goal2sat;
    params_ref      m_params;
    expr_ref_vector m_fmls;
    expr_ref_vector m_current_fmls;
    unsigned_vector m_fmls_lim;
    expr_ref_vector m_core;
    atom2bool_var   m_map;
    model_ref       m_model;
    model_converter_ref m_mc;
    tactic_ref      m_preprocess;
    unsigned        m_num_scopes;
    sat::literal_vector m_asms;
    goal_ref_buffer     m_subgoals;
    proof_converter_ref m_pc;
    model_converter_ref m_mc2;
    expr_dependency_ref m_dep_core;

    typedef obj_map<expr, sat::literal> dep2asm_t;
public:
    inc_sat_solver(ast_manager& m, params_ref const& p):
        m(m), m_solver(p,0), m_params(p),
        m_fmls(m), m_current_fmls(m), m_core(m), m_map(m),
        m_num_scopes(0),
        m_dep_core(m) {
        m_params.set_bool("elim_vars", false);
        m_solver.updt_params(m_params);
        params_ref simp2_p = p;
        simp2_p.set_bool("som", true);
        simp2_p.set_bool("pull_cheap_ite", true);
        simp2_p.set_bool("push_ite_bv", false);
        simp2_p.set_bool("local_ctx", true);
        simp2_p.set_uint("local_ctx_limit", 10000000);
        simp2_p.set_bool("flat", true); // required by som
        simp2_p.set_bool("hoist_mul", false); // required by som
        m_preprocess =
            and_then(mk_card2bv_tactic(m, m_params),
                     mk_simplify_tactic(m),
                     mk_propagate_values_tactic(m),
                     using_params(mk_simplify_tactic(m), simp2_p),
                     mk_max_bv_sharing_tactic(m),
                     mk_bit_blaster_tactic(m),
                     mk_aig_tactic(),
                     using_params(mk_simplify_tactic(m), simp2_p));

    }

    virtual ~inc_sat_solver() {}

    virtual void set_progress_callback(progress_callback * callback) {
    }
    virtual lbool check_sat(unsigned num_assumptions, expr * const * assumptions) {
        m_solver.pop_to_base_level();
        dep2asm_t dep2asm;

        m_model = 0;
        lbool r = internalize_formulas();
        if (r != l_true) return r;
        r = internalize_assumptions(num_assumptions, assumptions, dep2asm);
        if (r != l_true) return r;
        extract_assumptions(dep2asm, m_asms);
        r = m_solver.check(m_asms.size(), m_asms.c_ptr());
        switch (r) {
        case l_true:
            check_assumptions(dep2asm);
            break;
        case l_false:
            // TBD: expr_dependency core is not accounted for.
            if (num_assumptions > 0) {
                extract_core(dep2asm);
            }
            break;
        default:
            break;
        }
        return r;
    }
    virtual void set_cancel(bool f) {
        m_goal2sat.set_cancel(f);
        m_solver.set_cancel(f);
        m_preprocess->set_cancel(f);
    }
    virtual void push() {
        m_solver.user_push();
        ++m_num_scopes;
        m_fmls_lim.push_back(m_current_fmls.size());
    }
    virtual void pop(unsigned n) {
        if (n < m_num_scopes) {   // allow inc_sat_solver to
            n = m_num_scopes;     // take over for another solver.
        }
        SASSERT(n >= m_num_scopes);
        m_solver.user_pop(n);
        m_num_scopes -= n;
        while (n > 0) {
            m_current_fmls.resize(m_fmls_lim.back());
            m_fmls_lim.pop_back();
            --n;
        }
    }
    virtual unsigned get_scope_level() const {
        return m_num_scopes;
    }
    virtual void assert_expr(expr * t, expr * a) {
        if (a) {
            assert_expr(m.mk_implies(a, t));
        }
        else {
            assert_expr(t);
        }
    }
    virtual void assert_expr(expr * t) {
        m_fmls.push_back(t);
        m_current_fmls.push_back(t);
    }
    virtual void set_produce_models(bool f) {}
    virtual void collect_param_descrs(param_descrs & r) {
        goal2sat::collect_param_descrs(r);
        sat::solver::collect_param_descrs(r);
    }
    virtual void updt_params(params_ref const & p) {
        m_params = p;
        m_params.set_bool("elim_vars", false);
        m_solver.updt_params(m_params);
    }

    virtual void collect_statistics(statistics & st) const {
        m_preprocess->collect_statistics(st);
        m_solver.collect_statistics(st);
    }
    virtual void get_unsat_core(ptr_vector<expr> & r) {
        r.reset();
        r.append(m_core.size(), m_core.c_ptr());
    }
    virtual void get_model(model_ref & m) {
        if (!m_model.get()) {
            extract_model();
        }
        m = m_model;
    }
    virtual proof * get_proof() {
        UNREACHABLE();
        return 0;
    }
    virtual std::string reason_unknown() const {
        return "no reason given";
    }
    virtual void get_labels(svector<symbol> & r) {
        UNREACHABLE();
    }

    virtual unsigned get_num_assertions() const {
        return m_fmls.size();
    }

    virtual expr * get_assertion(unsigned idx) const {
        return m_fmls[idx];
    }

private:

    lbool internalize_goal(goal_ref& g, dep2asm_t& dep2asm) {
        m_mc2.reset();
        m_pc.reset();
        m_dep_core.reset();
        m_subgoals.reset();
        SASSERT(g->models_enabled());
        SASSERT(!g->proofs_enabled());
        TRACE("opt", g->display(tout););
        try {
            (*m_preprocess)(g, m_subgoals, m_mc2, m_pc, m_dep_core);
        }
        catch (tactic_exception & ex) {
            IF_VERBOSE(0, verbose_stream() << "exception in tactic " << ex.msg() << "\n";);
            return l_undef;
        }
        m_mc = concat(m_mc.get(), m_mc2.get());
        if (m_subgoals.size() != 1) {
            IF_VERBOSE(0, verbose_stream() << "size of subgoals is not 1, it is: " << m_subgoals.size() << "\n";);
            return l_undef;
        }
        g = m_subgoals[0];
        TRACE("opt", g->display_with_dependencies(tout););
        m_goal2sat(*g, m_params, m_solver, m_map, dep2asm, true);
        return l_true;
    }

    lbool internalize_assumptions(unsigned sz, expr* const* asms, dep2asm_t& dep2asm) {
        if (sz == 0) {
            return l_true;
        }
        goal_ref g = alloc(goal, m, true, true); // models and cores are enabled.
        for (unsigned i = 0; i < sz; ++i) {
            g->assert_expr(asms[i], m.mk_leaf(asms[i]));
        }
        return internalize_goal(g, dep2asm);
    }

    lbool internalize_formulas() {
        if (m_fmls.empty()) {
            return l_true;
        }
        dep2asm_t dep2asm;
        goal_ref g = alloc(goal, m, true, false); // models, maybe cores are enabled
        for (unsigned i = 0; i < m_fmls.size(); ++i) {
            g->assert_expr(m_fmls[i].get());
        }
        m_fmls.reset();
        return internalize_goal(g, dep2asm);
    }

    void extract_assumptions(dep2asm_t& dep2asm, sat::literal_vector& asms) {
        asms.reset();
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            asms.push_back(it->m_value);
        }
    }

    void extract_core(dep2asm_t& dep2asm) {
        u_map<expr*> asm2dep;
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            asm2dep.insert(it->m_value.index(), it->m_key);
        }
        sat::literal_vector const& core = m_solver.get_core();

        m_core.reset();
        for (unsigned i = 0; i < core.size(); ++i) {
            expr* e;
            if (asm2dep.find(core[i].index(), e)) {
                if (core[i].sign()) {
                    e = m.mk_not(e);
                }
                m_core.push_back(e);
            }
        }
        TRACE("opt",
              dep2asm_t::iterator it = dep2asm.begin();
              dep2asm_t::iterator end = dep2asm.end();
              for (; it != end; ++it) {
                  tout << mk_pp(it->m_key, m) << " |-> " << it->m_value << "\n";
              }
              tout << "core: ";
              for (unsigned i = 0; i < core.size(); ++i) {
                  tout << core[i] << ": " << mk_pp(m_core[i].get(), m) << " ";
              }
              tout << "\n";
              );

    }

    void check_assumptions(dep2asm_t& dep2asm) {
        sat::model const & ll_m = m_solver.get_model();
        dep2asm_t::iterator it = dep2asm.begin(), end = dep2asm.end();
        for (; it != end; ++it) {
            sat::literal lit = it->m_value;
            lbool polarity = lit.sign()?l_false:l_true;
            lbool value = sat::value_at(lit.var(), ll_m);
            if (value != polarity) {
                IF_VERBOSE(0, verbose_stream() << mk_pp(it->m_key, m) << " evaluates to " << value << "\n";
                           verbose_stream() << m_asms << "\n";
                           m_solver.display_assignment(verbose_stream());
                           m_solver.display(verbose_stream()););
                throw default_exception("bad state");
            }
        }
    }

    // TBD: this is super-expensive because of the
    // bit-blasting model converter.

    void extract_model() {
        TRACE("sat", tout << "retrieve model\n";);
        model_ref md = alloc(model, m);
        sat::model const & ll_m = m_solver.get_model();
        atom2bool_var::iterator it  = m_map.begin();
        atom2bool_var::iterator end = m_map.end();
        for (; it != end; ++it) {
            expr * n   = it->m_key;
            if (is_app(n) && to_app(n)->get_num_args() > 0) {
                continue;
            }
            sat::bool_var v = it->m_value;
            switch (sat::value_at(v, ll_m)) {
            case l_true:
                md->register_decl(to_app(n)->get_decl(), m.mk_true());
                break;
            case l_false:
                md->register_decl(to_app(n)->get_decl(), m.mk_false());
                break;
            default:
                break;
            }
        }
        m_model = md;
        if (m_mc) {
            (*m_mc)(m_model);
        }
        SASSERT(m_model);
        // IF_VERBOSE(0, model_smt2_pp(verbose_stream(), m, *(m_model.get()), 0););

    }
};

solver* mk_inc_sat_solver(ast_manager& m, params_ref& p) {
    return alloc(inc_sat_solver, m, p);
}
<|endoftext|>