<commit_before>#ifndef PROCESS_H
#define PROCESS_H
#include"heaps.hpp"
#include"errors.hpp"
#include<vector>
#include<stack>
#include<map>
#include<boost/shared_ptr.hpp>

class Process;

/*Use our own stack in order to support restack()*/
class ProcessStack{
private:
	std::vector<Generic*> stack;
public:
	Generic*& top(size_t off=1){
		if(off > stack.size() || off == 0){
			throw ArcError("internal",
					"Process stack underflow in top()");
		}
		return stack[stack.size() - off];
	}
	void pop(size_t num=1){
		if(num > stack.size()){
			throw ArcError( "internal",
					"Process stack underflow in pop()");
		}
		if(num != 0) stack.resize(stack.size() - num);
	}
	void push(Generic* gp){
		stack.push_back(gp);
	}
	/*Used in function calls*/
	void restack(size_t sz){
		if(sz > stack.size()){
			throw ArcError( "internal",
					"Process stack underflow in restack()");
		}
		size_t off = stack.size() - sz;
		/*Not exactly the best way to do it?*/
		if(sz != 0) stack.erase(stack.begin(), stack.begin() + off);
	}
	Generic*& operator[](int i){
		return stack[i];
	}
	size_t size(void) const{ return stack.size(); };
	friend class Process;
};

class Atom;

class Process : public Heap {
private:
	//should also be locked using the other_spaces lock
	std::vector<Generic*> mailbox;
	Generic* queue;//handled by Arc-side code
	std::map<boost::shared_ptr<Atom>, Generic*> global_cache;
protected:
	virtual void get_root_set(std::stack<Generic**>);
public:
	ProcessStack stack;
	void sendto(Process&, Generic*) const ;
	void assign(boost::shared_ptr<Atom>, Generic*) const ;
	Generic* get(boost::shared_ptr<Atom>);
	virtual ~Process(){};
	Process() : Heap(), queue(NULL) {};
};

typedef enum _e_ProcessStatus {
	process_running, process_waiting, process_dead
} ProcessStatus;

#endif //PROCESS_H

<commit_msg>Corrected signature for Process::get_root_set<commit_after>#ifndef PROCESS_H
#define PROCESS_H
#include"heaps.hpp"
#include"errors.hpp"
#include<vector>
#include<stack>
#include<map>
#include<boost/shared_ptr.hpp>

class Process;

/*Use our own stack in order to support restack()*/
class ProcessStack{
private:
	std::vector<Generic*> stack;
public:
	Generic*& top(size_t off=1){
		if(off > stack.size() || off == 0){
			throw ArcError("internal",
					"Process stack underflow in top()");
		}
		return stack[stack.size() - off];
	}
	void pop(size_t num=1){
		if(num > stack.size()){
			throw ArcError( "internal",
					"Process stack underflow in pop()");
		}
		if(num != 0) stack.resize(stack.size() - num);
	}
	void push(Generic* gp){
		stack.push_back(gp);
	}
	/*Used in function calls*/
	void restack(size_t sz){
		if(sz > stack.size()){
			throw ArcError( "internal",
					"Process stack underflow in restack()");
		}
		size_t off = stack.size() - sz;
		/*Not exactly the best way to do it?*/
		if(sz != 0) stack.erase(stack.begin(), stack.begin() + off);
	}
	Generic*& operator[](int i){
		return stack[i];
	}
	size_t size(void) const{ return stack.size(); };
	friend class Process;
};

class Atom;

class Process : public Heap {
private:
	//should also be locked using the other_spaces lock
	std::vector<Generic*> mailbox;
	Generic* queue;//handled by Arc-side code
	std::map<boost::shared_ptr<Atom>, Generic*> global_cache;
protected:
	virtual void get_root_set(std::stack<Generic**>&);
public:
	ProcessStack stack;
	void sendto(Process&, Generic*) const ;
	void assign(boost::shared_ptr<Atom>, Generic*) const ;
	Generic* get(boost::shared_ptr<Atom>);
	virtual ~Process(){};
	Process() : Heap(), queue(NULL) {};
};

typedef enum _e_ProcessStatus {
	process_running, process_waiting, process_dead
} ProcessStatus;

#endif //PROCESS_H

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/external_protocol_handler.h"

#include "build/build_config.h"

#include <set>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process_impl.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/pref_names.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"

// Whether we accept requests for launching external protocols. This is set to
// false every time an external protocol is requested, and set back to true on
// each user gesture. This variable should only be accessed from the UI thread.
static bool g_accept_requests = true;

// static
void ExternalProtocolHandler::PrepopulateDictionary(DictionaryValue* win_pref) {
  static bool is_warm = false;
  if (is_warm)
    return;
  is_warm = true;

  static const wchar_t* const denied_schemes[] = {
    L"afp",
    L"data",
    L"disk",
    L"disks",
    // ShellExecuting file:///C:/WINDOWS/system32/notepad.exe will simply
    // execute the file specified!  Hopefully we won't see any "file" schemes
    // because we think of file:// URLs as handled URLs, but better to be safe
    // than to let an attacker format the user's hard drive.
    L"file",
    L"hcp",
    L"javascript",
    L"ms-help",
    L"nntp",
    L"shell",
    L"vbscript",
    // view-source is a special case in chrome. When it comes through an
    // iframe or a redirect, it looks like an external protocol, but we don't
    // want to shellexecute it.
    L"view-source",
    L"vnd.ms.radio",
  };

  static const wchar_t* const allowed_schemes[] = {
    L"mailto",
    L"news",
    L"snews",
  };

  bool should_block;
  for (size_t i = 0; i < arraysize(denied_schemes); ++i) {
    if (!win_pref->GetBoolean(denied_schemes[i], &should_block)) {
      win_pref->SetBoolean(denied_schemes[i], true);
    }
  }

  for (size_t i = 0; i < arraysize(allowed_schemes); ++i) {
    if (!win_pref->GetBoolean(allowed_schemes[i], &should_block)) {
      win_pref->SetBoolean(allowed_schemes[i], false);
    }
  }
}

// static
ExternalProtocolHandler::BlockState ExternalProtocolHandler::GetBlockState(
    const std::wstring& scheme) {
  // If we are being carpet bombed, block the request.
  if (!g_accept_requests)
    return BLOCK;

  if (scheme.length() == 1) {
    // We have a URL that looks something like:
    //   C:/WINDOWS/system32/notepad.exe
    // ShellExecuting this URL will cause the specified program to be executed.
    return BLOCK;
  }

  // Check the stored prefs.
  // TODO(pkasting): http://b/1119651 This kind of thing should go in the
  // preferences on the profile, not in the local state.
  PrefService* pref = g_browser_process->local_state();
  if (pref) {  // May be NULL during testing.
    DictionaryValue* win_pref =
        pref->GetMutableDictionary(prefs::kExcludedSchemes);
    CHECK(win_pref);

    // Warm up the dictionary if needed.
    PrepopulateDictionary(win_pref);

    bool should_block;
    if (win_pref->GetBoolean(scheme, &should_block))
      return should_block ? BLOCK : DONT_BLOCK;
  }

  return UNKNOWN;
}

// static
void ExternalProtocolHandler::SetBlockState(const std::wstring& scheme,
                                            BlockState state) {
  // Set in the stored prefs.
  // TODO(pkasting): http://b/1119651 This kind of thing should go in the
  // preferences on the profile, not in the local state.
  PrefService* pref = g_browser_process->local_state();
  if (pref) {  // May be NULL during testing.
    DictionaryValue* win_pref =
        pref->GetMutableDictionary(prefs::kExcludedSchemes);
    CHECK(win_pref);

    if (state == UNKNOWN)
      win_pref->Remove(scheme, NULL);
    else
      win_pref->SetBoolean(scheme, state == BLOCK ? true : false);
  }
}

// static
void ExternalProtocolHandler::LaunchUrl(const GURL& url,
                                        int render_process_host_id,
                                        int tab_contents_id) {
  DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());

  // Escape the input scheme to be sure that the command does not
  // have parameters unexpected by the external program.
  std::string escaped_url_string = EscapeExternalHandlerValue(url.spec());
  GURL escaped_url(escaped_url_string);
  BlockState block_state = GetBlockState(ASCIIToWide(escaped_url.scheme()));
  if (block_state == BLOCK)
    return;

  if (block_state == UNKNOWN) {
#if defined(OS_WIN) || defined(TOOLKIT_GTK) || defined(OS_MACOSX)
    g_accept_requests = false;
    // Ask the user if they want to allow the protocol. This will call
    // LaunchUrlWithoutSecurityCheck if the user decides to accept the protocol.
    RunExternalProtocolDialog(escaped_url,
                              render_process_host_id,
                              tab_contents_id);
#endif
    // For now, allow only whitelisted protocols to fire on Linux/Views.
    // See http://crbug.com/23853 .
    return;
  }

  LaunchUrlWithoutSecurityCheck(escaped_url);
}

// static
void ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(const GURL& url) {
#if defined(OS_MACOSX)
  // This must run on the UI thread on OS X.
  platform_util::OpenExternal(url);
#else
  // Otherwise put this work on the file thread. On Windows ShellExecute may
  // block for a significant amount of time, and it shouldn't hurt on Linux.
  MessageLoop* loop = g_browser_process->file_thread()->message_loop();
  if (loop == NULL) {
    return;
  }

  loop->PostTask(FROM_HERE,
      NewRunnableFunction(&platform_util::OpenExternal, url));
#endif
}

