<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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.

#include "iceoryx_utils/platform/semaphore.hpp"
#include "iceoryx_utils/platform/time.hpp"

#include <chrono>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <thread>

iox_sem_t::iox_sem_t() noexcept
{
}

iox_sem_t::iox_sem_t(iox_sem_t&& rhs) noexcept
{
    *this = std::move(rhs);
}

iox_sem_t::~iox_sem_t()
{
}

iox_sem_t& iox_sem_t::operator=(iox_sem_t&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_value.store(rhs.m_value.load());
        m_handle = rhs.m_handle;
        m_hasPosixHandle = rhs.m_hasPosixHandle;
        m_value = rhs.m_value;

        rhs.m_value.store(0);
    }
    return *this;
}

int iox_sem_getvalue(iox_sem_t* sem, int* sval)
{
    *sval = sem->m_value.load(std::memory_order_relaxed);
    return 0;
}

int iox_sem_post(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_post(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_add(1, std::memory_order_relaxed);
        }
    }
    else
    {
        // dispatch semaphore always succeed
        dispatch_semaphore_signal(sem->m_handle.dispatch);
        sem->m_value.fetch_add(1, std::memory_order_relaxed);
    }
    return retVal;
}

int iox_sem_wait(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_wait(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }
    else
    {
        // dispatch semaphore always succeed
        dispatch_semaphore_wait(sem->m_handle.dispatch, DISPATCH_TIME_FOREVER);
        sem->m_value.fetch_sub(1, std::memory_order_relaxed);
    }

    return retVal;
}

int iox_sem_trywait(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_trywait(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }
    else
    {
        if (dispatch_semaphore_wait(sem->m_handle.dispatch, 0) != 0)
        {
            errno = EAGAIN;
            retVal = -1;
        }
        else
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }

    return retVal;
}

int iox_sem_timedwait(iox_sem_t* sem, const struct timespec* abs_timeout)
{
    struct timeval tv;
    gettimeofday(&tv, nullptr);

    static constexpr int64_t NANOSECONDS_PER_SECOND = 1000000000;
    static constexpr int64_t NANOSECONDS_PER_MICROSECOND = 1000;

    int64_t timeoutInNanoSeconds = std::max(0ll,
                                            (abs_timeout->tv_sec - tv.tv_sec) * NANOSECONDS_PER_SECOND
                                                + abs_timeout->tv_nsec - tv.tv_usec * NANOSECONDS_PER_MICROSECOND);

    if (sem->m_hasPosixHandle)
    {
        int tryWaitCall = sem_trywait(sem->m_handle.posix);
        if (tryWaitCall == -1 && errno != EAGAIN)
        {
            return -1;
        }
        else if (tryWaitCall == -1 && errno == EAGAIN && timeoutInNanoSeconds == 0)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else if (tryWaitCall == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(timeoutInNanoSeconds));

        tryWaitCall = sem_trywait(sem->m_handle.posix);
        if (tryWaitCall == -1 && errno == EAGAIN)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else if (tryWaitCall == -1 && errno != EAGAIN)
        {
            return -1;
        }
        else if (tryWaitCall == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }
    }
    else
    {
        dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds);
        if (dispatch_semaphore_wait(sem->m_handle.dispatch, timeout) != 0)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }
    }

    return -1;
}

int iox_sem_close(iox_sem_t* sem)
{
    // will only be called by named semaphores which are in our case
    // posix semaphores
    // therefor we have to call delete since we created the iox_sem_t object
    // with new in iox_sem_open
    int retVal = sem_close(sem->m_handle.posix);
    delete sem;
    return retVal;
}

int iox_sem_destroy(iox_sem_t* sem)
{
    // will only be called by unnamed semaphores which are in our
    // case dispatch semaphores
    dispatch_release(sem->m_handle.dispatch);
    // no delete necessary since the user is providing memory here
    return 0;
}

int iox_sem_init(iox_sem_t* sem, int, unsigned int value)
{
    // no new necessary since the user is providing memory here
    sem->m_hasPosixHandle = false;
    sem->m_handle.dispatch = dispatch_semaphore_create(value);
    sem->m_value.store(value, std::memory_order_relaxed);

    if (sem->m_handle.dispatch == nullptr)
    {
        return -1;
    }
    return 0;
}

int iox_sem_unlink(const char* name)
{
    return sem_unlink(name);
}

iox_sem_t* iox_sem_open_impl(const char* name, int oflag, ...)
{
    if (strlen(name) == 0 || name[0] == 0)
    {
        return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
    }

    // sem_open creates a named semaphore which is corresponding to a file.
    // the posix version creates also something on the heap and if you would
    // like to share this semaphore you should open the named semaphore with
    // sem_open in another process. Sharing this semaphore via shared memory
    // is always wrong!
    // Hence, it is allowed to use new/delete in this case.
    iox_sem_t* sem = new iox_sem_t;

    if (oflag & (O_CREAT | O_EXCL))
    {
        va_list va;
        va_start(va, oflag);
        // mode_t is an alias for unsigned short but this causes undefined
        // behavior in va_arg since it is a promotable type - which will be
        // promoted to int
        mode_t mode = static_cast<mode_t>(va_arg(va, unsigned int));
        unsigned int value = va_arg(va, unsigned int);
        va_end(va);

        sem->m_handle.posix = sem_open(name, oflag, mode, value);
        sem->m_value.store(value, std::memory_order_relaxed);
    }
    else
    {
        sem->m_handle.posix = sem_open(name, oflag);
    }

    if (sem->m_handle.posix == SEM_FAILED)
    {
        delete sem;
        return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
    }

    return sem;
}
<commit_msg>iox-#204 removed atomic copy in move operations<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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.

#include "iceoryx_utils/platform/semaphore.hpp"
#include "iceoryx_utils/platform/time.hpp"

#include <chrono>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <thread>

iox_sem_t::iox_sem_t() noexcept
{
}

iox_sem_t::iox_sem_t(iox_sem_t&& rhs) noexcept
{
    *this = std::move(rhs);
}

iox_sem_t::~iox_sem_t()
{
}

iox_sem_t& iox_sem_t::operator=(iox_sem_t&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_value.store(rhs.m_value.load());
        m_handle = rhs.m_handle;
        m_hasPosixHandle = rhs.m_hasPosixHandle;

        rhs.m_value.store(0);
    }
    return *this;
}

int iox_sem_getvalue(iox_sem_t* sem, int* sval)
{
    *sval = sem->m_value.load(std::memory_order_relaxed);
    return 0;
}

int iox_sem_post(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_post(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_add(1, std::memory_order_relaxed);
        }
    }
    else
    {
        // dispatch semaphore always succeed
        dispatch_semaphore_signal(sem->m_handle.dispatch);
        sem->m_value.fetch_add(1, std::memory_order_relaxed);
    }
    return retVal;
}

int iox_sem_wait(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_wait(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }
    else
    {
        // dispatch semaphore always succeed
        dispatch_semaphore_wait(sem->m_handle.dispatch, DISPATCH_TIME_FOREVER);
        sem->m_value.fetch_sub(1, std::memory_order_relaxed);
    }

    return retVal;
}

int iox_sem_trywait(iox_sem_t* sem)
{
    int retVal{0};
    if (sem->m_hasPosixHandle)
    {
        retVal = sem_trywait(sem->m_handle.posix);
        if (retVal == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }
    else
    {
        if (dispatch_semaphore_wait(sem->m_handle.dispatch, 0) != 0)
        {
            errno = EAGAIN;
            retVal = -1;
        }
        else
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
        }
    }

    return retVal;
}

int iox_sem_timedwait(iox_sem_t* sem, const struct timespec* abs_timeout)
{
    struct timeval tv;
    gettimeofday(&tv, nullptr);

    static constexpr int64_t NANOSECONDS_PER_SECOND = 1000000000;
    static constexpr int64_t NANOSECONDS_PER_MICROSECOND = 1000;

    int64_t timeoutInNanoSeconds = std::max(0ll,
                                            (abs_timeout->tv_sec - tv.tv_sec) * NANOSECONDS_PER_SECOND
                                                + abs_timeout->tv_nsec - tv.tv_usec * NANOSECONDS_PER_MICROSECOND);

    if (sem->m_hasPosixHandle)
    {
        int tryWaitCall = sem_trywait(sem->m_handle.posix);
        if (tryWaitCall == -1 && errno != EAGAIN)
        {
            return -1;
        }
        else if (tryWaitCall == -1 && errno == EAGAIN && timeoutInNanoSeconds == 0)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else if (tryWaitCall == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(timeoutInNanoSeconds));

        tryWaitCall = sem_trywait(sem->m_handle.posix);
        if (tryWaitCall == -1 && errno == EAGAIN)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else if (tryWaitCall == -1 && errno != EAGAIN)
        {
            return -1;
        }
        else if (tryWaitCall == 0)
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }
    }
    else
    {
        dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds);
        if (dispatch_semaphore_wait(sem->m_handle.dispatch, timeout) != 0)
        {
            errno = ETIMEDOUT;
            return -1;
        }
        else
        {
            sem->m_value.fetch_sub(1, std::memory_order_relaxed);
            return 0;
        }
    }

    return -1;
}

