<commit_before>/*******************************************************************************
 * Copyright (C) ST-Ericsson SA 2011
 * License terms: 3-clause BSD license
 ******************************************************************************/

#include "lcdriver_error_codes.h"
#include "MemMappedFile.h"
#if defined(_WIN32)
#include <windows.h>
#elif (defined(__linux__) || defined(__APPLE__))
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <string.h>
using namespace std;
#else
#error "Unknown target"
#endif

#ifdef __APPLE__
#define lseek64 lseek
#endif

MemMappedFile::MemMappedFile(uint32 alignmentLength):
    size_(0),
    isMapped_(false),
    mappedData_(0),
    error_(0),
    alignmentLength_(alignmentLength),
#ifdef _WIN32
    handle_(INVALID_HANDLE_VALUE),
    memmap_(INVALID_HANDLE_VALUE)
#else
    descriptor_(-1)
#endif
{
}

MemMappedFile::~MemMappedFile()
{
#ifdef _WIN32

    if (0 != mappedData_) {
        UnmapViewOfFile(mappedData_);
    }

    if (INVALID_HANDLE_VALUE != memmap_) {
        CloseHandle(memmap_);
    }

    if (INVALID_HANDLE_VALUE != handle_) {
        CloseHandle(handle_);
    }

#else

    if (0 != mappedData_) {
        munmap(mappedData_, size_);
    }

    if (-1 != descriptor_) {
        close(descriptor_);
    }

#endif
}

int MemMappedFile::LoadFileData(const char *path)
{
    path_ = path;
#ifdef _WIN32
    handle_ = CreateFile(path_.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (INVALID_HANDLE_VALUE == handle_) {
        return FILE_OPENING_ERROR;
    }

    uint64 SizeHigh = 0;

    size_ = ::GetFileSize(handle_, (LPDWORD)&SizeHigh);
    size_ = (SizeHigh << 32) | size_;

    if (0 == size_) {
        return 0;
    }

    memmap_ = CreateFileMapping(handle_, NULL, PAGE_READONLY, 0, 0, NULL);

    if (INVALID_HANDLE_VALUE == memmap_) {
        return FILE_CREATE_MAPPING_ERROR;
    }

    mappedData_ = static_cast<uint8 *>(MapViewOfFile(memmap_, FILE_MAP_READ, 0, 0, 0));

    if (0 != mappedData_) {
        isMapped_ = true;
        volatile char tmp;

        for (uint64 i = 0; i < size_; i += 4096) {
            tmp = mappedData_[i];
        }
    } else {
        isMapped_ = false;
        CloseHandle(memmap_);
        memmap_ = INVALID_HANDLE_VALUE;
    }

#else
    descriptor_ = open(path_.c_str(), O_RDONLY);

    if (-1 == descriptor_) {
        return FILE_OPENING_ERROR;
    }

    struct stat fileStat;

    if (0 != fstat(descriptor_, &fileStat)) {
        return FILE_FAILED_TO_GET_SIZE;
    }

    size_ = fileStat.st_size;

    /* Map file in memory, BUT DON"T Reserve SWAP memory, use only physical memory */
    mappedData_ = static_cast<uint8 *>(mmap(0, size_, PROT_READ, MAP_PRIVATE | MAP_NORESERVE /*| MAP_POPULATE*/, descriptor_, 0));

    if (MAP_FAILED != mappedData_) {
        isMapped_ = true;
    } else {
        isMapped_ = false;
    }

#endif
    return 0;
}

uint8 *MemMappedFile::AllocateFileData(uint64 offset, uint64 size)
{
    if (size_ < offset + size) {
        error_ = FILE_READ_INVALID_OFFSET;
        return 0;
    }

    uint32 alignedSize = (static_cast<uint32>(size) + (alignmentLength_ - 1)) & (~(alignmentLength_ - 1));

    if (isMapped_) {
        if (size_ < offset + alignedSize) {
            uint8 *data = new uint8[alignedSize];
            memcpy(data, mappedData_ + offset, static_cast<size_t>(size));
            return data;
        } else {
            return mappedData_ + offset;
        }
    } else {
        // file is not memory mapped fall back to plain read
        uint32 readSize = static_cast<uint32>(size);
        uint8 *data = new uint8[alignedSize];
#ifdef _WIN32
        LARGE_INTEGER liOffset;
        liOffset.QuadPart = offset;

        if (!SetFilePointerEx(handle_, liOffset, NULL, FILE_BEGIN)) {
            delete[] data;
            error_ = FILE_READ_INVALID_OFFSET;
            return 0;
        }

        uint32 bytesRead;

        if (ReadFile(handle_, data, readSize, (LPDWORD)&bytesRead, NULL) && bytesRead == size) {
            return data;
        } else {
            delete[] data;
            error_ = FILE_READ_ERROR;
            return 0;
        }

#else

        if (-1 == lseek64(descriptor_, offset, SEEK_SET)) {
            delete[] data;
            error_ = FILE_READ_INVALID_OFFSET;
            return 0;
        }

        if (readSize == (uint32)read(descriptor_, data, readSize)) {
            return data;
        } else {
            delete[] data;
            error_ = FILE_READ_ERROR;
            return 0;
        }

#endif
    }
}

void MemMappedFile::ReleaseFileData(uint8 *data, uint64 offset, uint64 size)
{
    uint32 alignedSize = (static_cast<uint32>(size) + (alignmentLength_ - 1)) & (~(alignmentLength_ - 1));

    if (!isMapped_ || size_ < offset + alignedSize) {
        delete[] data;
    }
}

uint64 MemMappedFile::GetFileSize()
{
    return size_;
}

int MemMappedFile::GetError()
{
    return error_;
}
<commit_msg>Missing include.<commit_after>/*******************************************************************************
 * Copyright (C) ST-Ericsson SA 2011
 * License terms: 3-clause BSD license
 ******************************************************************************/

#include "lcdriver_error_codes.h"
#include "MemMappedFile.h"
#if defined(_WIN32)
#include <windows.h>
#elif (defined(__linux__) || defined(__APPLE__))
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>

using namespace std;
#else
#error "Unknown target"
#endif

#ifdef __APPLE__
#define lseek64 lseek
#endif

MemMappedFile::MemMappedFile(uint32 alignmentLength):
    size_(0),
    isMapped_(false),
    mappedData_(0),
    error_(0),
    alignmentLength_(alignmentLength),
#ifdef _WIN32
    handle_(INVALID_HANDLE_VALUE),
    memmap_(INVALID_HANDLE_VALUE)
#else
    descriptor_(-1)
#endif
{
}

MemMappedFile::~MemMappedFile()
{
#ifdef _WIN32

    if (0 != mappedData_) {
        UnmapViewOfFile(mappedData_);
    }

    if (INVALID_HANDLE_VALUE != memmap_) {
        CloseHandle(memmap_);
    }

    if (INVALID_HANDLE_VALUE != handle_) {
        CloseHandle(handle_);
    }

#else

    if (0 != mappedData_) {
        munmap(mappedData_, size_);
    }

    if (-1 != descriptor_) {
        close(descriptor_);
    }

#endif
}

int MemMappedFile::LoadFileData(const char *path)
{
    path_ = path;
#ifdef _WIN32
    handle_ = CreateFile(path_.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (INVALID_HANDLE_VALUE == handle_) {
        return FILE_OPENING_ERROR;
    }

    uint64 SizeHigh = 0;

    size_ = ::GetFileSize(handle_, (LPDWORD)&SizeHigh);
    size_ = (SizeHigh << 32) | size_;

    if (0 == size_) {
        return 0;
    }

    memmap_ = CreateFileMapping(handle_, NULL, PAGE_READONLY, 0, 0, NULL);

    if (INVALID_HANDLE_VALUE == memmap_) {
        return FILE_CREATE_MAPPING_ERROR;
    }

    mappedData_ = static_cast<uint8 *>(MapViewOfFile(memmap_, FILE_MAP_READ, 0, 0, 0));

    if (0 != mappedData_) {
        isMapped_ = true;
        volatile char tmp;

        for (uint64 i = 0; i < size_; i += 4096) {
            tmp = mappedData_[i];
        }
    } else {
        isMapped_ = false;
        CloseHandle(memmap_);
        memmap_ = INVALID_HANDLE_VALUE;
    }

#else
    descriptor_ = open(path_.c_str(), O_RDONLY);

    if (-1 == descriptor_) {
        return FILE_OPENING_ERROR;
    }

    struct stat fileStat;

    if (0 != fstat(descriptor_, &fileStat)) {
        return FILE_FAILED_TO_GET_SIZE;
    }

    size_ = fileStat.st_size;

    /* Map file in memory, BUT DON"T Reserve SWAP memory, use only physical memory */
    mappedData_ = static_cast<uint8 *>(mmap(0, size_, PROT_READ, MAP_PRIVATE | MAP_NORESERVE /*| MAP_POPULATE*/, descriptor_, 0));

    if (MAP_FAILED != mappedData_) {
        isMapped_ = true;
    } else {
        isMapped_ = false;
    }

#endif
    return 0;
}

uint8 *MemMappedFile::AllocateFileData(uint64 offset, uint64 size)
{
    if (size_ < offset + size) {
        error_ = FILE_READ_INVALID_OFFSET;
        return 0;
    }

    uint32 alignedSize = (static_cast<uint32>(size) + (alignmentLength_ - 1)) & (~(alignmentLength_ - 1));

    if (isMapped_) {
        if (size_ < offset + alignedSize) {
            uint8 *data = new uint8[alignedSize];
            memcpy(data, mappedData_ + offset, static_cast<size_t>(size));
            return data;
        } else {
            return mappedData_ + offset;
        }
    } else {
        // file is not memory mapped fall back to plain read
        uint32 readSize = static_cast<uint32>(size);
        uint8 *data = new uint8[alignedSize];
#ifdef _WIN32
        LARGE_INTEGER liOffset;
        liOffset.QuadPart = offset;

        if (!SetFilePointerEx(handle_, liOffset, NULL, FILE_BEGIN)) {
            delete[] data;
            error_ = FILE_READ_INVALID_OFFSET;
            return 0;
        }

        uint32 bytesRead;

        if (ReadFile(handle_, data, readSize, (LPDWORD)&bytesRead, NULL) && bytesRead == size) {
            return data;
        } else {
            delete[] data;
            error_ = FILE_READ_ERROR;
            return 0;
        }

#else

        if (-1 == lseek64(descriptor_, offset, SEEK_SET)) {
            delete[] data;
            error_ = FILE_READ_INVALID_OFFSET;
            return 0;
        }

        if (readSize == (uint32)read(descriptor_, data, readSize)) {
            return data;
        } else {
            delete[] data;
            error_ = FILE_READ_ERROR;
            return 0;
        }

#endif
    }
}

void MemMappedFile::ReleaseFileData(uint8 *data, uint64 offset, uint64 size)
{
    uint32 alignedSize = (static_cast<uint32>(size) + (alignmentLength_ - 1)) & (~(alignmentLength_ - 1));

    if (!isMapped_ || size_ < offset + alignedSize) {
        delete[] data;
    }
}

uint64 MemMappedFile::GetFileSize()
{
    return size_;
}

int MemMappedFile::GetError()
{
    return error_;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "pam_pivportal.h"

// Mockup
int pam_get_user(pam_handle_t *pamh, const char **username, const char *attr) {
    return 0;
}

TEST (write_curl_data, successisok) {
    ASSERT_EQ(write_curl_data(NULL, 5, 5, NULL), 25);
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<commit_msg>#23. added unit test for randstring<commit_after>#include <gtest/gtest.h>
#include "pam_pivportal.h"

// Mockup
int pam_get_user(pam_handle_t *pamh, const char **username, const char *attr) {
    return 0;
}

TEST (write_curl_data, successisok) {
    ASSERT_EQ(write_curl_data(NULL, 5, 5, NULL), 25);
}

TEST (randstring, successisok) {
    char *randstr = NULL;
    randstr = randstring(10);
    ASSERT_EQ(strlen(randstr), 10);
    free(randstr);
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <memory>
#include <sstream>
#include <thread>

#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/point.h"
#include "geom/rectangle.h"
#include "geom/vector.h"
#include "image/image.h"
#include "model/obj.h"
#include "node/group/simple.h"
#include "node/group/kdtree/kdtree.h"
#include "node/group/axis_selector/round_robin.h"
#include "node/group/split_strategy/centre.h"
#include "node/group/kdtree/kdtree.h"
#include "node/group/bvh.h"
#include "node/instance.h"
#include "node/solid/disc.h"
#include "node/solid/infinite_plane.h"
#include "node/solid/sphere.h"
#include "node/solid/triangle.h"
#include "renderer/parallel/parallel.h"
#include "renderer/serial/serial.h"
#include "renderer/settings.h"
#include "supersampling/random.h"
#include "world/world.h"

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(800, 600));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(800, 600));
	settings.max_thread_count = std::thread::hardware_concurrency();
	settings.tile_size = Vector2i(100, 100);
	settings.max_sample_count = 2;
	settings.adaptive_sample_step = 10;

	CosineDebuggerEngine engine;
	ParallelRenderer renderer;
	RandomSuperSampling super_sampling(true);

	PerspectiveCamera camera(
		Point3(0.0, 0.75, -4.5),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		Rectangle(Point2i(0, 0), Vector2i(80, 60)).get_aspect_ratio(),
		M_PI/2.0f);

	ObjModel cow_model;
	BVH cow_bvh(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 520, 8);
	Instance cow(&cow_bvh);

	cow_model.load("mdl/cow.obj");
	cow_model.add_to_group(cow_bvh);
	cow_bvh.finish();
	cow.rotate(Vector3(0.0f, 0.0f, 1.0f), M_PI/4.0f);
	cow.rotate(Vector3(0.0f, 1.0f, 0.0f), M_PI/2.0f);
	cow.rotate(Vector3(0.0f, 0.0f, 1.0f), M_PI/2.0f);
	cow.rotate(Vector3(0.0f, 1.0f, 0.0f), M_PI/3.5f);
	cow.translate(Vector3(-3.5f, -2.0f, 0.0f));

	InfinitePlane plane(Point3(0.0f, -3.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));

	SimpleGroup scene;
	scene.add(&cow);
	scene.add(&plane);

	World world;
	world.scene = &scene;
	world.camera = &camera;

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write_png(std::string("cow.png"));

	return 0;
}

<commit_msg>Removed kdtree include; lowered sample count<commit_after>#include <cmath>
#include <iostream>
#include <memory>
#include <sstream>
#include <thread>

#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/point.h"
#include "geom/rectangle.h"
#include "geom/vector.h"
#include "image/image.h"
#include "model/obj.h"
#include "node/group/simple.h"
#include "node/group/axis_selector/round_robin.h"
#include "node/group/split_strategy/centre.h"
#include "node/group/bvh.h"
#include "node/instance.h"
#include "node/solid/disc.h"
#include "node/solid/infinite_plane.h"
#include "node/solid/sphere.h"
#include "node/solid/triangle.h"
#include "renderer/parallel/parallel.h"
#include "renderer/serial/serial.h"
#include "renderer/settings.h"
#include "supersampling/random.h"
#include "world/world.h"

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(800, 600));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(800, 600));
	settings.max_thread_count = std::thread::hardware_concurrency();
	settings.tile_size = Vector2i(100, 100);
	settings.max_sample_count = 1;
	settings.adaptive_sample_step = 10;

	CosineDebuggerEngine engine;
	ParallelRenderer renderer;
	RandomSuperSampling super_sampling(true);

	PerspectiveCamera camera(
		Point3(0.0, 0.75, -4.5),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		Rectangle(Point2i(0, 0), Vector2i(80, 60)).get_aspect_ratio(),
		M_PI/2.0f);

	ObjModel cow_model;
	BVH cow_bvh(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 520, 8);
	Instance cow(&cow_bvh);

	cow_model.load("mdl/cow.obj");
	cow_model.add_to_group(cow_bvh);
	cow_bvh.finish();
	cow.rotate(Vector3(0.0f, 0.0f, 1.0f), M_PI/4.0f);
	cow.rotate(Vector3(0.0f, 1.0f, 0.0f), M_PI/2.0f);
	cow.rotate(Vector3(0.0f, 0.0f, 1.0f), M_PI/2.0f);
	cow.rotate(Vector3(0.0f, 1.0f, 0.0f), M_PI/3.5f);
	cow.translate(Vector3(-3.5f, -2.0f, 0.0f));

	InfinitePlane plane(Point3(0.0f, -3.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));

	SimpleGroup scene;
	scene.add(&cow);
	scene.add(&plane);

	World world;
	world.scene = &scene;
	world.camera = &camera;

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write_png(std::string("cow.png"));

	return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: refbase.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:14:18 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef CONNECTIVITY_DBTOOLS_REFBASE_HXX