// static
void ExternalProtocolHandler::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kExcludedSchemes);
}

// static
void ExternalProtocolHandler::OnUserGesture() {
  DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());
  g_accept_requests = true;
}
<commit_msg>Protect the user against whitelisted external protocol bombardment as well as greylisted.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/external_protocol_handler.h"

#include "build/build_config.h"

#include <set>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process_impl.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/pref_names.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"

// Whether we accept requests for launching external protocols. This is set to
// false every time an external protocol is requested, and set back to true on
// each user gesture. This variable should only be accessed from the UI thread.
static bool g_accept_requests = true;

// static
void ExternalProtocolHandler::PrepopulateDictionary(DictionaryValue* win_pref) {
  static bool is_warm = false;
  if (is_warm)
    return;
  is_warm = true;

  static const wchar_t* const denied_schemes[] = {
    L"afp",
    L"data",
    L"disk",
    L"disks",
    // ShellExecuting file:///C:/WINDOWS/system32/notepad.exe will simply
    // execute the file specified!  Hopefully we won't see any "file" schemes
    // because we think of file:// URLs as handled URLs, but better to be safe
    // than to let an attacker format the user's hard drive.
    L"file",
    L"hcp",
    L"javascript",
    L"ms-help",
    L"nntp",
    L"shell",
    L"vbscript",
    // view-source is a special case in chrome. When it comes through an
    // iframe or a redirect, it looks like an external protocol, but we don't
    // want to shellexecute it.
    L"view-source",
    L"vnd.ms.radio",
  };

  static const wchar_t* const allowed_schemes[] = {
    L"mailto",
    L"news",
    L"snews",
  };

  bool should_block;
  for (size_t i = 0; i < arraysize(denied_schemes); ++i) {
    if (!win_pref->GetBoolean(denied_schemes[i], &should_block)) {
      win_pref->SetBoolean(denied_schemes[i], true);
    }
  }

  for (size_t i = 0; i < arraysize(allowed_schemes); ++i) {
    if (!win_pref->GetBoolean(allowed_schemes[i], &should_block)) {
      win_pref->SetBoolean(allowed_schemes[i], false);
    }
  }
}

// static
ExternalProtocolHandler::BlockState ExternalProtocolHandler::GetBlockState(
    const std::wstring& scheme) {
  // If we are being carpet bombed, block the request.
  if (!g_accept_requests)
    return BLOCK;

  if (scheme.length() == 1) {
    // We have a URL that looks something like:
    //   C:/WINDOWS/system32/notepad.exe
    // ShellExecuting this URL will cause the specified program to be executed.
    return BLOCK;
  }

  // Check the stored prefs.
  // TODO(pkasting): http://b/1119651 This kind of thing should go in the
  // preferences on the profile, not in the local state.
  PrefService* pref = g_browser_process->local_state();
  if (pref) {  // May be NULL during testing.
    DictionaryValue* win_pref =
        pref->GetMutableDictionary(prefs::kExcludedSchemes);
    CHECK(win_pref);

    // Warm up the dictionary if needed.
    PrepopulateDictionary(win_pref);

    bool should_block;
    if (win_pref->GetBoolean(scheme, &should_block))
      return should_block ? BLOCK : DONT_BLOCK;
  }

  return UNKNOWN;
}

// static
void ExternalProtocolHandler::SetBlockState(const std::wstring& scheme,
                                            BlockState state) {
  // Set in the stored prefs.
  // TODO(pkasting): http://b/1119651 This kind of thing should go in the
  // preferences on the profile, not in the local state.
  PrefService* pref = g_browser_process->local_state();
  if (pref) {  // May be NULL during testing.
    DictionaryValue* win_pref =
        pref->GetMutableDictionary(prefs::kExcludedSchemes);
    CHECK(win_pref);

    if (state == UNKNOWN)
      win_pref->Remove(scheme, NULL);
    else
      win_pref->SetBoolean(scheme, state == BLOCK ? true : false);
  }
}

// static
void ExternalProtocolHandler::LaunchUrl(const GURL& url,
                                        int render_process_host_id,
                                        int tab_contents_id) {
  DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());

  // Escape the input scheme to be sure that the command does not
  // have parameters unexpected by the external program.
  std::string escaped_url_string = EscapeExternalHandlerValue(url.spec());
  GURL escaped_url(escaped_url_string);
  BlockState block_state = GetBlockState(ASCIIToWide(escaped_url.scheme()));
  if (block_state == BLOCK)
    return;

  g_accept_requests = false;

  if (block_state == UNKNOWN) {
#if defined(OS_WIN) || defined(TOOLKIT_GTK) || defined(OS_MACOSX)
    // Ask the user if they want to allow the protocol. This will call
    // LaunchUrlWithoutSecurityCheck if the user decides to accept the protocol.
    RunExternalProtocolDialog(escaped_url,
                              render_process_host_id,
                              tab_contents_id);
#endif
    // For now, allow only whitelisted protocols to fire on Linux/Views.
    // See http://crbug.com/23853 .
    return;
  }

  LaunchUrlWithoutSecurityCheck(escaped_url);
}

// static
void ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(const GURL& url) {
#if defined(OS_MACOSX)
  // This must run on the UI thread on OS X.
  platform_util::OpenExternal(url);
#else
  // Otherwise put this work on the file thread. On Windows ShellExecute may
  // block for a significant amount of time, and it shouldn't hurt on Linux.
  MessageLoop* loop = g_browser_process->file_thread()->message_loop();
  if (loop == NULL) {
    return;
  }

  loop->PostTask(FROM_HERE,
      NewRunnableFunction(&platform_util::OpenExternal, url));
#endif
}

// static
void ExternalProtocolHandler::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kExcludedSchemes);
}

// static
void ExternalProtocolHandler::OnUserGesture() {
  DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());
  g_accept_requests = true;
}
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <boost/test/unit_test.hpp>

#include <pdal/GDALUtils.hpp>
#include <pdal/FileUtils.hpp>
#include "Support.hpp"

BOOST_AUTO_TEST_SUITE(GDALUtilsTest)

BOOST_AUTO_TEST_CASE(GDALUtilsTest_1)
{
    const int FILESIZE = 10000;  // size of file to use
    const int NUMREPS = 10000; // number of points to check

    const std::string tempfile = Support::datapath("vsilfile_test.dat");

    pdal::FileUtils::deleteFile(tempfile);

    srand(17);

    // compute the "true" values, and store into test file
    boost::uint8_t truth[FILESIZE];
    {
        FILE* fp = fopen(tempfile.c_str(), "wb");
        for (int i=0; i<FILESIZE; i++)
        {
            truth[i] = rand() % 256;
            fwrite(&truth[i], 1, 1, fp);\
        }
        fclose(fp);
    }

    // open the test file
    VSILFILE* fp = VSIFOpenL/*fopen*/(tempfile.c_str(), "rb");
    boost::iostreams::stream<pdal::gdal::VSILFileBuffer> i(fp);

    for (int reps=0; reps<NUMREPS; reps++)
    {
        // seek to a random spot and read a point
        int pos = rand()%FILESIZE;
        i.seekg(pos, std::iostream::beg);

        boost::uint8_t c;
        i.read((char*)&c, 1);

        // did we get the correct value?
        BOOST_CHECK(c == truth[pos]);
    }

    i.close();
    VSIFCloseL/*fclose*/(fp);

    pdal::FileUtils::deleteFile(tempfile);

    return;
}