int iox_sem_close(iox_sem_t* sem)
{
    // will only be called by named semaphores which are in our case
    // posix semaphores
    // therefor we have to call delete since we created the iox_sem_t object
    // with new in iox_sem_open
    int retVal = sem_close(sem->m_handle.posix);
    delete sem;
    return retVal;
}

int iox_sem_destroy(iox_sem_t* sem)
{
    // will only be called by unnamed semaphores which are in our
    // case dispatch semaphores
    dispatch_release(sem->m_handle.dispatch);
    // no delete necessary since the user is providing memory here
    return 0;
}

int iox_sem_init(iox_sem_t* sem, int, unsigned int value)
{
    // no new necessary since the user is providing memory here
    sem->m_hasPosixHandle = false;
    sem->m_handle.dispatch = dispatch_semaphore_create(value);
    sem->m_value.store(value, std::memory_order_relaxed);

    if (sem->m_handle.dispatch == nullptr)
    {
        return -1;
    }
    return 0;
}

int iox_sem_unlink(const char* name)
{
    return sem_unlink(name);
}

iox_sem_t* iox_sem_open_impl(const char* name, int oflag, ...)
{
    if (strlen(name) == 0 || name[0] == 0)
    {
        return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
    }

    // sem_open creates a named semaphore which is corresponding to a file.
    // the posix version creates also something on the heap and if you would
    // like to share this semaphore you should open the named semaphore with
    // sem_open in another process. Sharing this semaphore via shared memory
    // is always wrong!
    // Hence, it is allowed to use new/delete in this case.
    iox_sem_t* sem = new iox_sem_t;

    if (oflag & (O_CREAT | O_EXCL))
    {
        va_list va;
        va_start(va, oflag);
        // mode_t is an alias for unsigned short but this causes undefined
        // behavior in va_arg since it is a promotable type - which will be
        // promoted to int
        mode_t mode = static_cast<mode_t>(va_arg(va, unsigned int));
        unsigned int value = va_arg(va, unsigned int);
        va_end(va);

        sem->m_handle.posix = sem_open(name, oflag, mode, value);
        sem->m_value.store(value, std::memory_order_relaxed);
    }
    else
    {
        sem->m_handle.posix = sem_open(name, oflag);
    }

    if (sem->m_handle.posix == SEM_FAILED)
    {
        delete sem;
        return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
    }

    return sem;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_EDITOR_EDITOR_ENTITY_HPP
#define RJ_GAME_EDITOR_EDITOR_ENTITY_HPP

#include <rectojump/game/entity_rect.hpp>
#include <rectojump/global/config_settings.hpp>

namespace rj
{
	class editor_entity final : public entity_rect
	{
		entity_figure m_figure;

	public:
		editor_entity(const vec2f& pos) :
			entity_rect{pos, m_size, {0.f, 0.f}}
		{
			m_render_object.setOrigin(m_size / 2.f);
			m_render_object.setOutlineThickness(2.f);
			m_render_object.setOutlineColor(settings::get_color_dark());
			m_render_object.setFillColor(settings::get_color_dark());
		}

		void update(dur)
		{ }

		void set_figure(entity_figure f) noexcept
		{m_figure = f;}

		void set_texture(const sf::Texture* tx)
		{m_render_object.setTexture(tx);}

		entity_figure get_figure() const noexcept
		{return m_figure;}
	};
}

#endif // RJ_GAME_EDITOR_EDITOR_ENTITY_HPP
<commit_msg>editor_entity: added get_texture()<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_EDITOR_EDITOR_ENTITY_HPP
#define RJ_GAME_EDITOR_EDITOR_ENTITY_HPP

#include <rectojump/game/entity_rect.hpp>
#include <rectojump/global/config_settings.hpp>

namespace rj
{
	class editor_entity final : public entity_rect
	{
		entity_figure m_figure;

	public:
		editor_entity(const vec2f& pos) :
			entity_rect{pos, m_size, {0.f, 0.f}}
		{
			m_render_object.setOrigin(m_size / 2.f);
			m_render_object.setOutlineThickness(2.f);
			m_render_object.setOutlineColor(settings::get_color_dark());
			m_render_object.setFillColor(settings::get_color_dark());
		}

		void update(dur)
		{ }

		void set_figure(entity_figure f) noexcept
		{m_figure = f;}

		void set_texture(const sf::Texture* tx)
		{m_render_object.setTexture(tx);}

		const sf::Texture* get_texture() const noexcept
		{return m_render_object.getTexture();}

		entity_figure get_figure() const noexcept
		{return m_figure;}
	};
}

#endif // RJ_GAME_EDITOR_EDITOR_ENTITY_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/api/frame_subscriber.h"

#include "base/bind.h"
#include "atom/common/node_includes.h"
#include "ui/gfx/screen.h"

#include "content/public/browser/render_widget_host.h"

namespace atom {

namespace api {

FrameSubscriber::FrameSubscriber(v8::Isolate* isolate,
                                 content::RenderWidgetHostView* view,
                                 const FrameCaptureCallback& callback)
    : isolate_(isolate), view_(view), callback_(callback), weak_factory_(this) {
}

bool FrameSubscriber::ShouldCaptureFrame(
    const gfx::Rect& damage_rect,
    base::TimeTicks present_time,
    scoped_refptr<media::VideoFrame>* storage,
    DeliverFrameCallback* callback) {
  const auto host = view_ ? view_->GetRenderWidgetHost() : nullptr;
  if (!view_ || !host)
    return false;

  const auto size = view_->GetVisibleViewportSize();

  host->CopyFromBackingStore(
      gfx::Rect(size),
      size,
      base::Bind(&FrameSubscriber::OnFrameDelivered,
                 weak_factory_.GetWeakPtr(), callback_),
      kBGRA_8888_SkColorType);

  return false;
}

void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
  const SkBitmap& bitmap, content::ReadbackResponse response) {
  if (bitmap.computeSize64() == 0)
    return;

  v8::Locker locker(isolate_);
  v8::HandleScope handle_scope(isolate_);

  size_t rgb_arr_size = bitmap.width() * bitmap.height() *
    bitmap.bytesPerPixel();
  v8::MaybeLocal<v8::Object> buffer = node::Buffer::New(isolate_, rgb_arr_size);
  if (buffer.IsEmpty())
    return;

  bitmap.copyPixelsTo(
    reinterpret_cast<uint8*>(node::Buffer::Data(buffer.ToLocalChecked())),
    rgb_arr_size);

  callback_.Run(buffer.ToLocalChecked());
}

}  // namespace api

}  // namespace atom
<commit_msg>Removed an include no longer needed<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/api/frame_subscriber.h"

#include "base/bind.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/render_widget_host.h"

namespace atom {

namespace api {

FrameSubscriber::FrameSubscriber(v8::Isolate* isolate,
                                 content::RenderWidgetHostView* view,
                                 const FrameCaptureCallback& callback)
    : isolate_(isolate), view_(view), callback_(callback), weak_factory_(this) {
}

bool FrameSubscriber::ShouldCaptureFrame(
    const gfx::Rect& damage_rect,
    base::TimeTicks present_time,
    scoped_refptr<media::VideoFrame>* storage,
    DeliverFrameCallback* callback) {
  const auto host = view_ ? view_->GetRenderWidgetHost() : nullptr;
  if (!view_ || !host)
    return false;

  const auto size = view_->GetVisibleViewportSize();

  host->CopyFromBackingStore(
      gfx::Rect(size),
      size,
      base::Bind(&FrameSubscriber::OnFrameDelivered,
                 weak_factory_.GetWeakPtr(), callback_),
      kBGRA_8888_SkColorType);

  return false;
}

void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
  const SkBitmap& bitmap, content::ReadbackResponse response) {
  if (bitmap.computeSize64() == 0)
    return;

  v8::Locker locker(isolate_);
  v8::HandleScope handle_scope(isolate_);

  size_t rgb_arr_size = bitmap.width() * bitmap.height() *
    bitmap.bytesPerPixel();
  v8::MaybeLocal<v8::Object> buffer = node::Buffer::New(isolate_, rgb_arr_size);
  if (buffer.IsEmpty())
    return;

  bitmap.copyPixelsTo(
    reinterpret_cast<uint8*>(node::Buffer::Data(buffer.ToLocalChecked())),
    rgb_arr_size);

  callback_.Run(buffer.ToLocalChecked());
}

}  // namespace api

}  // namespace atom
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b2dpolygon.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-18 11:02:46 $
 *
 *  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 _BGFX_POLYGON_B2DPOLYGON_HXX