#include "refbase.hxx"
#endif

//........................................................................
namespace connectivity
{
//........................................................................

    //================================================================
    //= ORefBase
    //================================================================
    //----------------------------------------------------------------
    ORefBase::~ORefBase()
    {
    }

    //----------------------------------------------------------------
    oslInterlockedCount SAL_CALL ORefBase::acquire()
    {
        return osl_incrementInterlockedCount(&m_refCount);
    }

    //----------------------------------------------------------------
    oslInterlockedCount SAL_CALL ORefBase::release()
    {
        oslInterlockedCount nNewRefCount = osl_decrementInterlockedCount(&m_refCount);
        if (0 == nNewRefCount)
            delete this;

        return nNewRefCount;
    }

//........................................................................
}   // namespace connectivity
//........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.4.216); FILE MERGED 2008/04/01 10:53:49 thb 1.4.216.2: #i85898# Stripping all external header guards 2008/03/28 15:24:41 rt 1.4.216.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: refbase.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "refbase.hxx"

//........................................................................
namespace connectivity
{
//........................................................................

    //================================================================
    //= ORefBase
    //================================================================
    //----------------------------------------------------------------
    ORefBase::~ORefBase()
    {
    }

    //----------------------------------------------------------------
    oslInterlockedCount SAL_CALL ORefBase::acquire()
    {
        return osl_incrementInterlockedCount(&m_refCount);
    }

    //----------------------------------------------------------------
    oslInterlockedCount SAL_CALL ORefBase::release()
    {
        oslInterlockedCount nNewRefCount = osl_decrementInterlockedCount(&m_refCount);
        if (0 == nNewRefCount)
            delete this;

        return nNewRefCount;
    }

//........................................................................
}   // namespace connectivity
//........................................................................

<|endoftext|>


<commit_before>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include "main.h"
using namespace std;