BOOST_AUTO_TEST_CASE(GDALUtilsTest_2)
{
    const int FILESIZE = 10000;  // size of file to use

    const std::string tempfile_a = Support::datapath("vsilfile_test_a.dat");
    const std::string tempfile_b = Support::datapath("vsilfile_test_b.dat");

    pdal::FileUtils::deleteFile(tempfile_a);
    pdal::FileUtils::deleteFile(tempfile_b);

    // compute the "true" values, and store into test file
    boost::uint8_t truth[FILESIZE];
    {
        FILE* fp_a = fopen(tempfile_a.c_str(), "wb");
        VSILFILE* fp_b = VSIFOpenL(tempfile_b.c_str(), "wb");
        for (int i=0; i<FILESIZE; i++)
        {
            truth[i] = rand() % 256;
            fwrite(&truth[i], 1, 1, fp_a);
            VSIFWriteL(&truth[i], 1, 1, fp_b);
        }

        fseek(fp_a, 40, SEEK_SET);
        VSIFSeekL(fp_b, 40, SEEK_SET);

        fwrite(truth, 1, 34, fp_a);
        VSIFWriteL(truth, 1, 34, fp_b);

        fseek(fp_a, 342, SEEK_END);
        VSIFSeekL(fp_b, 342, SEEK_END);

        fwrite(truth, 1, 12, fp_a);
        VSIFWriteL(truth, 1, 12, fp_b);

        long pos_a = (long)ftell(fp_a);
        long pos_b = (long)VSIFTellL(fp_b);
        BOOST_CHECK(pos_a = pos_b);

        fclose(fp_a);
        VSIFCloseL(fp_b);
    }

    const bool ok = Support::compare_files(tempfile_a, tempfile_b);
    BOOST_CHECK(ok);

    pdal::FileUtils::deleteFile(tempfile_a);
    pdal::FileUtils::deleteFile(tempfile_b);

    return;
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add boost::iostreams::restrict<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <boost/test/unit_test.hpp>

#include <pdal/GDALUtils.hpp>
#include <pdal/FileUtils.hpp>
#include "Support.hpp"

#include <boost/iostreams/restrict.hpp>

BOOST_AUTO_TEST_SUITE(GDALUtilsTest)

BOOST_AUTO_TEST_CASE(GDALUtilsTest_1)
{
    const int FILESIZE = 10000;  // size of file to use
    const int NUMREPS = 10000; // number of points to check

    const std::string tempfile = Support::datapath("vsilfile_test.dat");

    pdal::FileUtils::deleteFile(tempfile);

    srand(17);

    // compute the "true" values, and store into test file
    boost::uint8_t truth[FILESIZE];
    {
        FILE* fp = fopen(tempfile.c_str(), "wb");
        for (int i=0; i<FILESIZE; i++)
        {
            truth[i] = rand() % 256;
            fwrite(&truth[i], 1, 1, fp);\
        }
        fclose(fp);
    }

    // open the test file
    VSILFILE* fp = VSIFOpenL/*fopen*/(tempfile.c_str(), "rb");
    boost::iostreams::stream<pdal::gdal::VSILFileBuffer> i(fp);

    for (int reps=0; reps<NUMREPS; reps++)
    {
        // seek to a random spot and read a point
        int pos = rand()%FILESIZE;
        i.seekg(pos, std::iostream::beg);

        boost::uint8_t c;
        i.read((char*)&c, 1);

        // did we get the correct value?
        BOOST_CHECK(c == truth[pos]);
    }

    i.close();
    VSIFCloseL/*fclose*/(fp);

    pdal::FileUtils::deleteFile(tempfile);

    return;
}

BOOST_AUTO_TEST_CASE(GDALUtilsTest_2)
{
    const int FILESIZE = 10000;  // size of file to use

    const std::string tempfile_a = Support::datapath("vsilfile_test_a.dat");
    const std::string tempfile_b = Support::datapath("vsilfile_test_b.dat");

    pdal::FileUtils::deleteFile(tempfile_a);
    pdal::FileUtils::deleteFile(tempfile_b);

    // compute the "true" values, and store into test file
    boost::uint8_t truth[FILESIZE];
    {
        FILE* fp_a = fopen(tempfile_a.c_str(), "wb");
        VSILFILE* fp_b = VSIFOpenL(tempfile_b.c_str(), "wb");
        for (int i=0; i<FILESIZE; i++)
        {
            truth[i] = rand() % 256;
            fwrite(&truth[i], 1, 1, fp_a);
            VSIFWriteL(&truth[i], 1, 1, fp_b);
        }

        fseek(fp_a, 40, SEEK_SET);
        VSIFSeekL(fp_b, 40, SEEK_SET);

        fwrite(truth, 1, 34, fp_a);
        VSIFWriteL(truth, 1, 34, fp_b);

        fseek(fp_a, 342, SEEK_END);
        VSIFSeekL(fp_b, 342, SEEK_END);

        fwrite(truth, 1, 12, fp_a);
        VSIFWriteL(truth, 1, 12, fp_b);

        long pos_a = (long)ftell(fp_a);
        long pos_b = (long)VSIFTellL(fp_b);
        BOOST_CHECK(pos_a = pos_b);

        fclose(fp_a);
        VSIFCloseL(fp_b);
    }

    const bool ok = Support::compare_files(tempfile_a, tempfile_b);
    BOOST_CHECK(ok);

    pdal::FileUtils::deleteFile(tempfile_a);
    pdal::FileUtils::deleteFile(tempfile_b);

    return;
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "StressDivergence.h"

#include "Material.h"

template<>
InputParameters validParams<StressDivergence>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<Real>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");

  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

StressDivergence::StressDivergence(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _stress(getMaterialProperty<RealTensorValue>("stress")),
   _Jacobian_mult(getMaterialProperty<ColumnMajorMatrix>("Jacobian_mult")),
   _component(getParam<Real>("component")),
   _xdisp_coupled(isCoupled("x_disp")),
   _ydisp_coupled(isCoupled("y_disp")),
   _zdisp_coupled(isCoupled("z_disp")),
   _xdisp_var(_xdisp_coupled ? coupled("x_disp") : 0),
   _ydisp_var(_ydisp_coupled ? coupled("y_disp") : 0),
   _zdisp_var(_zdisp_coupled ? coupled("z_disp") : 0)
{}

Real
StressDivergence::computeQpResidual()
{
  return _stress[_qp].row(_component) * _grad_test[_i][_qp];
}

Real
StressDivergence::computeQpJacobian()
{
  RealVectorValue value;
  for(unsigned int j = 0; j<LIBMESH_DIM; ++j)
    for(unsigned int i = 0; i<LIBMESH_DIM; ++i)
    {
      value(i) += 0.5*_Jacobian_mult[_qp]( (LIBMESH_DIM*_component)+i,(LIBMESH_DIM*_component)+j) * _grad_phi[_j][_qp](j);
      value(i) += 0.5*_Jacobian_mult[_qp]( _component+(i*LIBMESH_DIM),(LIBMESH_DIM*_component)+j) * _grad_phi[_j][_qp](j);
    }

  return value * _grad_test[_i][_qp];
}

Real
StressDivergence::computeQpOffDiagJacobian(unsigned int jvar)
{
  unsigned int coupled_component = 0;

  bool active(false);

  if ( _xdisp_coupled && jvar == _xdisp_var )
  {
    coupled_component = 0;
    active = true;
  }
  else if ( _ydisp_coupled && jvar == _ydisp_var )
  {
    coupled_component = 1;
    active = true;
  }
  else if ( _zdisp_coupled && jvar == _zdisp_var )
  {
    coupled_component = 2;
    active = true;
  }

  if ( active )
  {
    RealVectorValue value;
    for(unsigned int j = 0; j<LIBMESH_DIM; ++j)
    {
      for(unsigned int i = 0; i<LIBMESH_DIM; ++i)
      {
        value(i) += _Jacobian_mult[_qp]( (LIBMESH_DIM*_component)+i,(LIBMESH_DIM*coupled_component)+j) * _grad_phi[_j][_qp](j);
      }
    }
    return value * _grad_test[_i][_qp];
  }
  return 0;
}
<commit_msg>Update NearestNode<commit_after>#include "StressDivergence.h"

#include "Material.h"

template<>
InputParameters validParams<StressDivergence>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<Real>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addCoupledVar("disp_x", "The x displacement");
  params.addCoupledVar("disp_y", "The y displacement");
  params.addCoupledVar("disp_z", "The z displacement");

  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

StressDivergence::StressDivergence(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _stress(getMaterialProperty<RealTensorValue>("stress")),
   _Jacobian_mult(getMaterialProperty<ColumnMajorMatrix>("Jacobian_mult")),
   _component(getParam<Real>("component")),
   _xdisp_coupled(isCoupled("disp_x")),
   _ydisp_coupled(isCoupled("disp_y")),
   _zdisp_coupled(isCoupled("disp_z")),
   _xdisp_var(_xdisp_coupled ? coupled("disp_x") : 0),
   _ydisp_var(_ydisp_coupled ? coupled("disp_y") : 0),
   _zdisp_var(_zdisp_coupled ? coupled("disp_z") : 0)
{}

Real
StressDivergence::computeQpResidual()
{
  return _stress[_qp].row(_component) * _grad_test[_i][_qp];
}

Real
StressDivergence::computeQpJacobian()
{
  RealVectorValue value;
  for(unsigned int j = 0; j<LIBMESH_DIM; ++j)
    for(unsigned int i = 0; i<LIBMESH_DIM; ++i)
    {
      value(i) += 0.5*_Jacobian_mult[_qp]( (LIBMESH_DIM*_component)+i,(LIBMESH_DIM*_component)+j) * _grad_phi[_j][_qp](j);
      value(i) += 0.5*_Jacobian_mult[_qp]( _component+(i*LIBMESH_DIM),(LIBMESH_DIM*_component)+j) * _grad_phi[_j][_qp](j);
    }

  return value * _grad_test[_i][_qp];
}

Real
StressDivergence::computeQpOffDiagJacobian(unsigned int jvar)
{
  unsigned int coupled_component = 0;

  bool active(false);

  if ( _xdisp_coupled && jvar == _xdisp_var )
  {
    coupled_component = 0;
    active = true;
  }
  else if ( _ydisp_coupled && jvar == _ydisp_var )
  {
    coupled_component = 1;
    active = true;
  }
  else if ( _zdisp_coupled && jvar == _zdisp_var )
  {
    coupled_component = 2;
    active = true;
  }

  if ( active )
  {
    RealVectorValue value;
    for(unsigned int j = 0; j<LIBMESH_DIM; ++j)
    {
      for(unsigned int i = 0; i<LIBMESH_DIM; ++i)
      {
        value(i) += _Jacobian_mult[_qp]( (LIBMESH_DIM*_component)+i,(LIBMESH_DIM*coupled_component)+j) * _grad_phi[_j][_qp](j);
      }
    }
    return value * _grad_test[_i][_qp];
  }
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
#ifndef _Stroika_Foundation_Math_LinearAlgebra_Vector_inl_
#define _Stroika_Foundation_Math_LinearAlgebra_Vector_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include <vector>

#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"

namespace Stroika {
    namespace Foundation {
        namespace Math {
            namespace LinearAlgebra {

                /*
                 ********************************************************************************
                 ******************************** Vector<T>::IRep_ ******************************
                 ********************************************************************************
                 */
                template <typename T>
                class Vector<T>::IRep_ {
                public:
                    Containers::Sequence<T> fData;
                };

                /*
                 ********************************************************************************
                 ********************************** Vector<T> ***********************************
                 ********************************************************************************
                 */
                template <typename T>
                inline Vector<T>::Vector (size_t dimension)
                    : Vector (dimension, 0)
                {
                }
                template <typename T>
                Vector<T>::Vector (size_t dimension, Configuration::ArgByValueType<T> fillValue)
                    : fRep_ (make_shared<IRep_> ())
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->Append (fillValue);
                    }
                }
                template <typename T>
                Vector<T>::Vector (size_t dimension, const function<T ()>& filler)
                    : fRep_ (make_shared<IRep_> ())
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->Append (filler ());
                    }
                }
                template <typename T>
                template <typename CONTAINER_OF_T, typename ENABLE_IF>
                Vector<T>::Vector (const CONTAINER_OF_T& c)
                    : fRep_ (make_shared<IRep_> (c))
                {
                }
#if 0
                template <typename T>
                void    Vector<T>::Fill (T value)
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->SetAt (i, value);
                    }
                }
                template <typename T>
                void    Vector<T>::Fill (function<T ()> filler)
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->SetAt (i, filler ());
                    }
                }
#endif
                template <typename T>
                inline size_t Vector<T>::GetDimension () const
                {
                    return Rep_->cget ()->size ();
                }
                template <typename T>
                Vector<T> Vector<T>::Transform (function<T (T)> f) const
                {
                    vector<T> tmp;
                    size_t    dimension = GetDimension ();
                    tmp.reserve (dimension);
                    for (size_t i = 0; i < dimension; ++i) {
                        tmp.push_back (f (GetAt (i)));
                    }
                    return tmp;
                }
                template <typename T>
                T Vector<T>::Norm () const
                {
                    T result{};
                    fRep_->cget ()->Apply ([&](T v) { result += v * v; });
                    return sqrt (v);
                }
                template <typename T>
                inline Containers::Sequence<T> Vector<T>::GetItems () const
                {
                    return fRep_->cget ()->fData;
                }
                template <typename T>
                inline T Vector<T>::GetAt (size_t i) const
                {
                    return fRep_->cget ()->fData[i];
                }
                template <typename T>
                inline T Vector<T>::operator[] (size_t i) const
                {
                    return GetAt (i);
                }
                template <typename T>
                Characters::String Vector<T>::ToString () const
                {
                    Characters::StringBuilder sb;
                    sb += L"[";
                    for (T i : fRep_->cget ()->fData) {
                        sb += Characters::ToString (i) + L", ";
                    }
                    sb += L"]";
                    return sb.str ();
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_Math_LinearAlgebra_Vector_inl_*/
<commit_msg>fixed typo<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
#ifndef _Stroika_Foundation_Math_LinearAlgebra_Vector_inl_
#define _Stroika_Foundation_Math_LinearAlgebra_Vector_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include <vector>

#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"

namespace Stroika {
    namespace Foundation {
        namespace Math {
            namespace LinearAlgebra {

                /*
                 ********************************************************************************
                 ******************************** Vector<T>::IRep_ ******************************
                 ********************************************************************************
                 */
                template <typename T>
                class Vector<T>::IRep_ {
                public:
                    Containers::Sequence<T> fData;
                };

                /*
                 ********************************************************************************
                 ********************************** Vector<T> ***********************************
                 ********************************************************************************
                 */
                template <typename T>
                inline Vector<T>::Vector (size_t dimension)
                    : Vector (dimension, 0)
                {
                }
                template <typename T>
                Vector<T>::Vector (size_t dimension, Configuration::ArgByValueType<T> fillValue)
                    : fRep_ (make_shared<IRep_> ())
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->Append (fillValue);
                    }
                }
                template <typename T>
                Vector<T>::Vector (size_t dimension, const function<T ()>& filler)
                    : fRep_ (make_shared<IRep_> ())
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->Append (filler ());
                    }
                }
                template <typename T>
                template <typename CONTAINER_OF_T, typename ENABLE_IF>
                Vector<T>::Vector (const CONTAINER_OF_T& c)
                    : fRep_ (make_shared<IRep_> (c))
                {
                }
#if 0
                template <typename T>
                void    Vector<T>::Fill (T value)
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->SetAt (i, value);
                    }
                }
                template <typename T>
                void    Vector<T>::Fill (function<T ()> filler)
                {
                    for (size_t i = 0; i < dimension; ++i) {
                        fRep_->get ()->SetAt (i, filler ());
                    }
                }