#define _BGFX_POLYGON_B2DPOLYGON_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX
#include <o3tl/cow_wrapper.hxx>
#endif

#ifndef _BGFX_VECTOR_B2ENUMS_HXX
#include <basegfx/vector/b2enums.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations
class ImplB2DPolygon;

namespace basegfx
{
    class B2DPolygon;
    class B2DPoint;
    class B2DVector;
    class B2DHomMatrix;
} // end of namespace basegfx

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

namespace basegfx
{
    class B2DPolygon
    {
    public:
        typedef o3tl::cow_wrapper< ImplB2DPolygon > ImplType;

    private:
        // internal data.
        ImplType                                    mpPolygon;

    public:
        B2DPolygon();
        B2DPolygon(const B2DPolygon& rPolygon);
        B2DPolygon(const B2DPolygon& rPolygon, sal_uInt32 nIndex, sal_uInt32 nCount);
        ~B2DPolygon();

        // assignment operator
        B2DPolygon& operator=(const B2DPolygon& rPolygon);

        /// unshare this polygon with all internally shared instances
        void makeUnique();

        // compare operators
        bool operator==(const B2DPolygon& rPolygon) const;
        bool operator!=(const B2DPolygon& rPolygon) const;

        // member count
        sal_uInt32 count() const;

        // Coordinate interface
        basegfx::B2DPoint getB2DPoint(sal_uInt32 nIndex) const;
        void setB2DPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);

        // Coordinate insert/append
        void insert(sal_uInt32 nIndex, const basegfx::B2DPoint& rPoint, sal_uInt32 nCount = 1);
        void append(const basegfx::B2DPoint& rPoint, sal_uInt32 nCount = 1);

        // ControlPoint interface
        basegfx::B2DPoint getPrevControlPoint(sal_uInt32 nIndex) const;
        basegfx::B2DPoint getNextControlPoint(sal_uInt32 nIndex) const;
        void setPrevControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);
        void setNextControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);
        void setControlPoints(sal_uInt32 nIndex, const basegfx::B2DPoint& rPrev, const basegfx::B2DPoint& rNext);

        // ControlPoint resets
        void resetPrevControlPoint(sal_uInt32 nIndex);
        void resetNextControlPoint(sal_uInt32 nIndex);
        void resetControlPoints(sal_uInt32 nIndex);
        void resetControlPoints();

        // Bezier segment append with control points. The currently last
        // polygon point is implicitly taken as start point.
        void appendBezierSegment(const basegfx::B2DPoint& rNextControlPoint, const basegfx::B2DPoint& rPrevControlPoint, const basegfx::B2DPoint& rPoint);

        // ControlPoint checks
        bool areControlPointsUsed() const;
        bool isPrevControlPointUsed(sal_uInt32 nIndex) const;
        bool isNextControlPointUsed(sal_uInt32 nIndex) const;
        B2VectorContinuity getContinuityInPoint(sal_uInt32 nIndex) const;

        // insert/append other 2D polygons
        void insert(sal_uInt32 nIndex, const B2DPolygon& rPoly, sal_uInt32 nIndex2 = 0, sal_uInt32 nCount = 0);
        void append(const B2DPolygon& rPoly, sal_uInt32 nIndex = 0, sal_uInt32 nCount = 0);

        // remove
        void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1);

        // clear all points
        void clear();

        // closed state
        bool isClosed() const;
        void setClosed(bool bNew);

        // flip polygon direction
        void flip();

        // test if Polygon has double points
        bool hasDoublePoints() const;

        // remove double points, at the begin/end and follow-ups, too
        void removeDoublePoints();

        // apply transformation given in matrix form to the polygon
        void transform(const basegfx::B2DHomMatrix& rMatrix);
    };
} // end of namespace basegfx

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

#endif /* _BGFX_POLYGON_B2DPOLYGON_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.12.32); FILE MERGED 2008/04/01 15:01:08 thb 1.12.32.3: #i85898# Stripping all external header guards 2008/04/01 10:48:08 thb 1.12.32.2: #i85898# Stripping all external header guards 2008/03/28 16:05:40 rt 1.12.32.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: b2dpolygon.hxx,v $
 * $Revision: 1.13 $
 *
 * 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 _BGFX_POLYGON_B2DPOLYGON_HXX
#define _BGFX_POLYGON_B2DPOLYGON_HXX

#include <sal/types.h>
#include <o3tl/cow_wrapper.hxx>
#include <basegfx/vector/b2enums.hxx>

//////////////////////////////////////////////////////////////////////////////
// predeclarations
class ImplB2DPolygon;

namespace basegfx
{
    class B2DPolygon;
    class B2DPoint;
    class B2DVector;
    class B2DHomMatrix;
} // end of namespace basegfx

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

namespace basegfx
{
    class B2DPolygon
    {
    public:
        typedef o3tl::cow_wrapper< ImplB2DPolygon > ImplType;

    private:
        // internal data.
        ImplType                                    mpPolygon;

    public:
        B2DPolygon();
        B2DPolygon(const B2DPolygon& rPolygon);
        B2DPolygon(const B2DPolygon& rPolygon, sal_uInt32 nIndex, sal_uInt32 nCount);
        ~B2DPolygon();

        // assignment operator
        B2DPolygon& operator=(const B2DPolygon& rPolygon);

        /// unshare this polygon with all internally shared instances
        void makeUnique();

        // compare operators
        bool operator==(const B2DPolygon& rPolygon) const;
        bool operator!=(const B2DPolygon& rPolygon) const;

        // member count
        sal_uInt32 count() const;

        // Coordinate interface
        basegfx::B2DPoint getB2DPoint(sal_uInt32 nIndex) const;
        void setB2DPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);

        // Coordinate insert/append
        void insert(sal_uInt32 nIndex, const basegfx::B2DPoint& rPoint, sal_uInt32 nCount = 1);
        void append(const basegfx::B2DPoint& rPoint, sal_uInt32 nCount = 1);

        // ControlPoint interface
        basegfx::B2DPoint getPrevControlPoint(sal_uInt32 nIndex) const;
        basegfx::B2DPoint getNextControlPoint(sal_uInt32 nIndex) const;
        void setPrevControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);
        void setNextControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue);
        void setControlPoints(sal_uInt32 nIndex, const basegfx::B2DPoint& rPrev, const basegfx::B2DPoint& rNext);

        // ControlPoint resets
        void resetPrevControlPoint(sal_uInt32 nIndex);
        void resetNextControlPoint(sal_uInt32 nIndex);
        void resetControlPoints(sal_uInt32 nIndex);
        void resetControlPoints();

        // Bezier segment append with control points. The currently last
        // polygon point is implicitly taken as start point.
        void appendBezierSegment(const basegfx::B2DPoint& rNextControlPoint, const basegfx::B2DPoint& rPrevControlPoint, const basegfx::B2DPoint& rPoint);

        // ControlPoint checks
        bool areControlPointsUsed() const;
        bool isPrevControlPointUsed(sal_uInt32 nIndex) const;
        bool isNextControlPointUsed(sal_uInt32 nIndex) const;
        B2VectorContinuity getContinuityInPoint(sal_uInt32 nIndex) const;

        // insert/append other 2D polygons
        void insert(sal_uInt32 nIndex, const B2DPolygon& rPoly, sal_uInt32 nIndex2 = 0, sal_uInt32 nCount = 0);
        void append(const B2DPolygon& rPoly, sal_uInt32 nIndex = 0, sal_uInt32 nCount = 0);

        // remove
        void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1);

        // clear all points
        void clear();

        // closed state
        bool isClosed() const;
        void setClosed(bool bNew);

        // flip polygon direction
        void flip();

        // test if Polygon has double points
        bool hasDoublePoints() const;

        // remove double points, at the begin/end and follow-ups, too
        void removeDoublePoints();

        // apply transformation given in matrix form to the polygon
        void transform(const basegfx::B2DHomMatrix& rMatrix);
    };
} // end of namespace basegfx

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