pid_t wpid = 0;
pid_t fpid = 0;
static void sigHandle(int sig, siginfo_t *Info, void *Pointer);
int main() {
	string userinput;
	string login = getlogin();
	if(login == "")
		perror("getlogin");
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	bool ext  = false;
	string exit_status = "exit";
	struct sigaction Curr;
	struct sigaction Prev;
	sigset_t x;
	Curr.sa_mask = x;
	Curr.sa_sigaction = sigHandle;
	Curr.sa_flags = 0;
	Prev.sa_flags = 0;
	string directory_a = "";
	if(sigaction(SIGINT, &Curr, &Prev) == -1)
		perror("SIGINT sigaction");
	if(sigaction(SIGTSTP, &Curr, &Prev) == -1)
		perror("SIGTSTP sigaction");
	if(sigaction(SIGCHLD, &Curr, &Prev) == -1)
		perror("SIGCHLD sigaction");
	while(!ext) {
		char *pPath, *hHome;
		if((pPath = getenv("PWD")) == NULL)
			perror("first.1 getenv");
		if((hHome = getenv("HOME")) == NULL)
			perror("first.2 getenv");
		string PPath(pPath), HHome(hHome);
		if(PPath.find(HHome) != string::npos) {
			PPath.erase(PPath.begin(), PPath.begin() + HHome.size());
			PPath.insert(PPath.begin(), '~');
		}
		cout << login << "@" << hostname << PPath << " $ ";
		char *command_a;
		char *command;
		cin.clear();
		getline(cin, userinput);
		if(userinput.find("#") != string::npos)
			userinput.erase(userinput.find("#"), userinput.size());
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		bool multiple = false;
		if(userinput.size() != 0)
			connectors(userinput, c_pat, c_pos, first, multiple);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[50000];
		int status;
		redir condition;
		if(userinput.size() != 0) {
			while(userinput.substr(x, 1) != "") {
				if(multiple) {
					cout << "Error: Incorrect connector config" << endl;
					break;
				}
				if(first) {
					cout << "Error: file does not exist" << endl;
					break;
				}
				redir_check(condition, userinput.substr(x, c_pos.at(y) -x).c_str());
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
				command_a = strtok(command, "&;| \t");
				while(command_a != NULL) {
					arg[b] = command_a;
					command_a = strtok(NULL, "&;| \t");
					b++;
				}
				if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
					ext = true;
					break;
				}
				if(condition.redir_x) {
					redir_action(condition);
					nullify(condition);
				}
				else if(strcmp(arg[0], "cd") == 0) {
					if(b == 1) {
						char *home, *old;
						if((home = getenv("HOME")) == NULL)
							perror("getenv_1.1");
						if((old = getenv("PWD")) == NULL)
							perror("getenv_1.2");
						if(chdir(home) == -1)
							perror("chdir_1");
						if(setenv("PWD", home, 1) == -1)
							perror("setenv_1.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_1.2");
					}
					else if(strcmp(arg[1], "-") == 0) {
						char *old, *newDir;
						if((old = getenv("PWD")) == NULL)
							perror("getenv_2.1");
						if((newDir = getenv("OLDPWD")) == NULL)
							perror("getenv_2.2");
						if(chdir(newDir) == -1)
							perror("chdr_2");
						if(setenv("PWD", newDir, 1) == -1)
							perror("setenv_2.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_2.2");
					}
					else if(strrchr(arg[1], '~') != NULL) {
						if(strlen(arg[1]) == 1) {
							char *old, *home;
							if((old = getenv("PWD")) == NULL)
								perror("~ getenv1");
							if((home = getenv("HOME")) == NULL)
								perror("~ getenv2");
							if((chdir(home)) == -1)
								perror("~ chdir");
							if(setenv("OLDPWD", old, 1) == -1)
								perror("~ setenv_1");
							if(setenv("PWD", home, 1) == -1)
								perror("~ setenv_1");
						}
						else {
							char *old, *home;
							if((old = getenv("PWD")) == NULL)
								perror("~-- getenv1");
							if((home = getenv("HOME")) == NULL)
								perror("~-- getenv2");
							string ndir(home), argu(arg[1]);
							argu.erase(argu.begin());
							ndir = ndir + argu;
							if((chdir(ndir.c_str())) == -1) {
								perror("~-- chdir");
								if(chdir(old) == -1)
									perror("chdir 1");
								if(setenv("OLDPWD", old, 1) == -1)
									perror("~-- setenv1");
								if(setenv("PWD", old, 1) == -1)
									perror("~-- setenvr2");

							}
							else {
								if(setenv("OLDPWD", old, 1) == -1)
									perror("~-- setenv1");
								if(setenv("PWD", ndir.c_str(), 1) == -1)
									perror("~-- setenvr2");
							}
						}
					}
					else {
						char *old;
						if((old = getenv("PWD")) == NULL)
							perror("getenv_3.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_3.1");
						if(chdir(arg[1]) == -1) {
							perror("chdir_3");
							if(chdir(old) == -1)
								perror("chdir 2");
							if(setenv("PWD", old, 1) == -1)
								perror("setenv 4");
						}
						else {string newEnv(old);
							string newDir(arg[1]);
							if(strcmp(arg[1],"..") != 0) {
								string g(arg[1]);
								directory_a = g;
								newEnv = newEnv + "/" + newDir;
							}
							else if(strcmp(arg[1], "..") == 0) {
								char *temp;
								if((temp = getenv("PWD")) == NULL)
									perror(".. getenv");
								string g(temp);
								while(g.at(g.size() - 1) != '/')
									g.erase(g.size() - 1);
								g.erase(g.size() - 1);
								newEnv = g;
							}
							if(setenv("PWD", newEnv.c_str(), 1) == -1)
								perror("setenv_3.2");
						}
					}

				}
				else {
					fpid = fork();
					if(fpid == -1)
						perror("fork");
					if(fpid == 0) {
						if(execvp(arg[0], arg) == -1) {
							perror("execvp");
							exit(-1);
						}
						exit(0);
					}
					do {
						wpid = wait(&status);
					} while (wpid == -1 && errno == EINTR);
					if(wpid == -1) {
						perror("wait error");
						exit(-1);
					}
				}
				x = c_pos.at(y);
				unsigned int help = c_pat.at(y);
				for(unsigned int i = 0; i < b; i++)
					arg[i] = NULL;
				if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2)
					y++;
				else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos)) {
					x = c_pos.at(y + 1);
					y+=2;
				}
				else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos)) {
					x = c_pos.at(y + 1);
					y+=2;
				}
				else
					break;
				b = 0;
			}
		}
		delete []command;
	}
	return 0;
}
static void sigHandle(int sig, siginfo_t *Info, void *Pointer) {
	if(sig == SIGINT) {
		cout << Info->si_pid - Info->si_pid << Pointer;
		cout << "C" << endl;
		return;
	}
	else if (sig == SIGTSTP) {
		if(fpid == 0) {
		//	kill(fpid, SIGSTOP);
			raise(SIGSTOP);
			cout << endl;
		}
	}
	else {
	//	cout << "not a valid signal" << endl;
		return;
	}
}
<commit_msg>gave up on ctrl z, fixed cd .<commit_after>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include "main.h"
using namespace std;

pid_t wpid = 0;
pid_t fpid = 0;
static void sigHandle(int sig, siginfo_t *Info, void *Pointer);
int main() {
	string userinput;
	string login = getlogin();
	if(login == "")
		perror("getlogin");
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	bool ext  = false;
	string exit_status = "exit";
	struct sigaction Curr;
	struct sigaction Prev;
	sigset_t x;
	Curr.sa_mask = x;
	Curr.sa_sigaction = sigHandle;
	Curr.sa_flags = 0;
	Prev.sa_flags = 0;
	string directory_a = "";
	if(sigaction(SIGINT, &Curr, &Prev) == -1)
		perror("SIGINT sigaction");
	if(sigaction(SIGTSTP, &Curr, &Prev) == -1)
		perror("SIGTSTP sigaction");
	if(sigaction(SIGCHLD, &Curr, &Prev) == -1)
		perror("SIGCHLD sigaction");
	while(!ext) {
		char *pPath, *hHome;
		if((pPath = getenv("PWD")) == NULL)
			perror("first.1 getenv");
		if((hHome = getenv("HOME")) == NULL)
			perror("first.2 getenv");
		string PPath(pPath), HHome(hHome);
		if(PPath.find(HHome) != string::npos) {
			PPath.erase(PPath.begin(), PPath.begin() + HHome.size());
			PPath.insert(PPath.begin(), '~');
		}
		cout << login << "@" << hostname << ":" <<  PPath << " $ ";
		char *command_a;
		char *command;
		cin.clear();
		getline(cin, userinput);
		if(userinput.find("#") != string::npos)
			userinput.erase(userinput.find("#"), userinput.size());
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		bool multiple = false;
		if(userinput.size() != 0)
			connectors(userinput, c_pat, c_pos, first, multiple);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[50000];
		int status;
		redir condition;
		if(userinput.size() != 0) {
			while(userinput.substr(x, 1) != "") {
				if(multiple) {
					cout << "Error: Incorrect connector config" << endl;
					break;
				}
				if(first) {
					cout << "Error: file does not exist" << endl;
					break;
				}
				redir_check(condition, userinput.substr(x, c_pos.at(y) -x).c_str());
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
				command_a = strtok(command, "&;| \t");
				while(command_a != NULL) {
					arg[b] = command_a;
					command_a = strtok(NULL, "&;| \t");
					b++;
				}
				if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
					ext = true;
					break;
				}
				if(condition.redir_x) {
					redir_action(condition);
					nullify(condition);
				}
				else if(strcmp(arg[0], "cd") == 0) {
					if(b == 1) {
						char *home, *old;
						if((home = getenv("HOME")) == NULL)
							perror("getenv_1.1");
						if((old = getenv("PWD")) == NULL)
							perror("getenv_1.2");
						if(chdir(home) == -1)
							perror("chdir_1");
						if(setenv("PWD", home, 1) == -1)
							perror("setenv_1.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_1.2");
					}
					else if(strcmp(arg[1], "-") == 0) {
						char *old, *newDir;
						if((old = getenv("PWD")) == NULL)
							perror("getenv_2.1");
						if((newDir = getenv("OLDPWD")) == NULL)
							perror("getenv_2.2");
						if(chdir(newDir) == -1)
							perror("chdr_2");
						if(setenv("PWD", newDir, 1) == -1)
							perror("setenv_2.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_2.2");
					}
					else if(strrchr(arg[1], '~') != NULL) {
						if(strlen(arg[1]) == 1) {
							char *old, *home;
							if((old = getenv("PWD")) == NULL)
								perror("~ getenv1");
							if((home = getenv("HOME")) == NULL)
								perror("~ getenv2");
							if((chdir(home)) == -1)
								perror("~ chdir");
							if(setenv("OLDPWD", old, 1) == -1)
								perror("~ setenv_1");
							if(setenv("PWD", home, 1) == -1)
								perror("~ setenv_1");
						}
						else {
							char *old, *home;
							if((old = getenv("PWD")) == NULL)
								perror("~-- getenv1");
							if((home = getenv("HOME")) == NULL)
								perror("~-- getenv2");
							string ndir(home), argu(arg[1]);
							argu.erase(argu.begin());
							ndir = ndir + argu;
							if((chdir(ndir.c_str())) == -1) {
								perror("~-- chdir");
								if(chdir(old) == -1)
									perror("chdir 1");
								if(setenv("OLDPWD", old, 1) == -1)
									perror("~-- setenv1");
								if(setenv("PWD", old, 1) == -1)
									perror("~-- setenvr2");

							}
							else {
								if(setenv("OLDPWD", old, 1) == -1)
									perror("~-- setenv1");
								if(setenv("PWD", ndir.c_str(), 1) == -1)
									perror("~-- setenvr2");
							}
						}
					}
					else if(strcmp(arg[1], ".") == 0) {
						char *rem;
						if((rem = getenv("PWD")) == NULL)
							perror(". getenv");
						if(setenv("OLDPWD", rem, 1) == -1)
							perror(". setenv1");
						if(setenv("PWD", rem, 1) == -1)
							perror(". setenv2");
					}
					else {
						char *old;
						if((old = getenv("PWD")) == NULL)
							perror("getenv_3.1");
						if(setenv("OLDPWD", old, 1) == -1)
							perror("setenv_3.1");
						if(chdir(arg[1]) == -1) {
							perror("chdir_3");
							if(chdir(old) == -1)
								perror("chdir 2");
							if(setenv("PWD", old, 1) == -1)
								perror("setenv 4");
						}
						else {string newEnv(old);
							string newDir(arg[1]);
							if(strcmp(arg[1],"..") != 0) {
								string g(arg[1]);
								directory_a = g;
								newEnv = newEnv + "/" + newDir;
							}
							else if(strcmp(arg[1], "..") == 0) {
								char *temp;
								if((temp = getenv("PWD")) == NULL)
									perror(".. getenv");
								string g(temp);
								while(g.at(g.size() - 1) != '/')
									g.erase(g.size() - 1);
								g.erase(g.size() - 1);
								newEnv = g;
							}
							if(setenv("PWD", newEnv.c_str(), 1) == -1)
								perror("setenv_3.2");
						}
					}

				}
				else {
					int i = fork();
					fpid = i;
					cout << fpid << endl;
					if(i == -1)
						perror("fork");
					if(i == 0) {
						if(execvp(arg[0], arg) == -1) {
							perror("execvp");
							exit(-1);
						}
						exit(0);
					}
					do {
						wpid = wait(&status);
					} while (wpid == -1 && errno == EINTR);
					if(wpid == -1) {
						perror("wait error");
						exit(-1);
					}
				}
				x = c_pos.at(y);
				unsigned int help = c_pat.at(y);
				for(unsigned int i = 0; i < b; i++)
					arg[i] = NULL;
				if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2)
					y++;
				else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos)) {
					x = c_pos.at(y + 1);
					y+=2;
				}
				else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos)) {
					x = c_pos.at(y + 1);
					y+=2;
				}
				else
					break;
				b = 0;
			}
		}
		delete []command;
	}
	return 0;
}
static void sigHandle(int sig, siginfo_t *Info, void *Pointer) {
	if(sig == SIGINT) {
		if(fpid != 0) {
			kill(fpid, SIGKILL);
		}
		cout << Info->si_pid - Info->si_pid << Pointer;
		cout << "C" << endl;
	}
	else if (sig == SIGTSTP) {
		cout << fpid << endl;
		if(fpid == 0) {
			return;
		}
		kill(-(fpid), SIGTSTP);
		cout << fpid << endl;
	}
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>

#include <string>
#include <math.h>

#include "dmath/geometry.h"

static const float tol = 0.000000000000001f;

double magnitude(double vec[3]){
    return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}

void normalize(double vec[3]){
    float m = magnitude(vec);
    if(tol >= m) m = 1;
    vec[0] /= m;
    vec[1] /= m;
    vec[2] /= m;

    if(fabs(vec[0]) < tol) vec[0] = 0.0f;
    if(fabs(vec[1]) < tol) vec[1] = 0.0f;
    if(fabs(vec[2]) < tol) vec[2] = 0.0f;
}

class ArtificialPotentialField{
public:
    ArtificialPotentialField(ros::NodeHandle &node) :
        base_link_("base_link"),
        cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
        obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))

    {
        for(int i=0; i < 3; i++) obs_[i] = 0;
    }

    void spin(){
        ros::Rate r(10);

        ros::Duration(1).sleep();
        geometry_msgs::Twist cmd;
        cmd.linear.z = 0.15;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        cmd.linear.z = 0;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        const double force = 0.025;

        while(ros::ok()){
            double Fs[3];
            Fs[0] = Fs[1] = Fs[2] = 0;

            double f_in[3];
            get_potential_force(obs_, f_in, 0, 3, 1, 2.0);

            Fs[0] += f_in[0];
            Fs[1] += f_in[1];
            Fs[2] += f_in[2];

            double g[3];
            g[0] = 0;
            g[1] = 0;
            g[2] = 0;

            get_potential_force(g, f_in, 2, 0, 1.5, 1);

            Fs[0] += f_in[0];
            Fs[1] += f_in[1];
            Fs[2] += f_in[2];

            cmd.linear.x = Fs[1] * force;
            //cmd.linear.y = Fs[1] * force;

            ROS_INFO("obs = (%f, %f)", obs_[0], obs_[1]);
            ROS_INFO_STREAM("cmd = " << cmd);
            cmd_pub_.publish(cmd);
            r.sleep();
            ros::spinOnce();
        }
    }