#endif
                template <typename T>
                inline size_t Vector<T>::GetDimension () const
                {
                    return fRep_->cget ()->size ();
                }
                template <typename T>
                Vector<T> Vector<T>::Transform (function<T (T)> f) const
                {
                    vector<T> tmp;
                    size_t    dimension = GetDimension ();
                    tmp.reserve (dimension);
                    for (size_t i = 0; i < dimension; ++i) {
                        tmp.push_back (f (GetAt (i)));
                    }
                    return tmp;
                }
                template <typename T>
                T Vector<T>::Norm () const
                {
                    T result{};
                    fRep_->cget ()->Apply ([&](T v) { result += v * v; });
                    return sqrt (v);
                }
                template <typename T>
                inline Containers::Sequence<T> Vector<T>::GetItems () const
                {
                    return fRep_->cget ()->fData;
                }
                template <typename T>
                inline T Vector<T>::GetAt (size_t i) const
                {
                    return fRep_->cget ()->fData[i];
                }
                template <typename T>
                inline T Vector<T>::operator[] (size_t i) const
                {
                    return GetAt (i);
                }
                template <typename T>
                Characters::String Vector<T>::ToString () const
                {
                    Characters::StringBuilder sb;
                    sb += L"[";
                    for (T i : fRep_->cget ()->fData) {
                        sb += Characters::ToString (i) + L", ";
                    }
                    sb += L"]";
                    return sb.str ();
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_Math_LinearAlgebra_Vector_inl_*/
<|endoftext|>


<commit_before>//
// Copyright (C) 2014
// Alessio Sclocco <a.sclocco@vu.nl>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include <Kernel.hpp>
using isa::OpenCL::Kernel;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::giga;
using isa::utils::toStringValue;

#ifndef FLOPS_HPP
#define FLOPS_HPP

namespace isa {

namespace Benchmarks {

template < typename T > class Flops : public Kernel< T > {
public:
	Flops(string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > * a, CLData< T > * c) throw (OpenCLError);

	inline void setNrThreadsPerBlock(unsigned int threads);
	inline void setNrThreads(unsigned int threads);
	inline void setNrRows(unsigned int rows);
	inline void setNrIterations(unsigned int iterations);

private:
	unsigned int nrThreadsPerBlock;
	unsigned int nrThreads;
	unsigned int nrRows;
	unsigned int nrIterations;
};

// Implementation

template< typename T > Flops< T >::Flops(string dataType) : Kernel< T >("Flops", dataType), nrThreadsPerBlock(0), nrThreads(0), nrRows(0), nrIterations(0) {}

template< typename T > void Flops< T >::generateCode() throw (OpenCLError) {
	long long unsigned int ops = static_cast< long long unsigned int >(nrThreads) * nrIterations * 2;

	this->gflop = giga(ops);

	delete this->code;
	this->code = new string();
	*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict A, __global " + this->dataType + " * const restrict C) {\n"
		"const unsigned int id = (get_global_id(1) * get_global_size(0)) + get_global_id(0);\n"
		+ this->dataType + " a = A[id];\n"
		+ this->dataType + " total = 0;\n"
		"for ( unsigned int iteration = 0; iteration < " + toStringValue< unsigned int >(nrIterations) + "; iteration++ ) {\n"
		"total += (a * get_local_id(0));\n"
		"}\n"
		"C[id] = total;\n"
		"}";

	this->compile();
}

template< typename T > void Flops< T >::operator()(CLData< T > * a, CLData< T > * c) throw (OpenCLError) {
	cl::NDRange globalSize(nrThreads / nrRows, nrRows);
	cl::NDRange localSize(nrThreadsPerBlock, 1);

	this->setArgument(0, *(a->getDeviceData()));
	this->setArgument(1, *(c->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void Flops< T >::setNrThreadsPerBlock(unsigned int threads) {
	nrThreadsPerBlock = threads;
}

template< typename T > inline void Flops< T >::setNrThreads(unsigned int threads) {
	nrThreads = threads;
}

template< typename T > inline void Flops< T >::setNrRows(unsigned int rows) {
	nrRows = rows;
}

template< typename T > inline void Flops< T >::setNrIterations(unsigned int iteration) {
	nrIterations = iteration;
}

} // Benchmarks
} // isa

#endif // FLOPS_HPP
<commit_msg>Add more operations.<commit_after>//
// Copyright (C) 2014
// Alessio Sclocco <a.sclocco@vu.nl>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include <Kernel.hpp>
using isa::OpenCL::Kernel;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::giga;
using isa::utils::toStringValue;

#ifndef FLOPS_HPP
#define FLOPS_HPP

namespace isa {

namespace Benchmarks {

template < typename T > class Flops : public Kernel< T > {
public:
	Flops(string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > * a, CLData< T > * c) throw (OpenCLError);

	inline void setNrThreadsPerBlock(unsigned int threads);
	inline void setNrThreads(unsigned int threads);
	inline void setNrRows(unsigned int rows);
	inline void setNrIterations(unsigned int iterations);

private:
	unsigned int nrThreadsPerBlock;
	unsigned int nrThreads;
	unsigned int nrRows;
	unsigned int nrIterations;
};

// Implementation

template< typename T > Flops< T >::Flops(string dataType) : Kernel< T >("Flops", dataType), nrThreadsPerBlock(0), nrThreads(0), nrRows(0), nrIterations(0) {}

template< typename T > void Flops< T >::generateCode() throw (OpenCLError) {
	long long unsigned int ops = static_cast< long long unsigned int >(nrThreads) * nrIterations * 8;

	this->gflop = giga(ops);

	delete this->code;
	this->code = new string();
	*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict A, __global " + this->dataType + " * const restrict C) {\n"
		"const unsigned int id = (get_global_id(1) * get_global_size(0)) + get_global_id(0);\n"
		+ this->dataType + " a = A[id];\n"
		+ this->dataType + " total = 0;\n"
		"for ( unsigned int iteration = 0; iteration < " + toStringValue< unsigned int >(nrIterations) + "; iteration++ ) {\n"
		"total += (a * get_local_id(0));\n"
		"total += (a * get_local_id(0));\n"
		"total += (a * get_local_id(0));\n"
		"total += (a * get_local_id(0));\n"
		"}\n"
		"C[id] = total;\n"
		"}";

	this->compile();
}

template< typename T > void Flops< T >::operator()(CLData< T > * a, CLData< T > * c) throw (OpenCLError) {
	cl::NDRange globalSize(nrThreads / nrRows, nrRows);
	cl::NDRange localSize(nrThreadsPerBlock, 1);

	this->setArgument(0, *(a->getDeviceData()));
	this->setArgument(1, *(c->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void Flops< T >::setNrThreadsPerBlock(unsigned int threads) {
	nrThreadsPerBlock = threads;
}

template< typename T > inline void Flops< T >::setNrThreads(unsigned int threads) {
	nrThreads = threads;
}

template< typename T > inline void Flops< T >::setNrRows(unsigned int rows) {
	nrRows = rows;
}

template< typename T > inline void Flops< T >::setNrIterations(unsigned int iteration) {
	nrIterations = iteration;
}

} // Benchmarks
} // isa

#endif // FLOPS_HPP
<|endoftext|>


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

/**
 *  \author volodink
 *  \brief define Arduino led on pin 13 as system led for status display (blink me twice, if you hear me)
 */
#define SYS_LED 13

/**
 *  \brief Software serial port object
 *  \author volodink
 */
SoftwareSerial serial(8,9);

/**
 *  \brief Starts only 1 time after reset
 *  \author volodink
 */
void setup() {
    // setup hardware serial
    Serial.begin(57600);
    // setup software serial
    serial.begin(9600);

    // set pins direction
    pinMode(SYS_LED, OUTPUT);
}

/**
 *  \brief Running in the infinite loop
 *  \author volodink
 */
void loop() {
    serial.println("hello");
    delay(1000);
}<commit_msg>Update ubx_decoder.cpp<commit_after>#include <Arduino.h>
#include <SoftwareSerial.h>

/**
 *  \author volodink
 *  \brief define Arduino led on pin 13 as system led for status display (blink me twice, if you hear me)
 */
#define SYS_LED 13

/**
 *  \brief Software serial port object
 *  \author volodink
 */
SoftwareSerial serial(8,9);

/**
 *  \brief Starts only 1 time after reset
 *  \author volodink
 */
void setup() {
    // setup hardware serial for GPS side
    Serial.begin(57600);
    // setup software serial for PC side
    serial.begin(9600);

    // set pins direction
    pinMode(SYS_LED, OUTPUT);
}

/**
 *  \brief Running in the infinite loop
 *  \author volodink
 */
void loop() {
    serial.println("hello");
    delay(1000);
}
<|endoftext|>


<commit_before>/// \file libport/assert.hh
/// \brief Provide nice assert like macros.

#ifndef LIBPORT_ASSERT_HH
# define LIBPORT_ASSERT_HH

# include <cassert>
# include <cstdlib>

// We have mysterious random aborts on OSX which is compiled with
// NDEBUG.  Temporarily disable NDEBUG to have verbose paborts.
# if defined NDEBUG
#  define LIBPORT_ASSERT_VERBOSE 0
# else
#  define LIBPORT_ASSERT_VERBOSE 1
# endif

# include <iostream> // std::cerr
# include <libport/cstdio> // libport::strerror.

# include <libport/compiler.hh>

# ifdef _MSC_VER
#  include <crtdbg.h>
# endif

namespace libport
{
  /// A wrapper to std::abort to ensure that it is declared as
  /// noreturn (which is not the case of std::abort with MSVC).
  LIBPORT_API
  ATTRIBUTE_NORETURN
  void abort();
}

/*---------------------------.
| passert -- Pretty assert.  |
`---------------------------*/

/// \def passert(Subject, Assertion)
/// Same as assert, but on failure, dump \a Subject of std::cerr.
# if ! LIBPORT_ASSERT_VERBOSE
#  define passert(Subject, Assertion)
# else

#  define passert(Subject, Assertion)			\
  ((void) ((Assertion)					\
	   ? 0						\
	   : __passert(Subject, Assertion)))

#  define __passert(Subject, Assertion)                         \
  pabort("failed assertion: " << #Assertion << std::endl	\
         << "\t with "                                          \
         << #Subject << " = " << Subject)

# endif // LIBPORT_ASSERT_VERBOSE

/*-------------------------.
| pabort -- Pretty abort.  |
`-------------------------*/

/// \def pabort(Msg)
///
/// Same as abort, but when NDEBUG is not set, report the Msg using
/// the operator<< on std::cerr.  Msg may include << itself.  So
/// if Msg is complex, beware of predence issues with << and use parens
/// on the invocation side.

# define pabort(Msg)                                    \
  (std::cerr << __FILE__ ":" << __LINE__                \
             << ": abort: " << Msg << std::endl,        \
   libport::abort(), 0)

/*----------------------------------------------.
| errabort -- perror (well, strerror) + abort.  |
`----------------------------------------------*/

/// \def errabort(Msg)
# define errabort(Msg)    \
  pabort(libport::strerror(errno) << ": " << Msg)

/*--------------------------------------------------------.
| assert_exp -- Require a non-null value, and return it.  |
`--------------------------------------------------------*/

# if ! LIBPORT_ASSERT_VERBOSE
#  define assert_exp(Obj)		(Obj)
# else
// Basically, an assert that can be used in an expression.  I meant to
// use "nonnull", but this name is unused by libstdc++, so the #define
// breaks everything.
namespace libport
{
  template <typename T>
  inline
  T
  assert_exp_(T t, const char* file, int line, const char* msg)
  {
    if (!t)
    {
      std::cerr
	<< file << ": " << line << ": failed assertion: " << msg << std::endl;
      libport::abort();
    }
    return t;
  }
}

#  define assert_exp(Obj)		\
  libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)
# endif // LIBPORT_ASSERT_VERBOSE

#endif // !LIBPORT_ASSERT_HH
<commit_msg>Add assert_eq & cie: assertions that print both values in case of failure.<commit_after>/// \file libport/assert.hh
/// \brief Provide nice assert like macros.

#ifndef LIBPORT_ASSERT_HH
# define LIBPORT_ASSERT_HH

# include <cassert>
# include <cstdlib>

// We have mysterious random aborts on OSX which is compiled with
// NDEBUG.  Temporarily disable NDEBUG to have verbose paborts.
# if defined NDEBUG
#  define LIBPORT_ASSERT_VERBOSE 0
# else
#  define LIBPORT_ASSERT_VERBOSE 1
# endif

# include <iostream> // std::cerr
# include <libport/cstdio> // libport::strerror.

# include <libport/compiler.hh>
# include <libport/format.hh>

# ifdef _MSC_VER
#  include <crtdbg.h>
# endif

namespace libport
{
  /// A wrapper to std::abort to ensure that it is declared as
  /// noreturn (which is not the case of std::abort with MSVC).
  LIBPORT_API
  ATTRIBUTE_NORETURN
  void abort();
}

/*---------------------------.
| passert -- Pretty assert.  |
`---------------------------*/

/// \def passert(Subject, Assertion)
/// Same as assert, but on failure, dump \a Subject of std::cerr.
# if ! LIBPORT_ASSERT_VERBOSE
#  define passert(Subject, Assertion)
# else

#  define passert(Subject, Assertion)			\
  ((void) ((Assertion)					\
	   ? 0						\
	   : __passert(Subject, Assertion)))

#  define __passert(Subject, Assertion)                         \
  pabort("failed assertion: " << #Assertion << std::endl	\
         << "\t with "                                          \
         << #Subject << " = " << Subject)

# endif // LIBPORT_ASSERT_VERBOSE

/*-------------------------.
| pabort -- Pretty abort.  |
`-------------------------*/

/// \def pabort(Msg)
///
/// Same as abort, but when NDEBUG is not set, report the Msg using
/// the operator<< on std::cerr.  Msg may include << itself.  So
/// if Msg is complex, beware of predence issues with << and use parens
/// on the invocation side.

# define pabort(Msg)                                    \
  (std::cerr << __FILE__ ":" << __LINE__                \
             << ": abort: " << Msg << std::endl,        \
   libport::abort(), 0)

/*----------------------------------------------.
| errabort -- perror (well, strerror) + abort.  |
`----------------------------------------------*/

/// \def errabort(Msg)
# define errabort(Msg)    \
  pabort(libport::strerror(errno) << ": " << Msg)

/*--------------------------------------------------------.
| assert_exp -- Require a non-null value, and return it.  |
`--------------------------------------------------------*/

# if ! LIBPORT_ASSERT_VERBOSE
#  define assert_exp(Obj)		(Obj)
# else
// Basically, an assert that can be used in an expression.  I meant to
// use "nonnull", but this name is unused by libstdc++, so the #define
// breaks everything.
namespace libport
{
  template <typename T>
  inline
  T
  assert_exp_(T t, const char* file, int line, const char* msg)
  {
    if (!t)
    {
      std::cerr
	<< file << ": " << line << ": failed assertion: " << msg << std::endl;
      libport::abort();
    }
    return t;
  }
}

#  define assert_exp(Obj)		\
  libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)
# endif // LIBPORT_ASSERT_VERBOSE

/*-------------------------------------------------------------.
| assert_comp -- compare two values, show both of them if fail |
`-------------------------------------------------------------*/

# if ! LIBPORT_ASSERT_VERBOSE
#  define assert_eq
#  define assert_ne
# else
#  define assert_op(Op, A, B)                                           \
  if (!(A Op B))                                                        \
    pabort(::libport::format(#A " " #Op " " #B " (%s " #Op " %s)", A, B)) \

#  define assert_eq(A, B) assert_op(==, A, B)
#  define assert_ne(A, B) assert_op(!=, A, B)
#  define assert_lt(A, B) assert_op(< , A, B)
#  define assert_le(A, B) assert_op(<=, A, B)
#  define assert_gt(A, B) assert_op(> , A, B)
#  define assert_ge(A, B) assert_op(>=, A, B)
# endif

#endif // !LIBPORT_ASSERT_HH
<|endoftext|>


<commit_before>#include "catch.hpp"

// mapnik
#include <mapnik/image_any.hpp>
#include <mapnik/color.hpp>
#include <mapnik/image_view_any.hpp>
#include <mapnik/image_util.hpp>

TEST_CASE("image class") {

SECTION("test gray16") {

    const mapnik::image_gray16 im(4,4);
    mapnik::image_gray16 im2(im);
    mapnik::image_gray16 im3(5,5);

    CHECK(im == im);
    CHECK_FALSE(im == im2);
    CHECK_FALSE(im2 == im3);
    CHECK(im < im3);
    CHECK_FALSE(im < im2);

    // Check that width is correct
    CHECK(im.width() == 4);
    CHECK(im2.width() == 4);

    // Check that height is correct
    CHECK(im.height() == 4);
    CHECK(im2.height() == 4);

    CHECK(im(0,0) == 0);
    CHECK(im2(0,0) == 0);
    im2(0,0) = 1;
    CHECK(im2(0,0) == 1);
    im2.set(514);
    CHECK(im2(0,0) == 514);
    CHECK(im2(1,1) == 514);

    // Check that size is correct
    CHECK(im.size() == 32);
    CHECK(im2.size() == 32);

    // Check that row_size is correct
    CHECK(im.row_size() == 8);
    CHECK(im2.row_size() == 8);

    // Check that get_premultiplied is correct
    CHECK_FALSE(im.get_premultiplied());
    CHECK_FALSE(im2.get_premultiplied());

    // Check that set premultiplied works
    im2.set_premultiplied(true);
    CHECK(im2.get_premultiplied());

    // Check that painted is correct
    CHECK_FALSE(im.painted());
    CHECK_FALSE(im2.painted());

    // Check that set premultiplied works
    im2.painted(true);
    CHECK(im2.painted());

    // Check that offset is correct
    CHECK(im.get_offset() == 0.0);
    CHECK(im2.get_offset() == 0.0);

    // Check that set offset works
    im2.set_offset(2.3);
    CHECK(im2.get_offset() == 2.3);

    // Check that scaling is correct
    CHECK(im.get_scaling() == 1.0);
    CHECK(im2.get_scaling() == 1.0);

    // Check that set scaling works
    im2.set_scaling(1.1);
    CHECK(im2.get_scaling() == 1.1);

    // CHECK that image dtype is correct
    CHECK(im.get_dtype() == mapnik::image_dtype_gray16);
    CHECK(im2.get_dtype() == mapnik::image_dtype_gray16);

    using pixel_type = mapnik::image_view_gray16::pixel_type;
    pixel_type expected_val;
    // Check that all data in the view is correct
    // IM
    expected_val = 0;
    pixel_type const* data_im = im.data();
    CHECK(*data_im == expected_val);
    unsigned char const* data_b = im.bytes();
    CHECK(*data_b == 0);
    for (std::size_t y = 0; y < im.height(); ++y)
    {
        std::size_t width = im.width();
        pixel_type const* data_1  = im.get_row(y);
        pixel_type const* data_2  = im.get_row(y, 1);
        for (std::size_t x = 0; x < width; ++x)
        {
            CHECK(*data_1 == expected_val);
            ++data_1;
        }
        for (std::size_t x = 1; x < width; ++x)
        {
            CHECK(*data_2 == expected_val);
            ++data_2;
        }
    }
    // IM2
    expected_val = 514;
    pixel_type * data_im2 = im2.data();
    CHECK(*data_im2 == expected_val);
    unsigned char * data_b2 = im2.bytes();
    CHECK(*data_b2 == 2);
    ++data_b;
    CHECK(*data_b2 == 2);
    for (std::size_t y = 0; y < im2.height(); ++y)
    {
        std::size_t width = im2.width();
        pixel_type const* data_1  = im2.get_row(y);
        pixel_type const* data_2  = im2.get_row(y, 1);
        for (std::size_t x = 0; x < width; ++x)
        {
            CHECK(*data_1 == expected_val);
            ++data_1;
        }
        for (std::size_t x = 1; x < width; ++x)
        {
            CHECK(*data_2 == expected_val);
            ++data_2;
        }
    }

    // Test set row
    std::vector<pixel_type> v1(im2.width(), 30);
    std::vector<pixel_type> v2(im2.width()-1, 50);
    im2.set_row(0, v1.data(), v1.size());
    im2.set_row(1, 1, v2.size(), v2.data());

    CHECK(im2(0,0) == 30);
    CHECK(im2(0,1) == 514);
    CHECK(im2(1,1) == 50);

} // END SECTION

SECTION("image_null")
{
    mapnik::image_null im_null;
    const mapnik::image_null im_null2(2,2); // Actually doesn't really set any size
    mapnik::image_null im_null3(im_null2);
    mapnik::image_null im_null4(std::move(im_null3));

    // All nulls are equal
    CHECK(im_null == im_null4);
    CHECK(im_null == im_null2);

    // No null is greater
    CHECK_FALSE(im_null < im_null4);
    CHECK_FALSE(im_null < im_null2);

    // Check defaults
    CHECK(im_null.width() == 0);
    CHECK(im_null.height() == 0);
    CHECK(im_null.size() == 0);
    CHECK(im_null.row_size() == 0);
    // Setting offset does nothing
    im_null.set_offset(10000000.0);
    CHECK(im_null.get_offset() == 0.0);
    // Setting scaling does nothing
    im_null.set_scaling(123123123.0);
    CHECK(im_null.get_scaling() == 1.0);
    CHECK(im_null.get_dtype() == mapnik::image_dtype_null);
    // Setting premultiplied does nothing
    im_null.set_premultiplied(true);
    CHECK_FALSE(im_null.get_premultiplied());
    // Setting painted does nothing
    im_null.painted(true);
    CHECK_FALSE(im_null.painted());

    // Should throw if we try to access or setdata.
    REQUIRE_THROWS(im_null(0,0));
    REQUIRE_THROWS(im_null2(0,0));
    REQUIRE_THROWS(im_null(0,0) = 1);

    unsigned char const* e1 = im_null.bytes();
    unsigned char * e2 = im_null.bytes();
    CHECK(e1 == nullptr);
    CHECK(e2 == nullptr);

} // END SECTION

SECTION("image any")
{
    mapnik::image_null null_im;
    const mapnik::image_any im_any_null(null_im);
    CHECK(im_any_null.get_dtype() == mapnik::image_dtype_null);
    CHECK(im_any_null.bytes() == nullptr);

    mapnik::image_gray16 im(4,4);
    mapnik::fill(im, 514);
    mapnik::image_any im_any(im);

    CHECK(im_any.get_dtype() == mapnik::image_dtype_gray16);
    unsigned char * foo = im_any.bytes();
    CHECK(*foo == 2);
    ++foo;
    CHECK(*foo == 2);
    CHECK(im_any.width() == 4);
    CHECK(im_any.height() == 4);
    CHECK(im_any.size() == 32);
    CHECK(im_any.row_size() == 8);
    CHECK_FALSE(im_any.get_premultiplied());
    im_any.set_offset(10.0);
    CHECK(im_any.get_offset() == 10.0);
    im_any.set_scaling(2.1);
    CHECK(im_any.get_scaling() == 2.1);

} // END SECTION

} // END TEST CASE

<commit_msg>Added more tests around image_any<commit_after>#include "catch.hpp"

// mapnik
#include <mapnik/image_any.hpp>
#include <mapnik/color.hpp>
#include <mapnik/image_view_any.hpp>
#include <mapnik/image_util.hpp>

TEST_CASE("image class") {

SECTION("test gray16") {

    const mapnik::image_gray16 im(4,4);
    mapnik::image_gray16 im2(im);
    mapnik::image_gray16 im3(5,5);

    CHECK(im == im);
    CHECK_FALSE(im == im2);
    CHECK_FALSE(im2 == im3);
    CHECK(im < im3);
    CHECK_FALSE(im < im2);

    // Check that width is correct
    CHECK(im.width() == 4);
    CHECK(im2.width() == 4);

    // Check that height is correct
    CHECK(im.height() == 4);
    CHECK(im2.height() == 4);

    CHECK(im(0,0) == 0);
    CHECK(im2(0,0) == 0);
    im2(0,0) = 1;
    CHECK(im2(0,0) == 1);
    im2.set(514);
    CHECK(im2(0,0) == 514);
    CHECK(im2(1,1) == 514);

    // Check that size is correct
    CHECK(im.size() == 32);
    CHECK(im2.size() == 32);

    // Check that row_size is correct
    CHECK(im.row_size() == 8);
    CHECK(im2.row_size() == 8);

    // Check that get_premultiplied is correct
    CHECK_FALSE(im.get_premultiplied());
    CHECK_FALSE(im2.get_premultiplied());

    // Check that set premultiplied works
    im2.set_premultiplied(true);
    CHECK(im2.get_premultiplied());

    // Check that painted is correct
    CHECK_FALSE(im.painted());
    CHECK_FALSE(im2.painted());

    // Check that set premultiplied works
    im2.painted(true);
    CHECK(im2.painted());

    // Check that offset is correct
    CHECK(im.get_offset() == 0.0);
    CHECK(im2.get_offset() == 0.0);

    // Check that set offset works
    im2.set_offset(2.3);
    CHECK(im2.get_offset() == 2.3);

    // Check that scaling is correct
    CHECK(im.get_scaling() == 1.0);
    CHECK(im2.get_scaling() == 1.0);

    // Check that set scaling works
    im2.set_scaling(1.1);
    CHECK(im2.get_scaling() == 1.1);

    // CHECK that image dtype is correct
    CHECK(im.get_dtype() == mapnik::image_dtype_gray16);
    CHECK(im2.get_dtype() == mapnik::image_dtype_gray16);

    using pixel_type = mapnik::image_view_gray16::pixel_type;
    pixel_type expected_val;
    // Check that all data in the view is correct
    // IM
    expected_val = 0;
    pixel_type const* data_im = im.data();
    CHECK(*data_im == expected_val);
    unsigned char const* data_b = im.bytes();
    CHECK(*data_b == 0);
    for (std::size_t y = 0; y < im.height(); ++y)
    {
        std::size_t width = im.width();
        pixel_type const* data_1  = im.get_row(y);
        pixel_type const* data_2  = im.get_row(y, 1);
        for (std::size_t x = 0; x < width; ++x)
        {
            CHECK(*data_1 == expected_val);
            ++data_1;
        }
        for (std::size_t x = 1; x < width; ++x)
        {
            CHECK(*data_2 == expected_val);
            ++data_2;
        }
    }
    // IM2
    expected_val = 514;
    pixel_type * data_im2 = im2.data();
    CHECK(*data_im2 == expected_val);
    unsigned char * data_b2 = im2.bytes();
    CHECK(*data_b2 == 2);
    ++data_b;
    CHECK(*data_b2 == 2);
    for (std::size_t y = 0; y < im2.height(); ++y)
    {
        std::size_t width = im2.width();
        pixel_type const* data_1  = im2.get_row(y);
        pixel_type const* data_2  = im2.get_row(y, 1);
        for (std::size_t x = 0; x < width; ++x)
        {
            CHECK(*data_1 == expected_val);
            ++data_1;
        }
        for (std::size_t x = 1; x < width; ++x)
        {
            CHECK(*data_2 == expected_val);
            ++data_2;
        }
    }

    // Test set row
    std::vector<pixel_type> v1(im2.width(), 30);
    std::vector<pixel_type> v2(im2.width()-1, 50);
    im2.set_row(0, v1.data(), v1.size());
    im2.set_row(1, 1, v2.size(), v2.data());

    CHECK(im2(0,0) == 30);
    CHECK(im2(0,1) == 514);
    CHECK(im2(1,1) == 50);

} // END SECTION

SECTION("image_null")
{
    mapnik::image_null im_null;
    const mapnik::image_null im_null2(2,2); // Actually doesn't really set any size
    mapnik::image_null im_null3(im_null2);
    mapnik::image_null im_null4(std::move(im_null3));

    // All nulls are equal
    CHECK(im_null == im_null4);
    CHECK(im_null == im_null2);

    // No null is greater
    CHECK_FALSE(im_null < im_null4);
    CHECK_FALSE(im_null < im_null2);

    // Check defaults
    CHECK(im_null.width() == 0);
    CHECK(im_null.height() == 0);
    CHECK(im_null.size() == 0);
    CHECK(im_null.row_size() == 0);
    // Setting offset does nothing
    im_null.set_offset(10000000.0);
    CHECK(im_null.get_offset() == 0.0);
    // Setting scaling does nothing
    im_null.set_scaling(123123123.0);
    CHECK(im_null.get_scaling() == 1.0);
    CHECK(im_null.get_dtype() == mapnik::image_dtype_null);
    // Setting premultiplied does nothing
    im_null.set_premultiplied(true);
    CHECK_FALSE(im_null.get_premultiplied());
    // Setting painted does nothing
    im_null.painted(true);
    CHECK_FALSE(im_null.painted());

    // Should throw if we try to access or setdata.
    REQUIRE_THROWS(im_null(0,0));
    REQUIRE_THROWS(im_null2(0,0));
    REQUIRE_THROWS(im_null(0,0) = 1);

    unsigned char const* e1 = im_null.bytes();
    unsigned char * e2 = im_null.bytes();
    CHECK(e1 == nullptr);
    CHECK(e2 == nullptr);

} // END SECTION

SECTION("image any")
{
    mapnik::image_null null_im;
    const mapnik::image_any im_any_null(null_im);
    CHECK(im_any_null.get_dtype() == mapnik::image_dtype_null);
    CHECK(im_any_null.bytes() == nullptr);

    mapnik::image_gray16 im(4,4);
    mapnik::fill(im, 514);
    mapnik::image_any im_any(im);

    CHECK(im_any.get_dtype() == mapnik::image_dtype_gray16);
    unsigned char * foo = im_any.bytes();
    CHECK(*foo == 2);
    ++foo;
    CHECK(*foo == 2);
    CHECK(im_any.width() == 4);
    CHECK(im_any.height() == 4);
    CHECK(im_any.size() == 32);
    CHECK(im_any.row_size() == 8);
    CHECK_FALSE(im_any.get_premultiplied());
    im_any.set_offset(10.0);
    CHECK(im_any.get_offset() == 10.0);
    im_any.set_scaling(2.1);
    CHECK(im_any.get_scaling() == 2.1);
    CHECK_FALSE(im_any.painted());

} // END SECTION

SECTION("test image_any initialization")
{
    {
        mapnik::image_any im(4,4);
        CHECK(im.get_dtype() == mapnik::image_dtype_rgba8);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_null);
        CHECK(im.get_dtype() == mapnik::image_dtype_null);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray8);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray8);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray8s);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray8s);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray16);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray16);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray16s);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray16s);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray32);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray32);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray32s);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray32s);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray32f);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray32f);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray64);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray64);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray64s);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray64s);
    }
    {
        mapnik::image_any im(4, 4, mapnik::image_dtype_gray64f);
        CHECK(im.get_dtype() == mapnik::image_dtype_gray64f);
    }

} // END SECTION

} // END TEST CASE