#endif /* _BGFX_POLYGON_B2DPOLYGON_HXX */
<|endoftext|>


<commit_before>#include <algorithm>
#include <cstdlib>
#include <functional>
#include <ios>
#include <iostream>
#include <vector>
#include <valarray>
#include <utility>

// Vector

template<typename value_type>
struct Vector : public std::vector<value_type> {
  static const value_type EPS;

  value_type
  operator[](size_t i) const {
    if (i < this->size()) {
      return std::vector<value_type>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  value_type &
  operator[](size_t i) {
    if (i < this->size()) {
      return std::vector<value_type>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Vector(const std::vector<value_type> &value)
  {
    std::vector<value_type>::operator=(value);
  };

  Vector() = default;

  Vector(Vector<value_type> &&) = default; // Move constructor
  Vector(const Vector<value_type> &) = default; // Copy constructor

  Vector<value_type> &
  operator=(Vector<value_type> &&) = default; // Move operator

  Vector<value_type> &
  operator=(const Vector<value_type> &) = default; // Copy operator

  Vector(const std::initializer_list<value_type> &elems)
  {
    for (auto elem : elems) {
      this->push_back(elem);
    }
  }

  static value_type
  dot(const Vector &a, const Vector &b) {
    if (a.size() != b.size()) {
      throw std::runtime_error("Mismatch vector length for dot product");
    } else {
      value_type result = 0;
      for (size_t i = 0; i < a.size(); ++ i) {
        result += a[i] * b[i];
      }
      return result;
    }
  }

  static int
  compare(const Vector &a, const Vector &b) {
    for (size_t i = 0; i < a.size() && i < b.size(); ++ i) {
      if (a[i] - b[i] > Vector::EPS) {
        return 1;
      } else if (a[i] - b[i] < -Vector::EPS) {
        return -1;
      }
    }

    if (a.size() < b.size()) {
      return -1;
    } else if (a.size() > b.size()) {
      return 1;
    } else {
      return 0;
    }
  }
};

template<>
const double Vector<double>::EPS = 1e-6;

template<typename value_type>
bool
operator==(const Vector<value_type> &a, const Vector<value_type> &b)
{
  return Vector<value_type>::compare(a, b) == 0;
}

template<typename value_type>
bool
operator!=(const Vector<value_type> &a, const Vector<value_type> &b)
{
  return Vector<value_type>::compare(a, b) != 0;
}

// Matrix

template<typename value_type>
struct Matrix : public std::vector<Vector<value_type>>
{
  const static value_type EPS;

  const size_t rows;
  const size_t cols;

  Matrix(size_t _rows, size_t _cols) :
    rows(_rows),
    cols(_cols)
  {
    this->resize(rows);
    for (auto &row : *this) {
      row.resize(cols);

      for (auto &elem : row) {
        elem = 0;
      }
    }
  }

  Matrix(const Matrix<value_type> &other) = default; // Copy constructor

  Matrix(Matrix<value_type> &&) = default; // Move constructor

  Matrix(const std::initializer_list<Vector<value_type>> &elems) :
    rows(elems.size()),
    cols(elems.begin() != elems.end() ? elems.begin()->size() : 0)
  {
    for (const auto &elem : elems) {
      this->push_back(elem);
    }

    if (std::any_of(this->begin(), this->end(), [this](const Vector<value_type> &row){ return row.size() != this->cols; })) {
      throw std::runtime_error("Rows with wrong elem count");
    }
  }

  Matrix<value_type> &
  operator=(const Matrix<value_type> &other) // Copy operator
  {
    const_cast<size_t &>(rows) = other.rows;
    const_cast<size_t &>(cols) = other.cols;

    std::vector<Vector<value_type>>::operator=(other);

    return *this;
  }

  Matrix<value_type> &
  operator=(Matrix<value_type> &&) = default; // Move operator

  const Vector<value_type> &
  operator[](size_t i) const {
    if (i < this->size()) {
      return std::vector<Vector<value_type>>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Vector<value_type> &
  operator[](size_t i) {
    if (i < this->size()) {
      return std::vector<Vector<value_type>>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Matrix<value_type> &
  operator*=(value_type b) {
    for (auto &row : *this) {
      for (auto &e : row) {
        e *= b;
      }
    }
    return *this;
  };

};

template<typename value_type>
Vector<value_type>
operator*(const Matrix<value_type> &A, const Vector<value_type> &b)
{
  auto result = Vector<value_type>();

  for (const auto &row : A) {
    result.push_back(Vector<value_type>::dot(row, b));
  }

  return result;
};

template<typename value_type>
Matrix<value_type>
operator*(const Matrix<value_type> &A, value_type b)
{
  Matrix<value_type> result = A;
  result = A;
  result *= b;
  return result;
}

// Tests

void check(bool value)
{
  if (!value) {
    std::cerr << "error" << std::endl;
    exit(EXIT_FAILURE);
  } else {
    std::cout << ".";
  }
}

using Block = std::function<void ()>;

void
raises(const Block &block) {
  bool raises = false;
  try {
    block();
  } catch(const std::runtime_error &) {
    raises = true;
  }
  check(raises);
}

void
check_size()
{
  std::cout << "check_size";

  Matrix<double> m(3, 4);

  check(m.rows == 3);
  check(m.cols == 4);

  std::cout << "OK" << std::endl;
}

void
check_init()
{
  std::cout << "check_init";

  Matrix<double> m(3, 4);

  check(m.rows == 3);
  check(m.cols == 4);

  for (size_t i = 0; i < m.rows; ++ i) {
    for (size_t j = 0; j < m.cols; ++ j) {
      check(fabs(m[i][j]) <= Vector<double>::EPS);
    }
  }

  m = {{1, 2}, {3, 4}};

  check(m.rows == 2);
  check(m.cols == 2);

  check(fabs(m[0][0] - 1) <= Vector<double>::EPS);
  check(fabs(m[0][1] - 2) <= Vector<double>::EPS);
  check(fabs(m[1][0] - 3) <= Vector<double>::EPS);
  check(fabs(m[1][1] - 4) <= Vector<double>::EPS);

  raises([]{ Matrix<double>({{1, 2}, {3}}); });

  std::cout << "OK" << std::endl;
}

void
check_get_set()
{
  std::cout << "check_get_set";

  Matrix<double> m(2, 3);
  m[0][0] = 1;
  m[0][1] = 2;
  m[0][2] = 3;
  m[1][0] = 4;
  m[1][1] = 5;
  m[1][2] = 6;

  check(fabs(m[0][0] - 1) <= Vector<double>::EPS);
  check(fabs(m[0][1] - 2) <= Vector<double>::EPS);
  check(fabs(m[0][2] - 3) <= Vector<double>::EPS);
  check(fabs(m[1][0] - 4) <= Vector<double>::EPS);
  check(fabs(m[1][1] - 5) <= Vector<double>::EPS);
  check(fabs(m[1][2] - 6) <= Vector<double>::EPS);

  m[1][2] = 100;

  check(fabs(m[1][2] - 100) <= Vector<double>::EPS);

  std::cout << "OK" << std::endl;
}

void
check_raises()
{
  std::cout << "check_raises";

  Matrix<double> m(2, 3);

  raises([&m]{ m[-1][0]; });
  raises([&m]{ m[3][0]; });
  raises([&m]{ m[0][-1]; });
  raises([&m]{ m[0][3]; });

  raises([&m]{ m[-1][0] = 10; });
  raises([&m]{ m[3][0] = 10; });
  raises([&m]{ m[0][-1] = 10; });
  raises([&m]{ m[0][3] = 10; });

  std::cout << "OK" << std::endl;
}

void
check_equal()
{
  std::cout << "check_equal";

  Matrix<double> m1(2, 3), m2(2, 3), m3(4, 4);

  // Empty matrix
  check(m1 == m2);
  check(!(m1 != m2));

  check(!(m1 == m3));
  check(m1 != m3);

  // Uniq matrix
  m1[1][0] = 10;
  check(!(m1 == m2));
  check(m1 != m2);

  check(!(m1 == m3));
  check(m1 != m3);

  // Not uniq matrix
  m2[1][0] = 10;
  check(m1 == m2);
  check(!(m1 != m2));

  check(!(m1 == m3));
  check(m1 != m3);

  std::cout << "OK" << std::endl;
}

void
check_multiply()
{
  std::cout << "check_multiply";

  Matrix<double> m = {{1, 2},
              {3, 4},
              {5, 6}};
  Vector<double> v = {1, 2};

  check(m * v == Vector<double>({5, 11, 17}));

  check(m * 2.0 == Matrix<double>({{2, 4},
                                 {6, 8},
                                 {10, 12}}));

  check(m == Matrix<double>({{1, 2},
                             {3, 4},
                             {5, 6}}));
  m *= 2;
  check(m == Matrix<double>({{2, 4},
                             {6, 8},
                             {10, 12}}));

  std::cout << "OK" << std::endl;
}

// Main

int
main()
{
  std::ios::sync_with_stdio(false);

  check_size();
  check_init();
  check_get_set();
  check_raises();
  check_equal();
  check_multiply();

  return 0;
}
<commit_msg>Add comments<commit_after>#include <algorithm>
#include <cstdlib>
#include <functional>
#include <ios>
#include <iostream>
#include <vector>
#include <valarray>
#include <utility>

// Vector

template<typename value_type>
struct Vector : public std::vector<value_type> {
  static const value_type EPS; // For accurate float comparation

  value_type
  operator[](size_t i) const
  {
    if (i < this->size()) {
      return std::vector<value_type>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  value_type &
  operator[](size_t i)
  {
    if (i < this->size()) {
      return std::vector<value_type>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Vector(const std::vector<value_type> &value)
  {
    std::vector<value_type>::operator=(value);
  };

  Vector() = default;

  Vector(Vector<value_type> &&) = default; // Move constructor
  Vector(const Vector<value_type> &) = default; // Copy constructor

  Vector<value_type> &
  operator=(Vector<value_type> &&) = default; // Move operator

  Vector<value_type> &
  operator=(const Vector<value_type> &) = default; // Copy operator

  Vector(const std::initializer_list<value_type> &elems)
  {
    for (auto elem : elems) {
      this->push_back(elem);
    }
  }

  static value_type
  dot(const Vector &a, const Vector &b) // Скалярное произведение Векторов
  {
    if (a.size() != b.size()) {
      throw std::runtime_error("Mismatch vector length for dot product");
    } else {
      value_type result = 0;
      for (size_t i = 0; i < a.size(); ++ i) {
        result += a[i] * b[i];
      }
      return result;
    }
  }

  static int
  compare(const Vector &a, const Vector &b) // Оператор сравнения Векторов
  {
    for (size_t i = 0; i < a.size() && i < b.size(); ++ i) {
      if (a[i] - b[i] > Vector::EPS) {
        return 1;
      } else if (a[i] - b[i] < -Vector::EPS) {
        return -1;
      }
    }

    if (a.size() < b.size()) {
      return -1;
    } else if (a.size() > b.size()) {
      return 1;
    } else {
      return 0;
    }
  }
};

template<>
const double Vector<double>::EPS = 1e-6;

template<typename value_type>
bool
operator==(const Vector<value_type> &a, const Vector<value_type> &b)
{
  return Vector<value_type>::compare(a, b) == 0;
}

template<typename value_type>
bool
operator!=(const Vector<value_type> &a, const Vector<value_type> &b)
{
  return Vector<value_type>::compare(a, b) != 0;
}

// Matrix

template<typename value_type>
struct Matrix : public std::vector<Vector<value_type>>
{
  const static value_type EPS;

  const size_t rows;
  const size_t cols;

  Matrix(size_t _rows, size_t _cols) :
    rows(_rows),
    cols(_cols)
  {
    this->resize(rows);
    for (auto &row : *this) {
      row.resize(cols);

      for (auto &elem : row) {
        elem = 0;
      }
    }
  }

  Matrix(const Matrix<value_type> &other) = default; // Copy constructor

  Matrix(Matrix<value_type> &&) = default; // Move constructor

  Matrix(const std::initializer_list<Vector<value_type>> &elems) :
    rows(elems.size()),
    cols(elems.begin() != elems.end() ? elems.begin()->size() : 0)
  {
    for (const auto &elem : elems) {
      this->push_back(elem);
    }

    if (std::any_of(this->begin(), this->end(),
                    [this](const Vector<value_type> &row){ return row.size() != this->cols; })) {
      throw std::runtime_error("Rows with wrong elem count");
    }
  }

  Matrix<value_type> &
  operator=(const Matrix<value_type> &other) // Copy operator
  {
    const_cast<size_t &>(rows) = other.rows;
    const_cast<size_t &>(cols) = other.cols;

    std::vector<Vector<value_type>>::operator=(other);

    return *this;
  }

  Matrix<value_type> &
  operator=(Matrix<value_type> &&) = default; // Move operator

  const Vector<value_type> &
  operator[](size_t i) const
  {
    if (i < this->size()) {
      return std::vector<Vector<value_type>>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Vector<value_type> &
  operator[](size_t i)
  {
    if (i < this->size()) {
      return std::vector<Vector<value_type>>::operator[](i);
    } else {
      throw std::runtime_error("Incorrect index");
    }
  }

  Matrix<value_type> &
  operator*=(value_type b)
  {
    for (auto &row : *this) {
      for (auto &e : row) {
        e *= b;
      }
    }
    return *this;
  };

};

template<typename value_type>
Vector<value_type>
operator*(const Matrix<value_type> &A, const Vector<value_type> &b) // <== Оператор умножения
{
  auto result = Vector<value_type>();

  for (const auto &row : A) {
    result.push_back(Vector<value_type>::dot(row, b));
  }

  return result;
};

template<typename value_type>
Matrix<value_type>
operator*(const Matrix<value_type> &A, value_type b) // <== Еще один оператор умножения
{
  Matrix<value_type> result = A;
  result = A;
  result *= b;
  return result;
}

// Tests

void check(bool value)
{
  if (!value) {
    std::cerr << "error" << std::endl;
    exit(EXIT_FAILURE);
  } else {
    std::cout << ".";
  }
}

using Block = std::function<void ()>;

void
raises(const Block &block)
{
  bool raises = false;
  try {
    block();
  } catch(const std::runtime_error &) {
    raises = true;
  }
  check(raises);
}

void
check_size()
{
  std::cout << "check_size";

  Matrix<double> m(3, 4);

  check(m.rows == 3);
  check(m.cols == 4);

  std::cout << "OK" << std::endl;
}

void
check_init()
{
  std::cout << "check_init";

  Matrix<double> m(3, 4);

  check(m.rows == 3);
  check(m.cols == 4);

  for (size_t i = 0; i < m.rows; ++ i) {
    for (size_t j = 0; j < m.cols; ++ j) {
      check(fabs(m[i][j]) <= Vector<double>::EPS);
    }
  }

  m = {{1, 2}, {3, 4}};

  check(m.rows == 2);
  check(m.cols == 2);

  check(fabs(m[0][0] - 1) <= Vector<double>::EPS);
  check(fabs(m[0][1] - 2) <= Vector<double>::EPS);
  check(fabs(m[1][0] - 3) <= Vector<double>::EPS);
  check(fabs(m[1][1] - 4) <= Vector<double>::EPS);

  raises([]{ Matrix<double>({{1, 2}, {3}}); });

  std::cout << "OK" << std::endl;
}

void
check_get_set()
{
  std::cout << "check_get_set";

  Matrix<double> m(2, 3);
  m[0][0] = 1;
  m[0][1] = 2;
  m[0][2] = 3;
  m[1][0] = 4;
  m[1][1] = 5;
  m[1][2] = 6;

  check(fabs(m[0][0] - 1) <= Vector<double>::EPS);
  check(fabs(m[0][1] - 2) <= Vector<double>::EPS);
  check(fabs(m[0][2] - 3) <= Vector<double>::EPS);
  check(fabs(m[1][0] - 4) <= Vector<double>::EPS);
  check(fabs(m[1][1] - 5) <= Vector<double>::EPS);
  check(fabs(m[1][2] - 6) <= Vector<double>::EPS);

  m[1][2] = 100;

  check(fabs(m[1][2] - 100) <= Vector<double>::EPS);

  std::cout << "OK" << std::endl;
}

void
check_raises()
{
  std::cout << "check_raises";

  Matrix<double> m(2, 3);

  raises([&m]{ m[-1][0]; });
  raises([&m]{ m[3][0]; });
  raises([&m]{ m[0][-1]; });
  raises([&m]{ m[0][3]; });

  raises([&m]{ m[-1][0] = 10; });
  raises([&m]{ m[3][0] = 10; });
  raises([&m]{ m[0][-1] = 10; });
  raises([&m]{ m[0][3] = 10; });

  std::cout << "OK" << std::endl;
}

void
check_equal()
{
  std::cout << "check_equal";

  Matrix<double> m1(2, 3), m2(2, 3), m3(4, 4);

  // Empty matrix
  check(m1 == m2);
  check(!(m1 != m2));

  check(!(m1 == m3));
  check(m1 != m3);

  // Uniq matrix
  m1[1][0] = 10;
  check(!(m1 == m2));
  check(m1 != m2);

  check(!(m1 == m3));
  check(m1 != m3);

  // Not uniq matrix
  m2[1][0] = 10;
  check(m1 == m2);
  check(!(m1 != m2));

  check(!(m1 == m3));
  check(m1 != m3);

  std::cout << "OK" << std::endl;
}

void
check_multiply()
{
  std::cout << "check_multiply";

  Matrix<double> m = {{1, 2},
              {3, 4},
              {5, 6}};
  Vector<double> v = {1, 2};

  check(m * v == Vector<double>({5, 11, 17}));

  check(m * 2.0 == Matrix<double>({{2, 4},
                                 {6, 8},
                                 {10, 12}}));

  check(m == Matrix<double>({{1, 2},
                             {3, 4},
                             {5, 6}}));
  m *= 2;
  check(m == Matrix<double>({{2, 4},
                             {6, 8},
                             {10, 12}}));

  std::cout << "OK" << std::endl;
}

// Main

int
main()
{
  std::ios::sync_with_stdio(false);

  check_size();
  check_init();
  check_get_set();
  check_raises();
  check_equal();
  check_multiply();

  return 0;
}
<|endoftext|>


<commit_before>#include "../test_optimizer.hpp"
#include "../test_sgd.hpp"
#include "nnlib/math/math.hpp"
#include "nnlib/math/random.hpp"
#include "nnlib/nn/linear.hpp"
#include "nnlib/opt/sgd.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestClassImpl(SGD)
{
    Linear<T> model(2, 3);
    NNRunAbstractTest(Optimizer, SGD, new SGD<T>(model));

    NNTestMethod(momentum)
    {
        NNTestParams(T)
        {
            Linear<T> model(1, 1);
            model.params().fill(1);
            SGD<T> opt(model);
            opt.momentum(0.5);
            NNTestAlmostEquals(opt.momentum(), 0.5, 1e-12);
        }
    }
}
<commit_msg>Better SGD test.<commit_after>#include "../test_optimizer.hpp"
#include "../test_sgd.hpp"
#include "nnlib/math/math.hpp"
#include "nnlib/math/random.hpp"
#include "nnlib/nn/linear.hpp"
#include "nnlib/opt/sgd.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestClassImpl(SGD)
{
    Linear<T> model(2, 3);
    NNRunAbstractTest(Optimizer, SGD, new SGD<T>(model));

    NNTestMethod(momentum)
    {
        NNTestParams(T)
        {
            Linear<T> model(1, 1, false);
            model.params().copy({ 1 });

            SGD<T> opt(model);
            opt.learningRate(0.25);
            opt.momentum(0.5);
            NNTestAlmostEquals(opt.momentum(), 0.5, 1e-12);

            Tensor<T> inputs = { 1 };
            Tensor<T> target = { 0 };

            opt.step(inputs, target);
            NNTestAlmostEquals(opt.params()(0), 0.25, 1e-12);

            opt.step(inputs, target);
            NNTestAlmostEquals(opt.params()(0), -0.0625, 1e-12);
        }
    }

    NNTestMethod(step)
    {
        NNTestParams(const Tensor &, const Tensor &)
        {
            Linear<T> model(1, 1, false);
            model.params().copy({ 1 });

            SGD<T> opt(model);
            opt.learningRate(0.25);
            opt.momentum(0);

            Tensor<T> inputs = { 1 };
            Tensor<T> target = { 0 };

            opt.step(inputs, target);
            NNTestAlmostEquals(opt.params()(0), 0.5, 1e-12);

            opt.step(inputs, target);
            NNTestAlmostEquals(opt.params()(0), 0.25, 1e-12);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * File:   vjudge.cpp
 * Author: 51isoft
 *
 * Created on 2014年1月31日, 下午3:41
 */

#include "vjudge.h"
#include "JudgerInfo.h"
#include "Bott.h"

#include "JudgerFactory.h"

/**
 * Start a virtual judger
 * @param arg   Should be a JudgerInfo, contains oj specific contents
 * @return NULL
 */
void * start_judger(void * arg) {
    JudgerInfo * judger_info = (JudgerInfo *) arg;
    VirtualJudger * judger = NULL;

    while (true) {
        try {
            judger = JudgerFactory::createJudger(judger_info);
            judger->run();
        } catch (Exception & e) {
            LOG((string)"Judger failed, reason: " + e.what(), judger_info->GetId());
        }
        if (judger) {
            delete judger;
            judger = NULL;
        }
        LOG("Trying to recreate a judger, wait 5 seconds first.", judger_info->GetId());
        sleep(5);
    }

    pthread_exit(NULL);
}

int main() {
    // boost io performance
    ios::sync_with_stdio(false);

    curl_global_init(CURL_GLOBAL_ALL);
    vector<JudgerInfo> judgers = CONFIG->GetJudger_info();
    for (vector<JudgerInfo>::iterator it = judgers.begin(); it != judgers.end(); ++it) {
        pthread_t thread_id;
        pthread_create(&thread_id, NULL, start_judger, (void *)(& (*it)));
    }

    // Infinite loop
    while (true) {
        sleep(100000);
    }

    curl_global_cleanup();
    return 0;
}

<commit_msg>fix memory leak<commit_after>/*
 * File:   vjudge.cpp
 * Author: 51isoft
 *
 * Created on 2014年1月31日, 下午3:41
 */

#include "vjudge.h"
#include "JudgerInfo.h"
#include "Bott.h"

#include "JudgerFactory.h"

/**
 * Start a virtual judger
 * @param arg   Should be a JudgerInfo, contains oj specific contents
 * @return NULL
 */
void * start_judger(void * arg) {
    JudgerInfo * judger_info = (JudgerInfo *) arg;
    VirtualJudger * judger = NULL;

    while (true) {
        try {
            judger = JudgerFactory::createJudger(judger_info);
            judger->run();
        } catch (Exception & e) {
            LOG((string)"Judger failed, reason: " + e.what(), judger_info->GetId());
        }
        if (judger) {
            delete judger;
            judger = NULL;
        }
        LOG("Trying to recreate a judger, wait 5 seconds first.", judger_info->GetId());
        sleep(5);
    }

    pthread_exit(NULL);
}

int main() {
    // boost io performance
    ios::sync_with_stdio(false);

    curl_global_init(CURL_GLOBAL_ALL);
    vector<JudgerInfo> judgers = CONFIG->GetJudger_info();
    for (vector<JudgerInfo>::iterator it = judgers.begin(); it != judgers.end(); ++it) {
        pthread_t thread_id;
        pthread_create(&thread_id, NULL, start_judger, (void *)(& (*it)));
        pthread_detach(thread_id);
    }

    // Infinite loop
    while (true) {
        sleep(100000);
    }

    curl_global_cleanup();
    return 0;
}

<|endoftext|>


<commit_before>#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
ADC_MODE(ADC_VCC);
//#include <ESP8266WiFiMulti.h>

//AWS
#include <sha256.h>
#include <Utils.h>
#include <AWSClient2.h>

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <MQTTClient.h>
#include <Countdown.h>

//AWS MQTT Websocket
#include <Client.h>
#include <AWSWebSocketClient.h>
#include <CircularByteBuffer.h>

#include <DHT.h>
#include <DHT_U.h>

#define AM2302_WIRE_BUS 4
#define DHTTYPE DHT22   // DHT 22  (AM2302)

#include "wifi_config.h"
#include "aws-iot-config.h"

//AWS IOT config, change these:
char wifi_ssid[]       = WIFI_SSID;
char wifi_password[]   = WIFI_PASSWORD;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;
const uint deepSleepInterval = 30 * 60* 1000000U;
const uint deepSleepIntervalOnError = 5 * 60* 1000000U;

//ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;

DHT dht(AM2302_WIRE_BUS, DHTTYPE);

//# of connections
long connection = 0;
float h = 0.0f;
float t = 0.0f;

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i=0; i<22; i+=1)
    cID[i]=(char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
  MQTT::Message &message = md.message;

  Serial.print("Message ");
  Serial.print(++arrivedcount);
  Serial.print(" arrived: qos ");
  Serial.print(message.qos);
  Serial.print(", retained ");
  Serial.print(message.retained);
  Serial.print(", dup ");
  Serial.print(message.dup);
  Serial.print(", packetid ");
  Serial.println(message.id);
  Serial.print("Payload ");
  char* msg = new char[message.payloadlen+1]();
  memcpy (msg,message.payload,message.payloadlen);
  Serial.println(msg);
  delete msg;
}

//connects to websocket layer and mqtt layer
bool connect () {

  if (client == NULL) {
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  } else {

    if (client->isConnected ()) {
      client->disconnect ();
    }
    delete client;
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  }

  //delay is not necessary... it just help us to get a "trustful" heap space value
  delay (1000);
  Serial.print (millis ());
  Serial.print (" - conn: ");
  Serial.print (++connection);
  Serial.print (" - (");
  Serial.print (ESP.getFreeHeap ());
  Serial.println (")");

  int rc = ipstack.connect(aws_endpoint, port);
  if (rc != 1)
  {
    Serial.println("error connection to the websocket server");
    return false;
  } else {
    Serial.println("websocket layer connected");
  }

  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
  char* clientID = generateClientID ();
  data.clientID.cstring = clientID;
  rc = client->connect(data);
  delete[] clientID;
  if (rc != 0)
  {
    Serial.print("error connection to MQTT server");
    Serial.println(rc);
    return false;
  }
  Serial.println("MQTT connected");
  return true;
}

//subscribe to a mqtt topic
void subscribe () {
  //subscript to a topic
  int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived);
  if (rc != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc);
    return;
  }
  Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
// void sendmessage () {
//     //send a message
//     MQTT::Message message;
//     char buf[100];
//     strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}");
//     message.qos = MQTT::QOS0;
//     message.retained = false;
//     message.dup = false;
//     message.payload = (void*)buf;
//     message.payloadlen = strlen(buf)+1;
//     int rc = client->publish(aws_topic, message);
// }
bool readWeatherData()
{
  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  if (isnan(h) || isnan(t))
  {
    return false;
  }
  return true;
}

void sendmessage () {
  //send a message
  MQTT::Message message;
  char buf[100];

  char strTemperature[8];
  char strRH[8];
  // if (isnan(h) || isnan(t)){
  //   Serial.println("Bad sample values. Quitting");
  //   return;
  // }

  Serial.println(h);
  Serial.println(t);

  dtostrf(t, 2, 2, strTemperature);
  dtostrf(h, 2, 2, strRH);

  double voltage = ESP.getVcc()/1000.0;

  //String messagebody = String( "{\"state\":{") + "\"temperature\":\"" + strTemperature + "\"" + ", \"humidity\":\"" + strRH + "\"" "}}"  ;
  String messagebody = String( "{\"state\":{") + "\"reported\":{" + "\"temperature\":\"" + t + "\"" + ", \"humidity\":\"" + h + "\"" + ", \"voltage\":\"" + voltage + "\"" "}}}";

  Serial.println(aws_topic);
  Serial.println(messagebody);

  strcpy(buf, messagebody.c_str());
  //strcpy(buf, "{\"state\":{\"reported\":{\"temperature\": false}, \"desired\":{\"on\": false}}}");
  message.qos = MQTT::QOS1;
  message.retained = true;
  message.dup = false;
  message.payload = (void*)buf;
  message.payloadlen = strlen(buf)+1;
  int rc = client->publish(aws_topic, message);
}

void setup() {
  Serial.begin (115200);
  WiFi.mode(WIFI_OFF);
  //WiFi.disconnect(true);

  //Warm up the DHT and sleep for it to be fully operational.
  //Needs about 2 seconds as per AM2302 datasheet
  dht.begin();
  delay (3000);

  Serial.setDebugOutput(1);

  //read the data from sensor
  if (!readWeatherData())
  {
    Serial.println("Bad sample values. Quitting");
    ESP.deepSleep(deepSleepIntervalOnError,WAKE_RF_DEFAULT);
    delay(1000);
  }

  //Setup Wifi
  WiFi.mode(WIFI_STA);
  WiFi.persistent(false);
  WiFi.setAutoReconnect(false);
  WiFi.begin(wifi_ssid, wifi_password);
  WiFi.printDiag(Serial);

  Serial.println ("connecting to wifi");
  int starttime = millis();
  while(WiFi.status() != WL_CONNECTED)
  {
    if (starttime + 15000 < millis() )
    {
      //Goto sleep
      WiFi.disconnect(true);
      ESP.deepSleep(deepSleepIntervalOnError,WAKE_RF_DEFAULT);
      delay(1000);
    }
    delay(500);
    Serial.print (".");
  }
  Serial.println ("\nconnected");

  //fill AWS parameters
  awsWSclient.setAWSRegion(aws_region);
  awsWSclient.setAWSDomain(aws_endpoint);
  awsWSclient.setAWSKeyID(aws_key);
  awsWSclient.setAWSSecretKey(aws_secret);
  awsWSclient.setUseSSL(true);

  // if (connect ()) {
  //   subscribe ();
  //   sendmessage ();
  // }
  connect ();
}

void loop() {
  //Check if connected
  if (awsWSclient.connected ())
  {
    sendmessage();
  }

  //Get Ready to sleep.
  {
    Serial.println("Going to sleep...");
    WiFi.disconnect(true);
    ESP.deepSleep(deepSleepInterval,WAKE_RF_DEFAULT);
    ///Need a delay after calling deepsleep
    delay(1000);
  }
}
<commit_msg>Increase deep sleep interval to 60 mins<commit_after>#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
ADC_MODE(ADC_VCC);
//#include <ESP8266WiFiMulti.h>

//AWS
#include <sha256.h>
#include <Utils.h>
#include <AWSClient2.h>

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <MQTTClient.h>
#include <Countdown.h>

//AWS MQTT Websocket
#include <Client.h>
#include <AWSWebSocketClient.h>
#include <CircularByteBuffer.h>

#include <DHT.h>
#include <DHT_U.h>

#define AM2302_WIRE_BUS 4
#define DHTTYPE DHT22   // DHT 22  (AM2302)

#include "wifi_config.h"
#include "aws-iot-config.h"

//AWS IOT config, change these:
char wifi_ssid[]       = WIFI_SSID;
char wifi_password[]   = WIFI_PASSWORD;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;
const uint deepSleepInterval = 60 * 60* 1000000U;
const uint deepSleepIntervalOnError = 5 * 60* 1000000U;

//ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;

DHT dht(AM2302_WIRE_BUS, DHTTYPE);

//# of connections
long connection = 0;
float h = 0.0f;
float t = 0.0f;

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i=0; i<22; i+=1)
    cID[i]=(char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
  MQTT::Message &message = md.message;

  Serial.print("Message ");
  Serial.print(++arrivedcount);
  Serial.print(" arrived: qos ");
  Serial.print(message.qos);
  Serial.print(", retained ");
  Serial.print(message.retained);
  Serial.print(", dup ");
  Serial.print(message.dup);
  Serial.print(", packetid ");
  Serial.println(message.id);
  Serial.print("Payload ");
  char* msg = new char[message.payloadlen+1]();
  memcpy (msg,message.payload,message.payloadlen);
  Serial.println(msg);
  delete msg;
}

//connects to websocket layer and mqtt layer
bool connect () {

  if (client == NULL) {
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  } else {

    if (client->isConnected ()) {
      client->disconnect ();
    }
    delete client;
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  }

  //delay is not necessary... it just help us to get a "trustful" heap space value
  delay (1000);
  Serial.print (millis ());
  Serial.print (" - conn: ");
  Serial.print (++connection);
  Serial.print (" - (");
  Serial.print (ESP.getFreeHeap ());
  Serial.println (")");

  int rc = ipstack.connect(aws_endpoint, port);
  if (rc != 1)
  {
    Serial.println("error connection to the websocket server");
    return false;
  } else {
    Serial.println("websocket layer connected");
  }

  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
  char* clientID = generateClientID ();
  data.clientID.cstring = clientID;
  rc = client->connect(data);
  delete[] clientID;
  if (rc != 0)
  {
    Serial.print("error connection to MQTT server");
    Serial.println(rc);
    return false;
  }
  Serial.println("MQTT connected");
  return true;
}

//subscribe to a mqtt topic
void subscribe () {
  //subscript to a topic
  int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived);
  if (rc != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc);
    return;
  }
  Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
// void sendmessage () {
//     //send a message
//     MQTT::Message message;
//     char buf[100];
//     strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}");
//     message.qos = MQTT::QOS0;
//     message.retained = false;
//     message.dup = false;
//     message.payload = (void*)buf;
//     message.payloadlen = strlen(buf)+1;
//     int rc = client->publish(aws_topic, message);
// }
bool readWeatherData()
{
  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  if (isnan(h) || isnan(t))
  {
    return false;
  }
  return true;
}

void sendmessage () {
  //send a message
  MQTT::Message message;
  char buf[100];

  char strTemperature[8];
  char strRH[8];
  // if (isnan(h) || isnan(t)){
  //   Serial.println("Bad sample values. Quitting");
  //   return;
  // }

  Serial.println(h);
  Serial.println(t);

  dtostrf(t, 2, 2, strTemperature);
  dtostrf(h, 2, 2, strRH);

  double voltage = ESP.getVcc()/1000.0;

  //String messagebody = String( "{\"state\":{") + "\"temperature\":\"" + strTemperature + "\"" + ", \"humidity\":\"" + strRH + "\"" "}}"  ;
  String messagebody = String( "{\"state\":{") + "\"reported\":{" + "\"temperature\":\"" + t + "\"" + ", \"humidity\":\"" + h + "\"" + ", \"voltage\":\"" + voltage + "\"" "}}}";

  Serial.println(aws_topic);
  Serial.println(messagebody);

  strcpy(buf, messagebody.c_str());
  //strcpy(buf, "{\"state\":{\"reported\":{\"temperature\": false}, \"desired\":{\"on\": false}}}");
  message.qos = MQTT::QOS1;
  message.retained = true;
  message.dup = false;
  message.payload = (void*)buf;
  message.payloadlen = strlen(buf)+1;
  int rc = client->publish(aws_topic, message);
}

void setup() {
  Serial.begin (115200);
  WiFi.mode(WIFI_OFF);
  //WiFi.disconnect(true);

  //Warm up the DHT and sleep for it to be fully operational.
  //Needs about 2 seconds as per AM2302 datasheet
  dht.begin();
  delay (3000);

  Serial.setDebugOutput(1);

  //read the data from sensor
  if (!readWeatherData())
  {
    Serial.println("Bad sample values. Quitting");
    ESP.deepSleep(deepSleepIntervalOnError,WAKE_RF_DEFAULT);
    delay(1000);
  }

  //Setup Wifi
  WiFi.mode(WIFI_STA);
  WiFi.persistent(false);
  WiFi.setAutoReconnect(false);
  WiFi.begin(wifi_ssid, wifi_password);
  WiFi.printDiag(Serial);

  Serial.println ("connecting to wifi");
  int starttime = millis();
  while(WiFi.status() != WL_CONNECTED)
  {
    if (starttime + 15000 < millis() )
    {
      //Goto sleep
      WiFi.disconnect(true);
      ESP.deepSleep(deepSleepIntervalOnError,WAKE_RF_DEFAULT);
      delay(1000);
    }
    delay(500);
    Serial.print (".");
  }
  Serial.println ("\nconnected");

  //fill AWS parameters
  awsWSclient.setAWSRegion(aws_region);
  awsWSclient.setAWSDomain(aws_endpoint);
  awsWSclient.setAWSKeyID(aws_key);
  awsWSclient.setAWSSecretKey(aws_secret);
  awsWSclient.setUseSSL(true);

  // if (connect ()) {
  //   subscribe ();
  //   sendmessage ();
  // }
  connect ();
}

void loop() {
  //Check if connected
  if (awsWSclient.connected ())
  {
    sendmessage();
  }

  //Get Ready to sleep.
  {
    Serial.println("Going to sleep...");
    WiFi.disconnect(true);
    ESP.deepSleep(deepSleepInterval,WAKE_RF_DEFAULT);
    ///Need a delay after calling deepsleep
    delay(1000);
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: instancelocker.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:48:26 $
 *
 *  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 __INSTANCELOCKER_HXX_
#define __INSTANCELOCKER_HXX_

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_
#include <com/sun/star/util/XCloseListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XACTIONSAPPROVAL_HPP_
#include <com/sun/star/embed/XActionsApproval.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ACTIONS_HPP_
#include <com/sun/star/embed/Actions.hpp>
#endif

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

class OLockListener;

// the service is implemented as a wrapper to be able to die by refcount
// the disposing mechanics is required for java related scenarios
class OInstanceLocker : public ::cppu::WeakImplHelper3< ::com::sun::star::lang::XComponent,
                                                        ::com::sun::star::lang::XInitialization,
                                                        ::com::sun::star::lang::XServiceInfo >
{
    ::osl::Mutex m_aMutex;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;

    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xLockListener;
    OLockListener* m_pLockListener;

    ::cppu::OInterfaceContainerHelper* m_pListenersContainer; // list of listeners

    sal_Bool m_bDisposed;
    sal_Bool m_bInitialized;

public:
    OInstanceLocker( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext );
    ~OInstanceLocker();

    static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
            impl_staticGetSupportedServiceNames();

    static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();

    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
        impl_staticCreateSelfInstance(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );

// XComponent
    virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

// XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

// XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

};

class OLockListener : public ::cppu::WeakImplHelper2< ::com::sun::star::util::XCloseListener,
                                                    ::com::sun::star::frame::XTerminateListener >
{
    ::osl::Mutex m_aMutex;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xInstance;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XActionsApproval > m_xApproval;

    ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent > m_xWrapper;

    sal_Bool m_bDisposed;
    sal_Bool m_bInitialized;

    sal_Int32 m_nMode;

public:
    OLockListener(  const ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent >& xWrapper,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xInstance,
                    sal_Int32 nMode,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XActionsApproval > xApproval );

    ~OLockListener();

    sal_Bool Init();
    void Dispose();

// XEventListener
    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

// XCloseListener
    virtual void SAL_CALL queryClosing( const ::com::sun::star::lang::EventObject& Source, sal_Bool GetsOwnership ) throw (::com::sun::star::util::CloseVetoException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL notifyClosing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

// XTerminateListener
    virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException);

};

#endif

<commit_msg>INTEGRATION: CWS fwk77 (1.3.146); FILE MERGED 2007/10/18 12:48:29 mav 1.3.146.1: #i81435# introduce SeekableOutputStream implementation; use new registration<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: instancelocker.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-04 16:37:49 $
 *
 *  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 __INSTANCELOCKER_HXX_
#define __INSTANCELOCKER_HXX_

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_
#include <com/sun/star/util/XCloseListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XACTIONSAPPROVAL_HPP_
#include <com/sun/star/embed/XActionsApproval.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ACTIONS_HPP_
#include <com/sun/star/embed/Actions.hpp>
#endif

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

class OLockListener;

// the service is implemented as a wrapper to be able to die by refcount
// the disposing mechanics is required for java related scenarios
class OInstanceLocker : public ::cppu::WeakImplHelper3< ::com::sun::star::lang::XComponent,
                                                        ::com::sun::star::lang::XInitialization,
                                                        ::com::sun::star::lang::XServiceInfo >
{
    ::osl::Mutex m_aMutex;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;

    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xLockListener;
    OLockListener* m_pLockListener;

    ::cppu::OInterfaceContainerHelper* m_pListenersContainer; // list of listeners

    sal_Bool m_bDisposed;
    sal_Bool m_bInitialized;

public:
    OInstanceLocker( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext );
    ~OInstanceLocker();

    static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
            impl_staticGetSupportedServiceNames();

    static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();

    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
        impl_staticCreateSelfInstance(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );

// XComponent
    virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

// XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

// XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

};

class OLockListener : public ::cppu::WeakImplHelper2< ::com::sun::star::util::XCloseListener,
                                                    ::com::sun::star::frame::XTerminateListener >
{
    ::osl::Mutex m_aMutex;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xInstance;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XActionsApproval > m_xApproval;

    ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent > m_xWrapper;

    sal_Bool m_bDisposed;
    sal_Bool m_bInitialized;

    sal_Int32 m_nMode;

public:
    OLockListener(  const ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent >& xWrapper,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xInstance,
                    sal_Int32 nMode,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XActionsApproval > xApproval );

    ~OLockListener();

    sal_Bool Init();
    void Dispose();

// XEventListener
    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

// XCloseListener
    virtual void SAL_CALL queryClosing( const ::com::sun::star::lang::EventObject& Source, sal_Bool GetsOwnership ) throw (::com::sun::star::util::CloseVetoException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL notifyClosing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

// XTerminateListener
    virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException);

};

#endif

<|endoftext|>