private:
    void get_potential_force(double dest_lc[3], double f_out[3], double A = 1, double B = 1, double n = 1, double m = 1){
        double u[3];
        u[0] = dest_lc[0];
        u[1] = dest_lc[1];
        u[2] = dest_lc[2];
        normalize(u);

        const double d = magnitude(dest_lc);
        double U = 0;
        if(fabs(d) > tol){
            U = -A/pow(d, n) + B/pow(d, m);
        }

        f_out[0] = U * u[0];
        f_out[1] = U * u[1];
        f_out[2] = U * u[2];
    }

    void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){
        sensor_msgs::PointCloud obs_lsr, obs_base;
        sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr);
        tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base);

        if(obs_base.points.size() == 0){
            obs_[0] = 0;
            obs_[1] = 0;
            obs_[2] = 0;
            return;
        }

        double min_obs[3];
        min_obs[0] = obs_base.points[0].x;
        min_obs[1] = obs_base.points[0].y;
        min_obs[2] = obs_base.points[0].z;

        float min_dist = magnitude(min_obs);

        for(int i=1; i < obs_base.points.size(); i++){
            double obs[3];
            obs[0] = obs_base.points[i].x;
            obs[1] = obs_base.points[i].y;
            obs[2] = obs_base.points[i].z;

            //ROS_INFO("(%f, %f)", obs[0], obs[1]);

            double dist = magnitude(obs);
            if(dist < min_dist){
                min_obs[0] = obs[0];
                min_obs[1] = obs[1];
                min_obs[2] = obs[2];
                min_dist = dist;
            }
        }

        obs_[0] = min_obs[0];
        obs_[1] = min_obs[1];
        obs_[2] = min_obs[2];
    }

    double obs_[3];
    ros::Publisher cmd_pub_;
    ros::Subscriber obs_sub_;
    tf::TransformListener tf_listener_;
    std::string base_link_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, "apf_planner");

    ros::NodeHandle node;
    ArtificialPotentialField apf(node);
    apf.spin();

    return 0;
}

<commit_msg>Use dmath tools<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>

#include <string>
#include <math.h>

#include "dmath/geometry.h"

class ArtificialPotentialField{
public:
    ArtificialPotentialField(ros::NodeHandle &node) :
        base_link_("base_link"),
        cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
        obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))

    {
        for(int i=0; i < 3; i++) obs_[i] = 0;
    }

    void spin(){
        ros::Rate r(10);

        ros::Duration(1).sleep();
        geometry_msgs::Twist cmd;
        cmd.linear.z = 0.15;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        cmd.linear.z = 0;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        const double force = 0.025;

        while(ros::ok()){
            dmath::Vector3D Fs;
            Fs += get_potential_force(obs_, 0, 3, 1, 2.0);

            dmath::Vector3D g;
            Fs += get_potential_force(g, 2, 0, 1.5, 1);

            dmath::Vector3D vel = Fs * force;
            //cmd.linear.x = Fs[1] * force;
            //cmd.linear.y = Fs[1] * force;

            ROS_INFO("obs = (%f, %f)", obs_.x, obs_.y);
            ROS_INFO_STREAM("cmd = " << cmd);
            cmd_pub_.publish(cmd);
            r.sleep();
            ros::spinOnce();
        }
    }

private:
    Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
        Vector3D u = dest_lc;
        normalize(u);

        const double d = magnitude(dest_lc);
        double U = 0;
        if(fabs(d) > dmath::tol){
            U = -A/pow(d, n) + B/pow(d, m);
        }

        return U * u;
    }

    void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){
        sensor_msgs::PointCloud obs_lsr, obs_base;
        sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr);
        tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base);

        if(obs_base.points.size() == 0){
            obs_[0] = 0;
            obs_[1] = 0;
            obs_[2] = 0;
            return;
        }

        double min_obs[3];
        min_obs[0] = obs_base.points[0].x;
        min_obs[1] = obs_base.points[0].y;
        min_obs[2] = obs_base.points[0].z;

        float min_dist = magnitude(min_obs);

        for(int i=1; i < obs_base.points.size(); i++){
            double obs[3];
            obs[0] = obs_base.points[i].x;
            obs[1] = obs_base.points[i].y;
            obs[2] = obs_base.points[i].z;

            //ROS_INFO("(%f, %f)", obs[0], obs[1]);

            double dist = magnitude(obs);
            if(dist < min_dist){
                min_obs[0] = obs[0];
                min_obs[1] = obs[1];
                min_obs[2] = obs[2];
                min_dist = dist;
            }
        }

        obs_[0] = min_obs[0];
        obs_[1] = min_obs[1];
        obs_[2] = min_obs[2];
    }

    dmath::Vector3D obs_;
    ros::Publisher cmd_pub_;
    ros::Subscriber obs_sub_;
    tf::TransformListener tf_listener_;
    std::string base_link_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, "apf_planner");

    ros::NodeHandle node;
    ArtificialPotentialField apf(node);
    apf.spin();

    return 0;
}

<|endoftext|>


<commit_before>#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QTimer>
#include <QThreadPool>

#include "seafile-applet.h"
#include "ui/tray-icon.h"
#include "configurator.h"
#include "account-mgr.h"
#include "rpc/rpc-client.h"
#include "rpc/local-repo.h"
#include "utils/file-utils.h"
#include "utils/utils.h"
#include "utils/uninstall-helpers.h"
#include "data-mgr.h"
#include "tasks.h"
#include "transfer-mgr.h"

#include "auto-update-mgr.h"

namespace {

const char *kFileCacheTopDirName = "file-cache";
const char *kFileCacheTempTopDirName = "file-cache-tmp";
const char *kFileCacheDBFileName = "file-cache.db";

inline bool addPath(QFileSystemWatcher *watcher, const QString &file) {
  if (watcher->files().contains(file))
      return true;
  bool ret = watcher->addPath(file);
  if (!ret) {
      qWarning("[AutoUpdateManager] failed to watch cache file %s", file.toUtf8().data());
  }
  return ret;
}

inline bool removePath(QFileSystemWatcher *watcher, const QString &file) {
  if (!watcher->files().contains(file))
      return true;
  bool ret = watcher->removePath(file);
  if (!ret) {
      qWarning("[AutoUpdateManager] failed to remove watch on cache file %s", file.toUtf8().data());
  }
  return ret;
}
} // anonymous namespace

SINGLETON_IMPL(AutoUpdateManager)

AutoUpdateManager::AutoUpdateManager()
{
    connect(&watcher_, SIGNAL(fileChanged(const QString&)),
            this, SLOT(onFileChanged(const QString&)));
}

void AutoUpdateManager::start()
{
    cleanCachedFile();
}