<|endoftext|>


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

#ifndef _SB_INTERN_HXX
#define _SB_INTERN_HXX

#include <sbxfac.hxx>
#ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX
#include <unotools/transliterationwrapper.hxx>
#endif
#include "sb.hxx"

class ::utl::TransliterationWrapper;
class SbUnoFactory;
class SbTypeFactory;
class SbOLEFactory;
class SbiInstance;
class SbModule;

class SbiFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
    virtual SbxObject* CreateObject( const String& );
};

struct SbClassData
{
    SbxArrayRef     mxIfaces;

    SbClassData( void );
    ~SbClassData( void )
        { clear(); }
    void clear( void );
};

// #115824: Factory class to create class objects (type command)
// Implementation: sb.cxx
class SbClassFactory : public SbxFactory
{
    SbxObjectRef    xClassModules;

public:
    SbClassFactory( void );

    void AddClassModule( SbModule* pClassModule );
    void RemoveClassModule( SbModule* pClassModule );

    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
    virtual SbxObject* CreateObject( const String& );

    SbModule* FindClass( const String& rClassName );
};

// Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette
class SbErrorStackEntry
{
public:
    SbErrorStackEntry(SbMethodRef aM, xub_StrLen nL, xub_StrLen nC1, xub_StrLen nC2)
        : aMethod(aM), nLine(nL), nCol1(nC1), nCol2(nC2) {}
    SbMethodRef aMethod;
    xub_StrLen nLine;
    xub_StrLen nCol1, nCol2;
};