void AutoUpdateManager::watchCachedFile(const Account& account,
                                        const QString& repo_id,
                                        const QString& path)
{
    QString local_path = DataManager::getLocalCacheFilePath(repo_id, path);
    qDebug("[AutoUpdateManager] watch cache file %s", local_path.toUtf8().data());
    if (!QFileInfo(local_path).exists()) {
        qWarning("[AutoUpdateManager] unable to watch non-existent cache file %s", local_path.toUtf8().data());
        return;
    }

    // do we have it in deferred list ?
    // skip if yes
    Q_FOREACH(const WatchedFileInfo& info, deleted_files_infos_)
    {
        if (repo_id == info.repo_id && path == info.path_in_repo)
            return;
    }

    addPath(&watcher_, local_path);
    watch_infos_[local_path] = WatchedFileInfo(account, repo_id, path);
}

void AutoUpdateManager::cleanCachedFile()
{
    qDebug("[AutoUpdateManager] cancel all download tasks");
    TransferManager::instance()->cancelAllDownloadTasks();

    const Account cur_account = seafApplet->accountManager()->currentAccount();
    foreach(const QString& key, watch_infos_.keys()) {
        if (watch_infos_[key].account == cur_account)
            watch_infos_.remove(key);
    }

    FileCache::instance()->cleanCurrentAccountCache();

    CachedFilesCleaner *cleaner = new CachedFilesCleaner();
    QThreadPool::globalInstance()->start(cleaner);
}

void AutoUpdateManager::onFileChanged(const QString& local_path)
{
    qDebug("[AutoUpdateManager] detected cache file %s changed", local_path.toUtf8().data());
#ifdef Q_OS_MAC
    if (MacImageFilesWorkAround::instance()->isRecentOpenedImage(local_path)) {
        return;
    }
#endif
    removePath(&watcher_, local_path);
    QString repo_id, path_in_repo;
    if (!watch_infos_.contains(local_path)) {
        // filter unwanted events
        return;
    }

    WatchedFileInfo &info = watch_infos_[local_path];

    if (!QFileInfo(local_path).exists()) {
        qDebug("[AutoUpdateManager] detected cache file %s renamed or removed", local_path.toUtf8().data());
        WatchedFileInfo deferred_info = info;
        removeWatch(local_path);
        // Some application would deleted and recreate the file when saving.
        // We work around that by double checking whether the file gets
        // recreated after a short period
        QTimer::singleShot(5000, this, SLOT(checkFileRecreated()));
        deleted_files_infos_.enqueue(deferred_info);
        return;
    }

    DataManager data_mgr(info.account);
    FileNetworkTask *task = data_mgr.createUploadTask(
        info.repo_id, ::getParentPath(info.path_in_repo),
        local_path, ::getBaseName(local_path), true);

    connect(task, SIGNAL(finished(bool)),
            this, SLOT(onUpdateTaskFinished(bool)));

    qDebug("[AutoUpdateManager] start uploading new version of file %s", local_path.toUtf8().data());

    task->start();
    info.uploading = true;
}

void AutoUpdateManager::onUpdateTaskFinished(bool success)
{
    FileUploadTask *task = qobject_cast<FileUploadTask *>(sender());
    if (task == NULL)
        return;
    const QString local_path = task->localFilePath();
    if (success) {
        qDebug("[AutoUpdateManager] uploaded new version of file %s", local_path.toUtf8().data());
        seafApplet->trayIcon()->showMessage(tr("Upload Success"),
                                            tr("File \"%1\"\nuploaded successfully.").arg(QFileInfo(local_path).fileName()),
                                            task->repoId());
        emit fileUpdated(task->repoId(), task->path());
        addPath(&watcher_, local_path);
        WatchedFileInfo& info = watch_infos_[local_path];
        info.uploading = false;
    } else {
        qWarning("[AutoUpdateManager] failed to upload new version of file %s", local_path.toUtf8().data());
        seafApplet->trayIcon()->showMessage(tr("Upload Failure"),
                                            tr("File \"%1\"\nfailed to upload.").arg(QFileInfo(local_path).fileName()),
                                            task->repoId());
        watch_infos_.remove(local_path);
        return;
    }
}

void AutoUpdateManager::removeWatch(const QString& local_path)
{
    watch_infos_.remove(local_path);
    removePath(&watcher_, local_path);
}

void AutoUpdateManager::checkFileRecreated()
{
    if (deleted_files_infos_.isEmpty()) {
        // impossible
        return;
    }

    const WatchedFileInfo info = deleted_files_infos_.dequeue();
    const QString path = DataManager::getLocalCacheFilePath(info.repo_id, info.path_in_repo);
    if (QFileInfo(path).exists()) {
        qDebug("[AutoUpdateManager] detected recreated file %s", path.toUtf8().data());
        addPath(&watcher_, path);
        watch_infos_[path] = info;
        // Some applications like MSOffice would remove the original file and
        // recreate it when the user modifies the file.
        onFileChanged(path);
    }
}

#ifdef Q_OS_MAC
SINGLETON_IMPL(MacImageFilesWorkAround)

MacImageFilesWorkAround::MacImageFilesWorkAround()
{
}

void MacImageFilesWorkAround::fileOpened(const QString& path)
{
    QString mimetype = ::mimeTypeFromFileName(path);
    if (mimetype.startsWith("image") || mimetype == "application/pdf") {
        images_[path] = QDateTime::currentMSecsSinceEpoch();
    }
}

bool MacImageFilesWorkAround::isRecentOpenedImage(const QString& path)
{
    qint64 ts = images_.value(path, 0);
    if (QDateTime::currentMSecsSinceEpoch() < ts + 1000 * 10) {
        return true;
    } else {
        return false;
    }
}
#endif

CachedFilesCleaner::CachedFilesCleaner()
{
}

void CachedFilesCleaner::run()
{
    QString file_cache_dir = pathJoin(seafApplet->configurator()->seafileDir(),
                               kFileCacheTopDirName);
    QString file_cache_tmp_dir = pathJoin(seafApplet->configurator()->seafileDir(),
                                   kFileCacheTempTopDirName);
    QString file_cache_db_file = pathJoin(seafApplet->configurator()->seafileDir(),
                                   kFileCacheDBFileName);

    qDebug("[AutoUpdateManager] removing cached files");
    if (QFile(file_cache_db_file).exists()) {
        if (!QFile(file_cache_db_file).remove()) {
            qWarning("[AutoUpdateManager] failed to remove db file");
        }
    }
    if (QDir(file_cache_tmp_dir).exists()) {
        delete_dir_recursively(file_cache_tmp_dir);
    }
    if (QDir(file_cache_dir).exists()) {
        QDir().rename(file_cache_dir, file_cache_tmp_dir);
        delete_dir_recursively(file_cache_tmp_dir);
    }
}
<commit_msg>CFB: auto update should watch cached files after upload fails<commit_after>#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QTimer>
#include <QThreadPool>

#include "seafile-applet.h"
#include "ui/tray-icon.h"
#include "configurator.h"
#include "account-mgr.h"
#include "rpc/rpc-client.h"
#include "rpc/local-repo.h"
#include "utils/file-utils.h"
#include "utils/utils.h"
#include "utils/uninstall-helpers.h"
#include "data-mgr.h"
#include "tasks.h"
#include "transfer-mgr.h"

#include "auto-update-mgr.h"

namespace {

const char *kFileCacheTopDirName = "file-cache";
const char *kFileCacheTempTopDirName = "file-cache-tmp";
const char *kFileCacheDBFileName = "file-cache.db";

inline bool addPath(QFileSystemWatcher *watcher, const QString &file) {
  if (watcher->files().contains(file))
      return true;
  bool ret = watcher->addPath(file);
  if (!ret) {
      qWarning("[AutoUpdateManager] failed to watch cache file %s", file.toUtf8().data());
  }
  return ret;
}

inline bool removePath(QFileSystemWatcher *watcher, const QString &file) {
  if (!watcher->files().contains(file))
      return true;
  bool ret = watcher->removePath(file);
  if (!ret) {
      qWarning("[AutoUpdateManager] failed to remove watch on cache file %s", file.toUtf8().data());
  }
  return ret;
}
} // anonymous namespace

SINGLETON_IMPL(AutoUpdateManager)

AutoUpdateManager::AutoUpdateManager()
{
    connect(&watcher_, SIGNAL(fileChanged(const QString&)),
            this, SLOT(onFileChanged(const QString&)));
}

void AutoUpdateManager::start()
{
    cleanCachedFile();
}

void AutoUpdateManager::watchCachedFile(const Account& account,
                                        const QString& repo_id,
                                        const QString& path)
{
    QString local_path = DataManager::getLocalCacheFilePath(repo_id, path);
    qDebug("[AutoUpdateManager] watch cache file %s", local_path.toUtf8().data());
    if (!QFileInfo(local_path).exists()) {
        qWarning("[AutoUpdateManager] unable to watch non-existent cache file %s", local_path.toUtf8().data());
        return;
    }

    // do we have it in deferred list ?
    // skip if yes
    Q_FOREACH(const WatchedFileInfo& info, deleted_files_infos_)
    {
        if (repo_id == info.repo_id && path == info.path_in_repo)
            return;
    }

    addPath(&watcher_, local_path);
    watch_infos_[local_path] = WatchedFileInfo(account, repo_id, path);
}

void AutoUpdateManager::cleanCachedFile()
{
    qDebug("[AutoUpdateManager] cancel all download tasks");
    TransferManager::instance()->cancelAllDownloadTasks();

    const Account cur_account = seafApplet->accountManager()->currentAccount();
    foreach(const QString& key, watch_infos_.keys()) {
        if (watch_infos_[key].account == cur_account)
            watch_infos_.remove(key);
    }

    FileCache::instance()->cleanCurrentAccountCache();

    CachedFilesCleaner *cleaner = new CachedFilesCleaner();
    QThreadPool::globalInstance()->start(cleaner);
}

void AutoUpdateManager::onFileChanged(const QString& local_path)
{
    qDebug("[AutoUpdateManager] detected cache file %s changed", local_path.toUtf8().data());
#ifdef Q_OS_MAC
    if (MacImageFilesWorkAround::instance()->isRecentOpenedImage(local_path)) {
        return;
    }
#endif
    removePath(&watcher_, local_path);
    QString repo_id, path_in_repo;
    if (!watch_infos_.contains(local_path)) {
        // filter unwanted events
        return;
    }

    WatchedFileInfo &info = watch_infos_[local_path];

    if (!QFileInfo(local_path).exists()) {
        qDebug("[AutoUpdateManager] detected cache file %s renamed or removed", local_path.toUtf8().data());
        WatchedFileInfo deferred_info = info;
        removeWatch(local_path);
        // Some application would deleted and recreate the file when saving.
        // We work around that by double checking whether the file gets
        // recreated after a short period
        QTimer::singleShot(5000, this, SLOT(checkFileRecreated()));
        deleted_files_infos_.enqueue(deferred_info);
        return;
    }

    DataManager data_mgr(info.account);
    FileNetworkTask *task = data_mgr.createUploadTask(
        info.repo_id, ::getParentPath(info.path_in_repo),
        local_path, ::getBaseName(local_path), true);

    connect(task, SIGNAL(finished(bool)),
            this, SLOT(onUpdateTaskFinished(bool)));

    qDebug("[AutoUpdateManager] start uploading new version of file %s", local_path.toUtf8().data());

    task->start();
    info.uploading = true;
}