SV_DECL_PTRARR_DEL(SbErrorStack, SbErrorStackEntry*, 1, 1)

struct SbiGlobals
{
    SbiInstance*    pInst;          // alle aktiven Runtime-Instanzen
    SbiFactory*     pSbFac;         // StarBASIC-Factory
    SbUnoFactory*   pUnoFac;        // Factory fuer Uno-Structs bei DIM AS NEW
    SbTypeFactory*  pTypeFac;       // Factory for user defined types
    SbClassFactory* pClassFac;      // Factory for user defined classes (based on class modules)
    SbOLEFactory*   pOLEFac;        // Factory for OLE types
    SbModule*       pMod;           // aktuell aktives Modul
    SbModule*       pCompMod;       // aktuell compiliertes Modul
    short           nInst;          // Anzahl BASICs
    Link            aErrHdl;        // globaler Error-Handler
    Link            aBreakHdl;      // globaler Break-Handler
    SbError         nCode;          // aktueller Fehlercode
    xub_StrLen      nLine;          // aktuelle Zeile
    xub_StrLen      nCol1,nCol2;    // aktuelle Spalten (von,bis)
    BOOL            bCompiler;      // Flag fuer Compiler-Error
    BOOL            bGlobalInitErr; // Beim GlobalInit trat ein Compiler-Fehler auf
    BOOL            bRunInit;       // TRUE, wenn RunInit vom Basic aktiv ist
    String          aErrMsg;        // Puffer fuer GetErrorText()
    SbLanguageMode  eLanguageMode;  // Flag fuer Visual-Basic-Script-Modus
    SbErrorStack*   pErrStack;      // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette
    ::utl::TransliterationWrapper* pTransliterationWrapper;    // For StrComp
    BOOL            bBlockCompilerError;
    BasicManager*   pAppBasMgr;

    SbiGlobals();
    ~SbiGlobals();
};

// Utility-Makros und -Routinen

SbiGlobals* GetSbData();

#define pINST       GetSbData()->pInst
#define pMOD        GetSbData()->pMod
#define pCMOD       GetSbData()->pCompMod
#define pSBFAC      GetSbData()->pSbFac
#define pUNOFAC     GetSbData()->pUnoFac
#define pTYPEFAC    GetSbData()->pTypeFac
#define pCLASSFAC   GetSbData()->pClassFac
#define pOLEFAC     GetSbData()->pOLEFac

#endif

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

#ifndef _SB_INTERN_HXX
#define _SB_INTERN_HXX

#include <sbxfac.hxx>
#ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX
#include <unotools/transliterationwrapper.hxx>
#endif
#include "sb.hxx"

class ::utl::TransliterationWrapper;
class SbUnoFactory;
class SbTypeFactory;
class SbOLEFactory;
class SbiInstance;
class SbModule;

class SbiFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
    virtual SbxObject* CreateObject( const String& );
};

struct SbClassData
{
    SbxArrayRef     mxIfaces;

    SbClassData( void );
    ~SbClassData( void )
        { clear(); }
    void clear( void );
};

// #115824: Factory class to create class objects (type command)
// Implementation: sb.cxx
class SbClassFactory : public SbxFactory
{
    SbxObjectRef    xClassModules;

public:
    SbClassFactory( void );