void AutoUpdateManager::onUpdateTaskFinished(bool success)
{
    FileUploadTask *task = qobject_cast<FileUploadTask *>(sender());
    if (task == NULL)
        return;
    const QString local_path = task->localFilePath();
    if (success) {
        qDebug("[AutoUpdateManager] uploaded new version of file %s", local_path.toUtf8().data());
        seafApplet->trayIcon()->showMessage(tr("Upload Success"),
                                            tr("File \"%1\"\nuploaded successfully.").arg(QFileInfo(local_path).fileName()),
                                            task->repoId());
        emit fileUpdated(task->repoId(), task->path());
    } else {
        qWarning("[AutoUpdateManager] failed to upload new version of file %s", local_path.toUtf8().data());
        seafApplet->trayIcon()->showMessage(tr("Upload Failure"),
                                            tr("File \"%1\"\nfailed to upload.").arg(QFileInfo(local_path).fileName()),
                                            task->repoId());
    }

    addPath(&watcher_, local_path);
    WatchedFileInfo& info = watch_infos_[local_path];
    info.uploading = false;
}

void AutoUpdateManager::removeWatch(const QString& local_path)
{
    watch_infos_.remove(local_path);
    removePath(&watcher_, local_path);
}

void AutoUpdateManager::checkFileRecreated()
{
    if (deleted_files_infos_.isEmpty()) {
        // impossible
        return;
    }

    const WatchedFileInfo info = deleted_files_infos_.dequeue();
    const QString path = DataManager::getLocalCacheFilePath(info.repo_id, info.path_in_repo);
    if (QFileInfo(path).exists()) {
        qDebug("[AutoUpdateManager] detected recreated file %s", path.toUtf8().data());
        addPath(&watcher_, path);
        watch_infos_[path] = info;
        // Some applications like MSOffice would remove the original file and
        // recreate it when the user modifies the file.
        onFileChanged(path);
    }
}

#ifdef Q_OS_MAC
SINGLETON_IMPL(MacImageFilesWorkAround)

MacImageFilesWorkAround::MacImageFilesWorkAround()
{
}

void MacImageFilesWorkAround::fileOpened(const QString& path)
{
    QString mimetype = ::mimeTypeFromFileName(path);
    if (mimetype.startsWith("image") || mimetype == "application/pdf") {
        images_[path] = QDateTime::currentMSecsSinceEpoch();
    }
}

bool MacImageFilesWorkAround::isRecentOpenedImage(const QString& path)
{
    qint64 ts = images_.value(path, 0);
    if (QDateTime::currentMSecsSinceEpoch() < ts + 1000 * 10) {
        return true;
    } else {
        return false;
    }
}
#endif

CachedFilesCleaner::CachedFilesCleaner()
{
}

void CachedFilesCleaner::run()
{
    QString file_cache_dir = pathJoin(seafApplet->configurator()->seafileDir(),
                               kFileCacheTopDirName);
    QString file_cache_tmp_dir = pathJoin(seafApplet->configurator()->seafileDir(),
                                   kFileCacheTempTopDirName);
    QString file_cache_db_file = pathJoin(seafApplet->configurator()->seafileDir(),
                                   kFileCacheDBFileName);

    qDebug("[AutoUpdateManager] removing cached files");
    if (QFile(file_cache_db_file).exists()) {
        if (!QFile(file_cache_db_file).remove()) {
            qWarning("[AutoUpdateManager] failed to remove db file");
        }
    }
    if (QDir(file_cache_tmp_dir).exists()) {
        delete_dir_recursively(file_cache_tmp_dir);
    }
    if (QDir(file_cache_dir).exists()) {
        QDir().rename(file_cache_dir, file_cache_tmp_dir);
        delete_dir_recursively(file_cache_tmp_dir);
    }
}
<|endoftext|>


<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>

std::string const intToString(int n){
	std::stringstream ss;
	ss << n;
	return ss.str();
}

void const drawObject(cv::Point const &center, cv::Mat &frame, bool showCoords = false){
	cv::Scalar color(0, 255, 0);
	cv::circle(frame, center, 15, color, 2);
	if(showCoords){
		std::string coords = "x" + intToString(center.x) + " y" + intToString(center.y);
		cv::putText(frame, coords, cv::Point(center.x + 20, center.y), 1, 1, color, 1);
	}
}

void const intro(){
	using namespace std;
	cout << "ECS: Quit" << endl;
	cout << "SPACEBAR: toggle tracking" << endl;
	cout << "c: toggle coords" << endl;
}

int main(){
	using namespace cv;
	intro();

	VideoCapture cap(0);
	if(!cap.isOpened()){
		std::cerr << "could not open webcam!" << std::endl;
		return EXIT_FAILURE;
	}

	Mat imgOrginal, imgOrginal2, imgGray1, imgGray2, imgDiff;
	bool tracking = false, showCoords = false;
	while(true){
		if(!cap.read(imgOrginal)){
			std::cerr << "could not read frame from video stream!" << std::endl;
			return EXIT_FAILURE;
		}
		cvtColor(imgOrginal, imgGray1, COLOR_BGR2GRAY);
		cap.read(imgOrginal2);
		cvtColor(imgOrginal2, imgGray2, COLOR_BGR2GRAY);

		absdiff(imgGray1, imgGray2, imgDiff);

		if(tracking){
			//tracking action
		}

		imshow("Orginal", imgDiff);

		int keyCode = waitKey(30);
		switch(keyCode){
			case 27: //ESC
				return EXIT_SUCCESS;
			break;
			case 32: //SPACEBAR
				tracking = !tracking;
			break;
			case 99: // c key
				showCoords = !showCoords;
			break;
			default:
				if(keyCode >= 0){
					std::cout << "keyCode: " << keyCode << std::endl;
				}
			break;
		}
	}

	return EXIT_SUCCESS;
}
<commit_msg>WIP - search for motion<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int const SENSITIVTY = 20;
cv::Size const BLUR_SIZE(10, 10);

std::string const intToString(int n){
	std::stringstream ss;
	ss << n;
	return ss.str();
}

cv::Point const searchForMovement(cv::Mat const &imgThreshold){
	int posX = 0, int posY = 0;
	std::vector<std::vector<cv::Point>> contours;
	cv::findContours(imgThreshold, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
	if(contours.size > 0){ //found something
		//TODO
	}
	return cv::Point(posX, posY);
}

void const drawObject(cv::Point const &center, cv::Mat &frame, bool showCoords = false){
	cv::Scalar color(0, 255, 0);
	cv::circle(frame, center, 15, color, 2);
	if(showCoords){
		std::string coords = "x" + intToString(center.x) + " y" + intToString(center.y);
		cv::putText(frame, coords, cv::Point(center.x + 20, center.y), 1, 1, color, 1);
	}
}

void const intro(){
	using namespace std;
	cout << "ECS: Quit" << endl;
	cout << "SPACEBAR: toggle tracking" << endl;
	cout << "c: toggle coords" << endl;
}

int main(){
	using namespace cv;
	intro();

	VideoCapture cap(0);
	if(!cap.isOpened()){
		std::cerr << "could not open webcam!" << std::endl;
		return EXIT_FAILURE;
	}

	Mat imgOrginal, imgOrginal2, imgGray1, imgGray2, imgDiff, imgThreshold;
	bool tracking = false, showCoords = false;
	while(true){
		if(!cap.read(imgOrginal)){
			std::cerr << "could not read frame from video stream!" << std::endl;
			return EXIT_FAILURE;
		}
		cvtColor(imgOrginal, imgGray1, COLOR_BGR2GRAY);
		cap.read(imgOrginal2);
		cvtColor(imgOrginal2, imgGray2, COLOR_BGR2GRAY);

		absdiff(imgGray1, imgGray2, imgDiff);
		blur(imgDiff, imgDiff, BLUR_SIZE);
		threshold(imgDiff, imgThreshold, SENSITIVTY, 255, THRESH_BINARY);

		if(tracking){
			//tracking action
		}

		imshow("Orginal", imgThreshold);

		int keyCode = waitKey(30);
		switch(keyCode){
			case 27: //ESC
				return EXIT_SUCCESS;
			break;
			case 32: //SPACEBAR
				tracking = !tracking;
			break;
			case 99: // c key
				showCoords = !showCoords;
			break;
			default:
				if(keyCode >= 0){
					std::cout << "keyCode: " << keyCode << std::endl;
				}
			break;
		}
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>

const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;

const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);

const float kGridSpacing = 2.0f;
const int kGridSize = 8;

bool buttonLeft = false, buttonRight = false,
    buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;
Uint32 tickref = 0;

void handleKey(SDL_keysym *key, bool state)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        if (state) {
            SDL_Quit();
            exit(0);
        }
        break;
    case SDLK_UP:
    case SDLK_w:
        buttonUp = state;
        break;
    case SDLK_DOWN:
    case SDLK_s:
        buttonDown = state;
        break;
    case SDLK_LEFT:
    case SDLK_a:
        buttonLeft = state;
        break;
    case SDLK_RIGHT:
    case SDLK_d:
        buttonRight = state;
        break;
    default:
        break;
    }
}

void handleEvents(void)
{
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        switch (event.type) {
        case SDL_KEYDOWN:
            handleKey(&event.key.keysym, true);
            break;
        case SDL_KEYUP:
            handleKey(&event.key.keysym, false);
            break;
        case SDL_QUIT:
            SDL_Quit();
            exit(0);
            break;
        }
    }
}

void advanceFrame(void)
{
    float forward = 0.0f, turn = 0.0f, face;
    if (buttonLeft)
        turn += kPlayerTurnSpeed;
    if (buttonRight)
        turn -= kPlayerTurnSpeed;
    if (buttonUp)
        forward += kPlayerForwardSpeed;
    if (buttonDown)
        forward -= kPlayerForwardSpeed;
    playerFace += turn;
    face = playerFace * (kPi / 180.0f);
    playerX += forward * std::cos(face);
    playerY += forward * std::sin(face);
}

void updateState(void)
{
    Uint32 tick = SDL_GetTicks();
    if (tick > tickref + kLagThreshold) {
        advanceFrame();
        tickref = tick;
    } else if (tick > tickref + kFrameTime) {
        do {
            advanceFrame();
            tickref += kFrameTime;
        } while (tick > tickref + kFrameTime);
    } else if (tick < tickref)
        tickref = tick;
}

struct gradient_point {
    float pos;
    unsigned char color[3];
};

const gradient_point sky[] = {
    { -0.50f, {   0,   0,  51 } },
    { -0.02f, {   0,   0,   0 } },
    {  0.00f, { 102, 204, 255 } },
    {  0.20f, {  51,   0, 255 } },
    {  0.70f, {   0,   0,   0 } }
};

void drawSky(void)
{
    glPushAttrib(GL_CURRENT_BIT);
    glBegin(GL_TRIANGLE_STRIP);
    glColor3ubv(sky[0].color);
    glVertex3f(-2.0f, 1.0f, -1.0f);
    glVertex3f( 2.0f, 1.0f, -1.0f);
    for (int i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
        glColor3ubv(sky[i].color);
        glVertex3f(-2.0f, 1.0f, sky[i].pos);
        glVertex3f( 2.0f, 1.0f, sky[i].pos);
    }
    glVertex3f(-2.0f, 0.0f, 1.0f);
    glVertex3f( 2.0f, 0.0f, 1.0f);
    glEnd();
    glPopAttrib();
}

void drawGround(void)
{
    float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
    float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
    glPushMatrix();
    glTranslatef(px, py, 0.0f);
    glScalef(kGridSpacing, kGridSpacing, 1.0f);
    glColor3ub(51, 0, 255);
    glBegin(GL_LINES);
    for (int i = -kGridSize; i <= kGridSize; ++i) {
        glVertex3f(i, -kGridSize, 0.0f);
        glVertex3f(i,  kGridSize, 0.0f);
        glVertex3f(-kGridSize, i, 0.0f);
        glVertex3f( kGridSize, i, 0.0f);
    }
    glEnd();
    glPopAttrib();
    glPopMatrix();
}

void drawScene(void)
{
    glLoadIdentity();
    drawSky();
    glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
    glTranslatef(-playerX, -playerY, -1.0f);
    drawGround();
    SDL_GL_SwapBuffers();
}

int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;
    int flags;

    if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
    glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    while (1) {
        handleEvents();
        updateState();
        drawScene();
    }

    return 0;
}
<commit_msg>Moved projection matrix back into loop, wrote separate init function.<commit_after>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>

const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;

const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);

const float kGridSpacing = 2.0f;
const int kGridSize = 8;

bool buttonLeft = false, buttonRight = false,
    buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;
Uint32 tickref = 0;

void init(void)
{
    SDL_Surface *screen = NULL;
    int flags;

    if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }
}

void handleKey(SDL_keysym *key, bool state)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        if (state) {
            SDL_Quit();
            exit(0);
        }
        break;
    case SDLK_UP:
    case SDLK_w:
        buttonUp = state;
        break;
    case SDLK_DOWN:
    case SDLK_s:
        buttonDown = state;
        break;
    case SDLK_LEFT:
    case SDLK_a:
        buttonLeft = state;
        break;
    case SDLK_RIGHT:
    case SDLK_d:
        buttonRight = state;
        break;
    default:
        break;
    }
}

void handleEvents(void)
{
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        switch (event.type) {
        case SDL_KEYDOWN:
            handleKey(&event.key.keysym, true);
            break;
        case SDL_KEYUP:
            handleKey(&event.key.keysym, false);
            break;
        case SDL_QUIT:
            SDL_Quit();
            exit(0);
            break;
        }
    }
}

void advanceFrame(void)
{
    float forward = 0.0f, turn = 0.0f, face;
    if (buttonLeft)
        turn += kPlayerTurnSpeed;
    if (buttonRight)
        turn -= kPlayerTurnSpeed;
    if (buttonUp)
        forward += kPlayerForwardSpeed;
    if (buttonDown)
        forward -= kPlayerForwardSpeed;
    playerFace += turn;
    face = playerFace * (kPi / 180.0f);
    playerX += forward * std::cos(face);
    playerY += forward * std::sin(face);
}

void updateState(void)
{
    Uint32 tick = SDL_GetTicks();
    if (tick > tickref + kLagThreshold) {
        advanceFrame();
        tickref = tick;
    } else if (tick > tickref + kFrameTime) {
        do {
            advanceFrame();
            tickref += kFrameTime;
        } while (tick > tickref + kFrameTime);
    } else if (tick < tickref)
        tickref = tick;
}

struct gradient_point {
    float pos;
    unsigned char color[3];
};

const gradient_point sky[] = {
    { -0.50f, {   0,   0,  51 } },
    { -0.02f, {   0,   0,   0 } },
    {  0.00f, { 102, 204, 255 } },
    {  0.20f, {  51,   0, 255 } },
    {  0.70f, {   0,   0,   0 } }
};

void drawSky(void)
{
    glPushAttrib(GL_CURRENT_BIT);
    glBegin(GL_TRIANGLE_STRIP);
    glColor3ubv(sky[0].color);
    glVertex3f(-2.0f, 1.0f, -1.0f);
    glVertex3f( 2.0f, 1.0f, -1.0f);
    for (int i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
        glColor3ubv(sky[i].color);
        glVertex3f(-2.0f, 1.0f, sky[i].pos);
        glVertex3f( 2.0f, 1.0f, sky[i].pos);
    }
    glVertex3f(-2.0f, 0.0f, 1.0f);
    glVertex3f( 2.0f, 0.0f, 1.0f);
    glEnd();
    glPopAttrib();
}

void drawGround(void)
{
    float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
    float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
    glPushMatrix();
    glTranslatef(px, py, 0.0f);
    glScalef(kGridSpacing, kGridSpacing, 1.0f);
    glColor3ub(51, 0, 255);
    glBegin(GL_LINES);
    for (int i = -kGridSize; i <= kGridSize; ++i) {
        glVertex3f(i, -kGridSize, 0.0f);
        glVertex3f(i,  kGridSize, 0.0f);
        glVertex3f(-kGridSize, i, 0.0f);
        glVertex3f( kGridSize, i, 0.0f);
    }
    glEnd();
    glPopAttrib();
    glPopMatrix();
}

void drawScene(void)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
    glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    drawSky();

    glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
    glTranslatef(-playerX, -playerY, -1.0f);

    drawGround();

    SDL_GL_SwapBuffers();
}

int main(int argc, char *argv[])
{
    init();
    while (1) {
        handleEvents();
        updateState();
        drawScene();
    }
    return 0;
}
<|endoftext|>


<commit_before>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