    void AddClassModule( SbModule* pClassModule );
    void RemoveClassModule( SbModule* pClassModule );

    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
    virtual SbxObject* CreateObject( const String& );

    SbModule* FindClass( const String& rClassName );
};

// Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette
class SbErrorStackEntry
{
public:
    SbErrorStackEntry(SbMethodRef aM, xub_StrLen nL, xub_StrLen nC1, xub_StrLen nC2)
        : aMethod(aM), nLine(nL), nCol1(nC1), nCol2(nC2) {}
    SbMethodRef aMethod;
    xub_StrLen nLine;
    xub_StrLen nCol1, nCol2;
};

SV_DECL_PTRARR_DEL(SbErrorStack, SbErrorStackEntry*, 1, 1)

struct SbiGlobals
{
    SbiInstance*    pInst;          // alle aktiven Runtime-Instanzen
    SbiFactory*     pSbFac;         // StarBASIC-Factory
    SbUnoFactory*   pUnoFac;        // Factory fuer Uno-Structs bei DIM AS NEW
    SbTypeFactory*  pTypeFac;       // Factory for user defined types
    SbClassFactory* pClassFac;      // Factory for user defined classes (based on class modules)
    SbOLEFactory*   pOLEFac;        // Factory for OLE types
    SbModule*       pMod;           // aktuell aktives Modul
    SbModule*       pCompMod;       // aktuell compiliertes Modul
    short           nInst;          // Anzahl BASICs
    Link            aErrHdl;        // globaler Error-Handler
    Link            aBreakHdl;      // globaler Break-Handler
    SbError         nCode;          // aktueller Fehlercode
    xub_StrLen      nLine;          // aktuelle Zeile
    xub_StrLen      nCol1,nCol2;    // aktuelle Spalten (von,bis)
    BOOL            bCompiler;      // Flag fuer Compiler-Error
    BOOL            bGlobalInitErr; // Beim GlobalInit trat ein Compiler-Fehler auf
    BOOL            bRunInit;       // TRUE, wenn RunInit vom Basic aktiv ist
    String          aErrMsg;        // Puffer fuer GetErrorText()
    SbLanguageMode  eLanguageMode;  // Flag fuer Visual-Basic-Script-Modus
    SbErrorStack*   pErrStack;      // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette
    ::utl::TransliterationWrapper* pTransliterationWrapper;    // For StrComp
    BOOL            bBlockCompilerError;
    BasicManager*   pAppBasMgr;

    SbiGlobals();
    ~SbiGlobals();
};

// Utility-Makros und -Routinen

SbiGlobals* GetSbData();

#define pINST       GetSbData()->pInst
#define pMOD        GetSbData()->pMod
#define pCMOD       GetSbData()->pCompMod
#define pSBFAC      GetSbData()->pSbFac
#define pUNOFAC     GetSbData()->pUnoFac
#define pTYPEFAC    GetSbData()->pTypeFac
#define pCLASSFAC   GetSbData()->pClassFac
#define pOLEFAC     GetSbData()->pOLEFac

#endif

<|endoftext|>


<commit_before>#pragma once

#include <forward_list>
#include <iostream>
#include <memory>
#include <vector>

#include "GC/ValueObject.hpp"

namespace GC
{
    struct Object;
    template <typename T> struct Ref;

    class GC
    {
    public:
        GC() = default;
        ~GC() = default;

        static void add_to_gc(std::unique_ptr<Object> object);

        template<typename T, typename ... Params>
        static Ref<T> create(Params ... values)
        {
            auto object = new_object<T>(values...);
            auto reference = Ref<T>(object.get());
            add_to_gc(std::move(object));

            return reference;
        }

        static std::vector<Object*> get_roots();
        static void mark_objects(std::vector<Object*> roots);
        static void sweep();
        static void collect();

    private:
        static std::forward_list<std::unique_ptr<Object>> used_list;
        static unsigned int current_mark;

        struct AllocationCounter
        {
            std::uintmax_t existing { 0 };
            std::uintmax_t created { 0 };
            std::uintmax_t deleted { 0 };

            std::uintmax_t resolve()
            {
                existing += created;
                existing -= deleted;
                created = 0;
                deleted = 0;

                return existing;
            }
        };
        static AllocationCounter counter;
    };
}
<commit_msg>Removed constructor and destructor from GC<commit_after>#pragma once

#include <forward_list>
#include <iostream>
#include <memory>
#include <vector>

#include "GC/ValueObject.hpp"

namespace GC
{
    struct Object;
    template <typename T> struct Ref;

    class GC
    {
    public:
        static void add_to_gc(std::unique_ptr<Object> object);

        template<typename T, typename ... Params>
        static Ref<T> create(Params ... values)
        {
            auto object = new_object<T>(values...);
            auto reference = Ref<T>(object.get());
            add_to_gc(std::move(object));

            return reference;
        }

        static std::vector<Object*> get_roots();
        static void mark_objects(std::vector<Object*> roots);
        static void sweep();
        static void collect();

    private:
        static std::forward_list<std::unique_ptr<Object>> used_list;
        static unsigned int current_mark;

        struct AllocationCounter
        {
            std::uintmax_t existing { 0 };
            std::uintmax_t created { 0 };
            std::uintmax_t deleted { 0 };

            std::uintmax_t resolve()
            {
                existing += created;
                existing -= deleted;
                created = 0;
                deleted = 0;

                return existing;
            }
        };
        static AllocationCounter counter;
    };
}
<|endoftext|>