int main(int argc, char **argv) {
  {
    ics::ID id(2);
    ics::Angle degree = ics::Angle::newDegree();
    try {
      ics::ICS3 ics("/dev/ttyUSB0", ics::ICSBaudrate::RATE115200);
      assert(7500 == degree.getRaw());
      ics::Angle nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
    } catch (std::runtime_error& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    assert(127 == speed.get());
    speed.set(100);
    assert(100 == speed.get());
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree();
    ics::Angle radian = ics::Angle::newRadian();
    assert(degree.getRaw() == radian.getRaw());
    degree.set(0);
    radian.set(0);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(90);
    radian.set(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(60);
    radian.set(M_PI / 3);
    assert(degree.getRaw() == radian.getRaw());
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    assert(63 == current.get());
    current.set(30);
    assert(30 == current.get());
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<commit_msg>Update testcode for move task<commit_after>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

int main(int argc, char **argv) {
  {
    ics::ID id(2);
    ics::Angle degree = ics::Angle::newDegree();
    try {
      ics::ICS3 ics("/dev/ttyUSB0", ics::ICSBaudrate::RATE115200);
      assert(7500 == degree.getRaw());
      ics::Angle nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(50);
      ics.move(id, degree);
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(-50);
      ics.move(id, degree);
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(0);
      ics.move(id, degree);
    } catch (std::runtime_error& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    assert(127 == speed.get());
    speed.set(100);
    assert(100 == speed.get());
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree();
    ics::Angle radian = ics::Angle::newRadian();
    assert(degree.getRaw() == radian.getRaw());
    degree.set(0);
    radian.set(0);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(90);
    radian.set(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(60);
    radian.set(M_PI / 3);
    assert(degree.getRaw() == radian.getRaw());
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    assert(63 == current.get());
    current.set(30);
    assert(30 == current.get());
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<|endoftext|>


<commit_before>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>
#include <vector>
#include <random>
#include <chrono>

// For Debug
#include <iostream>

using namespace glm;
using namespace std;
using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Number of points to generate
const int num_points = 50000;
// Points generated
vector<vec2> points;

bool initialise()
{
	// Set background to white.
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glColor3f(1.0f, 0.0f, 0.0f);

	// Enable face culling
	glEnable(GL_CULL_FACE);

	// The three points we randomly select from
	vec2 v[3] =
	{
			vec2(-1.0f, -1.0f),
			vec2(0.0f, 1.0f),
			vec2(1.0f, -1.0f)
	};

	// Add starting point
	points.push_back(vec2(0.25f, 0.5f));

	// Create a random engine
	default_random_engine re;

	// Create a distribution. 3 points in array, so get 0, 1 or 2.
	uniform_int_distribution<int> dist(0,2);

	int k;
	for(k=0; k <5000; k++)
	{
		float x,y;

		int r = dist(re);

		/* compute point halfway between vertex and old point */
		points.push_back(vec2(
				(points.at(points.size()-1).x + v[r].x)/2.0,
				(points.at(points.size()-1).y + v[r].y)/2.0));
	}

	return true;
} // initialise

//updates the application
void update(double deltaTime)
{

} // update

//renders the application
void render()
{
	// Clear the screen
	glClear(GL_COLOR_BUFFER_BIT);
	// Set Colour to black
	glColor3f(0.0f, 0.0f, 0.0f);

	//Render a Triangle
	glBegin(GL_POINTS);
	for (vec2& point : points) {
		glVertex2fv(value_ptr(point));
	}
	glEnd();

	// Swap front and back buffers
	glfwSwapBuffers(window);

	// Set transform matrix to identity (no transform)
	glLoadIdentity();

} // render

int main(void)
{
	/* Initialize the library */
	if (!glfwInit())
	{
		return -1;
	}

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	/* Make the window's context current */
	glfwMakeContextCurrent(window);

	//initialise the window
	if (!initialise())
	{
		glfwTerminate();
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp
				- prevTimeStamp);
		//Convert to fractions of a second
		auto seconds = double(elapsed.count()) / 1000.0;

		// Update Application
		update(seconds);
		//Render scene
		render();

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();

		// set the previous time stamp to current time stamp
		prevTimeStamp = currentTimeStamp;
	} // Main Loop

	glfwTerminate();
	return 0;
} // main
<commit_msg>Implemented user controled scale, rotate and move<commit_after>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>
#include <vector>
#include <random>
#include <chrono>

// For Debug
#include <iostream>

using namespace glm;
using namespace std;
using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Number of points to generate
const int num_points = 50000;
// Points generated
vector<vec2> points;

// Value to keep track of current orientation on axis
float objOrientation = 0.0f;
// Keep track of position
glm::vec3 objPosition(0.0f, 0.0f, 0.0f);
// Keep track of scale
float objScale = 1.0f;

// Keep track of current mode
bool TRANSLATIONMODE = true;

bool initialise()
{
	// Set background to white.
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glColor3f(1.0f, 0.0f, 0.0f);

	// Enable face culling
	glEnable(GL_CULL_FACE);

	// The three points we randomly select from
	vec2 v[3] =
	{
			vec2(-1.0f, -1.0f),
			vec2(0.0f, 1.0f),
			vec2(1.0f, -1.0f)
	};

	// Add starting point
	points.push_back(vec2(0.25f, 0.5f));

	// Create a random engine
	default_random_engine re;

	// Create a distribution. 3 points in array, so get 0, 1 or 2.
	uniform_int_distribution<int> dist(0,2);

	int k;
	for(k=0; k <5000; k++)
	{
		float x,y;

		int r = dist(re);

		/* compute point halfway between vertex and old point */
		points.push_back(vec2(
				(points.at(points.size()-1).x + v[r].x)/2.0,
				(points.at(points.size()-1).y + v[r].y)/2.0));
	}

	return true;
} // initialise

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
	if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
		if (TRANSLATIONMODE == true) {
			TRANSLATIONMODE = false;
		} else {
			TRANSLATIONMODE = true;
		}

	}
} // Key_callback

void userRotation(double deltaTime) {

	if (glfwGetKey(window, GLFW_KEY_RIGHT)){
		objOrientation += (deltaTime * pi<float>());
	}
	if (glfwGetKey(window, GLFW_KEY_LEFT)){
		objOrientation -= (deltaTime * pi<float>());
	}

}

/*
 * userScale
 *
 * Increases and decreases the scale of the object.
 */
void userScale(double deltaTime) {
	if (glfwGetKey(window, GLFW_KEY_UP)){
		objScale += 1.0f * float(deltaTime);
	}
	if (glfwGetKey(window, GLFW_KEY_DOWN)){
		objScale -= 1.0f * float(deltaTime);
	}

}

/*
 * userTranslation
 *
 * moves the object around inside the window using the keyboard arrow keys.
 */
void userTranslation(double deltaTime) {
	// Move the quad when arrow keys are pressed
	if (glfwGetKey(window, GLFW_KEY_RIGHT)){
		if (objPosition.x < (1 - (objScale/2))) {
			objPosition += vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
		}
	}
	if (glfwGetKey(window, GLFW_KEY_LEFT)){
		if (objPosition.x > (-1.0 + (objScale/2))) {
			objPosition -= vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
		}
	}
	if (glfwGetKey(window, GLFW_KEY_UP)){
		if (objPosition.y < (1.0 - (objScale/2))) {
			objPosition += vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
		}
	}
	if (glfwGetKey(window, GLFW_KEY_DOWN)){
		if (objPosition.y > (-1.0 + (objScale/2))) {
			objPosition -= vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
		}
	}

} // userTranslation

//updates the application
void update(double deltaTime)
{
	// Check if escape pressed or window is closed
	running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
			!glfwWindowShouldClose(window);

	if (TRANSLATIONMODE) {
		userTranslation(deltaTime);
	} else {
		userScale(deltaTime);
		userRotation(deltaTime);
	}

} // update

//renders the application
void render()
{
	// Create model matrix
	auto model = translate(mat4(1.0f), objPosition);
	// Scale the triangle
	model *= scale(objScale, objScale, objScale);
	// Create rotation transform. Use Z-axis
	model *= rotate(mat4(10.f),
					degrees(objOrientation),
			        vec3(0.0f, 0.0f, 1.0f));

	// Set matrix mode
	glMatrixMode(GL_MODELVIEW);
	// Load model matrix
	glLoadMatrixf(value_ptr(model));

	// Clear the screen
	glClear(GL_COLOR_BUFFER_BIT);
	// Set Colour to black
	glColor3f(0.0f, 0.0f, 0.0f);

	//Render a Triangle
	glBegin(GL_POINTS);
	for (vec2& point : points) {
		glVertex2fv(value_ptr(point));
	}
	glEnd();

	// Swap front and back buffers
	glfwSwapBuffers(window);

	// Set transform matrix to identity (no transform)
	glLoadIdentity();

} // render

int main(void)
{
	/* Initialise the library */
	if (!glfwInit())
	{
		return -1;
	}

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	/* Make the window's context current */
	glfwMakeContextCurrent(window);

    glfwSetKeyCallback(window, key_callback);

	//initialise the window
	if (!initialise())
	{
		glfwTerminate();
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp
				- prevTimeStamp);
		//Convert to fractions of a second
		auto seconds = double(elapsed.count()) / 1000.0;

		// Update Application
		update(seconds);
		//Render scene
		render();

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();

		// set the previous time stamp to current time stamp
		prevTimeStamp = currentTimeStamp;
	} // Main Loop

	glfwTerminate();
	return 0;
} // main
<|endoftext|>


<commit_before>#ifndef RPT_XMLIMAGE_HXX
#define RPT_XMLIMAGE_HXX
/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlImage.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-09 11:56:18 $
 *
 *  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 RPT_XMLREPORTELEMENTBASE_HXX
#include "xmlReportElementBase.hxx"
#endif
#ifndef _COM_SUN_STAR_REPORT_XImageControl_HPP_
#include <com/sun/star/report/XImageControl.hpp>
#endif

namespace rptxml
{
    class ORptFilter;
    class OXMLImage : public OXMLReportElementBase
    {
        OXMLImage(const OXMLImage&);
        void operator =(const OXMLImage&);
    public:

        OXMLImage( ORptFilter& rImport, sal_uInt16 nPrfx,
                    const ::rtl::OUString& rLName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
                    ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XImageControl >& _xComponent
                    ,OXMLTable* _pContainer);
        virtual ~OXMLImage();
    };
// -----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------

#endif // RPT_XMLIMAGE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.104); FILE MERGED 2008/04/01 12:33:11 thb 1.2.104.2: #i85898# Stripping all external header guards 2008/03/31 13:32:09 rt 1.2.104.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: xmlImage.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 RPT_XMLIMAGE_HXX
#define RPT_XMLIMAGE_HXX

#include "xmlReportElementBase.hxx"
#ifndef _COM_SUN_STAR_REPORT_XImageControl_HPP_
#include <com/sun/star/report/XImageControl.hpp>
#endif

namespace rptxml
{
    class ORptFilter;
    class OXMLImage : public OXMLReportElementBase
    {
        OXMLImage(const OXMLImage&);
        void operator =(const OXMLImage&);
    public:

        OXMLImage( ORptFilter& rImport, sal_uInt16 nPrfx,
                    const ::rtl::OUString& rLName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
                    ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XImageControl >& _xComponent
                    ,OXMLTable* _pContainer);
        virtual ~OXMLImage();
    };
// -----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------

#endif // RPT_XMLIMAGE_HXX
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "generic_dbn_desc.hpp"

namespace dll {

template <typename Layers, typename... Parameters>
using dbn_desc = generic_dbn_desc<dbn, Layers, Parameters...>;

template <typename Layers>
struct dyn_layers_t;

template <bool Labels, typename... Layers>
struct dyn_layers_t <dll::detail::layers<Labels, Layers...>> {
    using dyn_t = dll::detail::layers<Labels, typename Layers::desc::dyn_layer_t...>;
};

template <template <typename> class DBN_T, typename Layers, typename... Parameters>
struct generic_dyn_dbn_desc : generic_dbn_desc<DBN_T, Layers, Parameters...> {
    /* Dynify the layers */
    using layers      = typename dyn_layers_t<Layers>::dyn_t;
    using base_layers = Layers;

    /*! The DBN type */
    using dbn_t = DBN_T<generic_dyn_dbn_desc<DBN_T, Layers, Parameters...>>;
};

template <typename Layers, typename... Parameters>
using dyn_dbn_desc = generic_dyn_dbn_desc<dbn, Layers, Parameters...>;

} //end of dll namespace
<commit_msg>Add support for automatic hybrid compilation<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "generic_dbn_desc.hpp"

namespace dll {

template <typename Layers>
struct dyn_layers_t;

template <bool Labels, typename... Layers>
struct dyn_layers_t <dll::detail::layers<Labels, Layers...>> {
    using dyn_t = dll::detail::layers<Labels, typename Layers::desc::dyn_layer_t...>;
};

template <template <typename> class DBN_T, typename Layers, typename... Parameters>
struct generic_dyn_dbn_desc : generic_dbn_desc<DBN_T, Layers, Parameters...> {
    /* Dynify the layers */
    using layers      = typename dyn_layers_t<Layers>::dyn_t;
    using base_layers = Layers;

    /*! The DBN type */
    using dbn_t = DBN_T<generic_dyn_dbn_desc<DBN_T, Layers, Parameters...>>;
};

template <typename Layers, typename... Parameters>
using dyn_dbn_desc = generic_dyn_dbn_desc<dbn, Layers, Parameters...>;

// By default dbn_desc use directly the layers that it is provided
// if DLL_QUICK is set, it is set to hybrid mode by default

#ifndef DLL_QUICK
template <typename Layers, typename... Parameters>
using dbn_desc = generic_dbn_desc<dbn, Layers, Parameters...>;
#else
template <typename Layers, typename... Parameters>
using dbn_desc = generic_dyn_dbn_desc<dbn, Layers, Parameters...>;
#endif

// fast_dbn_desc is always forced to direct mode, will not respect
// DLL_QUICK

template <typename Layers, typename... Parameters>
using fast_dbn_desc = generic_dbn_desc<dbn, Layers, Parameters...>;

} //end of dll namespace
<|endoftext|>