<commit_before>#include "binary-cache-store.hh"
#include "filetransfer.hh"
#include "globals.hh"
#include "nar-info-disk-cache.hh"

namespace nix {

MakeError(UploadToHTTP, Error);

class HttpBinaryCacheStore : public BinaryCacheStore
{
private:

    Path cacheUri;

    struct State
    {
        bool enabled = true;
        std::chrono::steady_clock::time_point disabledUntil;
    };

    Sync<State> _state;

public:

    HttpBinaryCacheStore(
        const Params & params, const Path & _cacheUri)
        : BinaryCacheStore(params)
        , cacheUri(_cacheUri)
    {
        if (cacheUri.back() == '/')
            cacheUri.pop_back();

        diskCache = getNarInfoDiskCache();
    }

    std::string getUri() override
    {
        return cacheUri;
    }

    void init() override
    {
        // FIXME: do this lazily?
        if (auto cacheInfo = diskCache->cacheExists(cacheUri)) {
            wantMassQuery.setDefault(cacheInfo->wantMassQuery ? "true" : "false");
            priority.setDefault(fmt("%d", cacheInfo->priority));
        } else {
            try {
                BinaryCacheStore::init();
            } catch (UploadToHTTP &) {
                throw Error("'%s' does not appear to be a binary cache", cacheUri);
            }
            diskCache->createCache(cacheUri, storeDir, wantMassQuery, priority);
        }
    }

protected:

    void maybeDisable()
    {
        auto state(_state.lock());
        if (state->enabled && settings.tryFallback) {
            int t = 60;
            printError("disabling binary cache '%s' for %s seconds", getUri(), t);
            state->enabled = false;
            state->disabledUntil = std::chrono::steady_clock::now() + std::chrono::seconds(t);
        }
    }

    void checkEnabled()
    {
        auto state(_state.lock());
        if (state->enabled) return;
        if (std::chrono::steady_clock::now() > state->disabledUntil) {
            state->enabled = true;
            debug("re-enabling binary cache '%s'", getUri());
            return;
        }
        throw SubstituterDisabled("substituter '%s' is disabled", getUri());
    }

    bool fileExists(const std::string & path) override
    {
        checkEnabled();

        try {
            FileTransferRequest request(cacheUri + "/" + path);
            request.head = true;
            getFileTransfer()->download(request);
            return true;
        } catch (FileTransferError & e) {
            /* S3 buckets return 403 if a file doesn't exist and the
               bucket is unlistable, so treat 403 as 404. */
            if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                return false;
            maybeDisable();
            throw;
        }
    }

    void upsertFile(const std::string & path,
        std::shared_ptr<std::basic_iostream<char>> istream,
        const std::string & mimeType) override
    {
        auto req = FileTransferRequest(cacheUri + "/" + path);
        req.data = std::make_shared<string>(StreamToSourceAdapter(istream).drain());
        req.mimeType = mimeType;
        try {
            getFileTransfer()->upload(req);
        } catch (FileTransferError & e) {
            throw UploadToHTTP("while uploading to HTTP binary cache at '%s': %s", cacheUri, e.msg());
        }
    }

    FileTransferRequest makeRequest(const std::string & path)
    {
        FileTransferRequest request(cacheUri + "/" + path);
        return request;
    }

    void getFile(const std::string & path, Sink & sink) override
    {
        checkEnabled();
        auto request(makeRequest(path));
        try {
            getFileTransfer()->download(std::move(request), sink);
        } catch (FileTransferError & e) {
            if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                throw NoSuchBinaryCacheFile("file '%s' does not exist in binary cache '%s'", path, getUri());
            maybeDisable();
            throw;
        }
    }

    void getFile(const std::string & path,
        Callback<std::shared_ptr<std::string>> callback) noexcept override
    {
        checkEnabled();

        auto request(makeRequest(path));

        auto callbackPtr = std::make_shared<decltype(callback)>(std::move(callback));

        getFileTransfer()->enqueueFileTransfer(request,
            {[callbackPtr, this](std::future<FileTransferResult> result) {
                try {
                    (*callbackPtr)(result.get().data);
                } catch (FileTransferError & e) {
                    if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                        return (*callbackPtr)(std::shared_ptr<std::string>());
                    maybeDisable();
                    callbackPtr->rethrow();
                } catch (...) {
                    callbackPtr->rethrow();
                }
            }});
    }

};

static RegisterStoreImplementation regStore([](
    const std::string & uri, const Store::Params & params)
    -> std::shared_ptr<Store>
{
    static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1";
    if (std::string(uri, 0, 7) != "http://" &&
        std::string(uri, 0, 8) != "https://" &&
        (!forceHttp || std::string(uri, 0, 7) != "file://"))
        return 0;
    auto store = std::make_shared<HttpBinaryCacheStore>(params, uri);
    store->init();
    return store;
});

}
<commit_msg>Allow HTTP binary cache to request absolute uris<commit_after>#include "binary-cache-store.hh"
#include "filetransfer.hh"
#include "globals.hh"
#include "nar-info-disk-cache.hh"

namespace nix {

MakeError(UploadToHTTP, Error);

class HttpBinaryCacheStore : public BinaryCacheStore
{
private:

    Path cacheUri;

    struct State
    {
        bool enabled = true;
        std::chrono::steady_clock::time_point disabledUntil;
    };

    Sync<State> _state;

public:

    HttpBinaryCacheStore(
        const Params & params, const Path & _cacheUri)
        : BinaryCacheStore(params)
        , cacheUri(_cacheUri)
    {
        if (cacheUri.back() == '/')
            cacheUri.pop_back();

        diskCache = getNarInfoDiskCache();
    }

    std::string getUri() override
    {
        return cacheUri;
    }

    void init() override
    {
        // FIXME: do this lazily?
        if (auto cacheInfo = diskCache->cacheExists(cacheUri)) {
            wantMassQuery.setDefault(cacheInfo->wantMassQuery ? "true" : "false");
            priority.setDefault(fmt("%d", cacheInfo->priority));
        } else {
            try {
                BinaryCacheStore::init();
            } catch (UploadToHTTP &) {
                throw Error("'%s' does not appear to be a binary cache", cacheUri);
            }
            diskCache->createCache(cacheUri, storeDir, wantMassQuery, priority);
        }
    }

protected:

    void maybeDisable()
    {
        auto state(_state.lock());
        if (state->enabled && settings.tryFallback) {
            int t = 60;
            printError("disabling binary cache '%s' for %s seconds", getUri(), t);
            state->enabled = false;
            state->disabledUntil = std::chrono::steady_clock::now() + std::chrono::seconds(t);
        }
    }

    void checkEnabled()
    {
        auto state(_state.lock());
        if (state->enabled) return;
        if (std::chrono::steady_clock::now() > state->disabledUntil) {
            state->enabled = true;
            debug("re-enabling binary cache '%s'", getUri());
            return;
        }
        throw SubstituterDisabled("substituter '%s' is disabled", getUri());
    }

    bool fileExists(const std::string & path) override
    {
        checkEnabled();

        try {
            FileTransferRequest request(makeRequest(path));
            request.head = true;
            getFileTransfer()->download(request);
            return true;
        } catch (FileTransferError & e) {
            /* S3 buckets return 403 if a file doesn't exist and the
               bucket is unlistable, so treat 403 as 404. */
            if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                return false;
            maybeDisable();
            throw;
        }
    }

    void upsertFile(const std::string & path,
        std::shared_ptr<std::basic_iostream<char>> istream,
        const std::string & mimeType) override
    {
        auto req = makeRequest(path);
        req.data = std::make_shared<string>(StreamToSourceAdapter(istream).drain());
        req.mimeType = mimeType;
        try {
            getFileTransfer()->upload(req);
        } catch (FileTransferError & e) {
            throw UploadToHTTP("while uploading to HTTP binary cache at '%s': %s", cacheUri, e.msg());
        }
    }

    FileTransferRequest makeRequest(const std::string & path)
    {
        return FileTransferRequest(
            hasPrefix(path, "https://") || hasPrefix(path, "http://") || hasPrefix(path, "file://")
            ? path
            : cacheUri + "/" + path);

    }

    void getFile(const std::string & path, Sink & sink) override
    {
        checkEnabled();
        auto request(makeRequest(path));
        try {
            getFileTransfer()->download(std::move(request), sink);
        } catch (FileTransferError & e) {
            if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                throw NoSuchBinaryCacheFile("file '%s' does not exist in binary cache '%s'", path, getUri());
            maybeDisable();
            throw;
        }
    }

    void getFile(const std::string & path,
        Callback<std::shared_ptr<std::string>> callback) noexcept override
    {
        checkEnabled();

        auto request(makeRequest(path));

        auto callbackPtr = std::make_shared<decltype(callback)>(std::move(callback));

        getFileTransfer()->enqueueFileTransfer(request,
            {[callbackPtr, this](std::future<FileTransferResult> result) {
                try {
                    (*callbackPtr)(result.get().data);
                } catch (FileTransferError & e) {
                    if (e.error == FileTransfer::NotFound || e.error == FileTransfer::Forbidden)
                        return (*callbackPtr)(std::shared_ptr<std::string>());
                    maybeDisable();
                    callbackPtr->rethrow();
                } catch (...) {
                    callbackPtr->rethrow();
                }
            }});
    }

};

static RegisterStoreImplementation regStore([](
    const std::string & uri, const Store::Params & params)
    -> std::shared_ptr<Store>
{
    static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1";
    if (std::string(uri, 0, 7) != "http://" &&
        std::string(uri, 0, 8) != "https://" &&
        (!forceHttp || std::string(uri, 0, 7) != "file://"))
        return 0;
    auto store = std::make_shared<HttpBinaryCacheStore>(params, uri);
    store->init();
    return store;
});

}
<|endoftext|>


<commit_before>//
//  testing a subd idea
//

#include <stdlib.h>
#include <iostream>
#include <cctype>     // std::tolower
#include <algorithm>
#include <vector>
// in project properties, add "../include" to the vc++ directories include path

#include "geometric.h"
#include "glwin.h"  // minimal opengl for windows setup wrapper
#include "misc_gl.h"
#include "wingmesh.h"
#include "minixml.h"

void wmwire(const WingMesh &m)
{
	glBegin(GL_LINES);
	for (auto e : m.edges)
	{
		glVertex3fv(m.verts[e.v]);
		glVertex3fv(m.verts[m.edges[e.next].v]);
	}
	glEnd();
}
void wmdraw(const WingMesh &m)
{
	gldraw(m.verts, m.GenerateTris());
}

std::vector<std::string> split(std::string line, std::string delimeter=" ")
{
	std::vector<std::string> tokens;
	size_t pos = 0;
	while ((pos = line.find(delimeter)) != std::string::npos)
	{
		auto token = line.substr(0, pos);
		line.erase(0, pos + delimeter.length());
		if (token.length())
			tokens.push_back(token);
	}
	if (line.length())
		tokens.push_back(line);
	return tokens;
}

WingMesh WingMeshLoad(const char *filename)
{
	WingMesh wm;
	std::ifstream filein(filename);
	if (!filein.is_open())
		throw "unable to open file";
	std::string line;
	while (std::getline(filein, line))
	{
		auto tokens = split(line);
		if (!tokens.size())
			continue;
		auto head = tokens.front();
		tokens.erase(tokens.begin());
		if (head == "v")
		{
			line.erase(0, 1);
			wm.verts.push_back(StringTo<float3>(line)*0.1f);
			continue;
		}
		if (head == "f")
		{
			std::vector<int> vids;
			for(auto &token:tokens)
				vids.push_back(StringTo<int>(split(token,"/")[0]) - 1);  // ugg obj index from one instead of zero
			int base = wm.edges.size();
			std::vector<float3> fverts;
			for (int i = 0; i < (int)vids.size(); i++)
			{
				int inext = (i + 1) % vids.size();
				int iprev = (i + vids.size()-1) % vids.size();
				wm.edges.push_back(WingMesh::HalfEdge(base + i, vids[i], -1, base + inext, base + iprev, wm.faces.size()));
				fverts.push_back(wm.verts[vids[i]]);
			}
			wm.faces.push_back(PolyPlane(fverts));
			continue;
		}
	}
	wm.LinkMesh();
	wm.InitBackLists();
	return wm;
}

int main(int argc, char *argv[])
{
	std::cout << "Test...\n";
	auto body = WingMeshLoad("EntireBody.obj");
	auto body1 = WingMeshSubDiv(body);
	auto body2 = WingMeshSubDiv(body1);

	//auto box = WingMeshSubDiv(WingMeshSubDiv(WingMeshCube(0.5f)));

	GLWin glwin("Test CatmullClark");
	glwin.keyboardfunc = [](int key, int, int)
	{
			switch (std::tolower(key))
			{
			case ' ':

				break;
			case 27:   // ESC
			case 'q':
				exit(0);
				break;
			default:
				std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n";
				break;
			}

	};

	float3 mousevec_prev;
	float4 model_orientation(0, 0, 0, 1);
	while (glwin.WindowUp())
	{
		if (glwin.MouseState)  // on mouse drag
		{
			model_orientation = qmul(VirtualTrackBall(float3(0, 0, 2), float3(0, 0, 0), mousevec_prev, glwin.MouseVector), model_orientation);
		}
		mousevec_prev = glwin.MouseVector;

		glPushAttrib(GL_ALL_ATTRIB_BITS);

		// Set up the viewport
		glViewport(0, 0, glwin.Width, glwin.Height);
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.Width / glwin.Height, 0.01, 10);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		gluLookAt(0, 0, 2, 0, 0, 0, 0, 1, 0);

		float4x4 R = { { 1, 0, 0, 0 },{ 0, 1, 0, 0 },{ 0, 0, 1, 0 },{ 0, 0, 0, 1 } };
		R[0].xyz() = qxdir(model_orientation); R[1].xyz() = qydir(model_orientation); R[2].xyz() = qzdir(model_orientation);
		glMultMatrixf(R);

		glEnable(GL_DEPTH_TEST);

		glDisable(GL_BLEND);

		glColor3f(0, 1, 1);
		glEnable(GL_CULL_FACE);
		//glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		wmwire(body2);
		glTranslatef(0.3f,0,0 );
		wmwire(body1);
		glTranslatef( 0.3f,0,0);
		wmwire(body );

		// Restore state
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();  //should be currently in modelview mode
		glPopAttrib();

		glwin.PrintString({ 0, 0 }, "Press ESC to quit.");

		glwin.SwapBuffers();
	}

	std::cout << "\n";
	return 0;
}

<commit_msg>using camera pose convention for view<commit_after>//
//  testing a subd idea
//

#include <stdlib.h>
#include <iostream>
#include <cctype>     // std::tolower
#include <algorithm>
#include <vector>
// in project properties, add "../include" to the vc++ directories include path

#include "geometric.h"
#include "glwin.h"  // minimal opengl for windows setup wrapper
#include "misc_gl.h"
#include "wingmesh.h"
#include "minixml.h"

void wmwire(const WingMesh &m)
{
	glBegin(GL_LINES);
	for (auto e : m.edges)
	{
		glVertex3fv(m.verts[e.v]);
		glVertex3fv(m.verts[m.edges[e.next].v]);
	}
	glEnd();
}
void wmdraw(const WingMesh &m)
{
	gldraw(m.verts, m.GenerateTris());
}

std::vector<std::string> split(std::string line, std::string delimeter=" ")
{
	std::vector<std::string> tokens;
	size_t pos = 0;
	while ((pos = line.find(delimeter)) != std::string::npos)
	{
		auto token = line.substr(0, pos);
		line.erase(0, pos + delimeter.length());
		if (token.length())
			tokens.push_back(token);
	}
	if (line.length())
		tokens.push_back(line);
	return tokens;
}

WingMesh WingMeshLoad(const char *filename)
{
	WingMesh wm;
	std::ifstream filein(filename);
	if (!filein.is_open())
		throw "unable to open file";
	std::string line;
	while (std::getline(filein, line))
	{
		auto tokens = split(line);
		if (!tokens.size())
			continue;
		auto head = tokens.front();
		tokens.erase(tokens.begin());
		if (head == "v")
		{
			line.erase(0, 1);
			wm.verts.push_back(StringTo<float3>(line)*0.1f);
			continue;
		}
		if (head == "f")
		{
			std::vector<int> vids;
			for(auto &token:tokens)
				vids.push_back(StringTo<int>(split(token,"/")[0]) - 1);  // ugg obj index from one instead of zero
			int base = wm.edges.size();
			std::vector<float3> fverts;
			for (int i = 0; i < (int)vids.size(); i++)
			{
				int inext = (i + 1) % vids.size();
				int iprev = (i + vids.size()-1) % vids.size();
				wm.edges.push_back(WingMesh::HalfEdge(base + i, vids[i], -1, base + inext, base + iprev, wm.faces.size()));
				fverts.push_back(wm.verts[vids[i]]);
			}
			wm.faces.push_back(PolyPlane(fverts));
			continue;
		}
	}
	wm.LinkMesh();
	wm.InitBackLists();
	return wm;
}

int main(int argc, char *argv[])
{
	std::cout << "Test...\n";
	auto body = WingMeshLoad("EntireBody.obj");
	auto body1 = WingMeshSubDiv(body);
	auto body2 = WingMeshSubDiv(body1);

	//auto box = WingMeshSubDiv(WingMeshSubDiv(WingMeshCube(0.5f)));

	GLWin glwin("Test CatmullClark");
	glwin.keyboardfunc = [](int key, int, int)
	{
			switch (std::tolower(key))
			{
			case ' ':

				break;
			case 27:   // ESC
			case 'q':
				exit(0);
				break;
			default:
				std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n";
				break;
			}

	};

	float3 mousevec_prev;
	float camdist = 2.0f;
	Pose  camera({ 0,0,camdist }, { 0, 0, 0, 1 });
	while (glwin.WindowUp())
	{
		if (glwin.MouseState)  // on mouse drag
		{
			camera.orientation = qmul(camera.orientation,qconj(VirtualTrackBall(float3(0, 0, 2), float3(0, 0, 0), mousevec_prev, glwin.MouseVector)));
			camera.position    = qzdir(camera.orientation)*camdist;
		}
		mousevec_prev = glwin.MouseVector;

		glPushAttrib(GL_ALL_ATTRIB_BITS);

		// Set up the viewport
		glViewport(0, 0, glwin.Width, glwin.Height);
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.Width / glwin.Height, 0.01, 10);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glMultMatrixf(camera.inverse().matrix());

		glEnable(GL_DEPTH_TEST);

		glDisable(GL_BLEND);

		glColor3f(0, 1, 1);
		glEnable(GL_CULL_FACE);
		//glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		wmwire(body );
		glTranslatef(0.3f,0,0 );
		wmwire(body1);
		glTranslatef( 0.3f,0,0);
		wmwire(body2);

		// Restore state
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();  //should be currently in modelview mode
		glPopAttrib();

		glwin.PrintString({ 0, 0 }, "Press ESC to quit.");

		glwin.SwapBuffers();
	}

	std::cout << "\n";
	return 0;
}

<|endoftext|>


<commit_before>/*
* SIV Mode Encryption
* (C) 2013,2017 Jack Lloyd
* (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/siv.h>
#include <botan/block_cipher.h>
#include <botan/cmac.h>
#include <botan/internal/poly_dbl.h>
#include <botan/ctr.h>

namespace Botan {

SIV_Mode::SIV_Mode(BlockCipher* cipher) :
   m_name(cipher->name() + "/SIV"),
   m_ctr(new CTR_BE(cipher->clone())),
   m_mac(new CMAC(cipher)),
   m_bs(cipher->block_size())
   {
   if(cipher->block_size() != 16)
      throw Invalid_Argument("SIV requires a 128 bit block cipher");
   }

SIV_Mode::~SIV_Mode()
   {
   // for ~unique_ptr
   }

void SIV_Mode::clear()
   {
   m_ctr->clear();
   m_mac->clear();
   reset();
   }

void SIV_Mode::reset()
   {
   m_nonce.clear();
   m_msg_buf.clear();
   m_ad_macs.clear();
   }

std::string SIV_Mode::name() const
   {
   return m_name;
   }

bool SIV_Mode::valid_nonce_length(size_t) const
   {
   return true;
   }

size_t SIV_Mode::update_granularity() const
   {
   /*
   This value does not particularly matter as regardless SIV_Mode::update
   buffers all input, so in theory this could be 1. However as for instance
   Transform_Filter creates update_granularity() uint8_t buffers, use a
   somewhat large size to avoid bouncing on a tiny buffer.
   */
   return 128;
   }

Key_Length_Specification SIV_Mode::key_spec() const
   {
   return m_mac->key_spec().multiple(2);
   }

void SIV_Mode::key_schedule(const uint8_t key[], size_t length)
   {
   const size_t keylen = length / 2;
   m_mac->set_key(key, keylen);
   m_ctr->set_key(key + keylen, keylen);
   m_ad_macs.clear();
   }

void SIV_Mode::set_associated_data_n(size_t n, const uint8_t ad[], size_t length)
   {
   const size_t max_ads = block_size() * 8 - 2;
   if(n > max_ads)
      throw Invalid_Argument(name() + " allows no more than " + std::to_string(max_ads) + " ADs");

   if(n >= m_ad_macs.size())
      m_ad_macs.resize(n+1);

   m_ad_macs[n] = m_mac->process(ad, length);
   }

void SIV_Mode::start_msg(const uint8_t nonce[], size_t nonce_len)
   {
   if(!valid_nonce_length(nonce_len))
      throw Invalid_IV_Length(name(), nonce_len);

   if(nonce_len)
      m_nonce = m_mac->process(nonce, nonce_len);
   else
      m_nonce.clear();

   m_msg_buf.clear();
   }

size_t SIV_Mode::process(uint8_t buf[], size_t sz)
   {
   // all output is saved for processing in finish
   m_msg_buf.insert(m_msg_buf.end(), buf, buf + sz);
   return 0;
   }

secure_vector<uint8_t> SIV_Mode::S2V(const uint8_t* text, size_t text_len)
   {
   const std::vector<uint8_t> zeros(block_size());

   secure_vector<uint8_t> V = m_mac->process(zeros.data(), zeros.size());

   for(size_t i = 0; i != m_ad_macs.size(); ++i)
      {
      poly_double_n(V.data(), V.size());
      V ^= m_ad_macs[i];
      }

   if(m_nonce.size())
      {
      poly_double_n(V.data(), V.size());
      V ^= m_nonce;
      }

   if(text_len < block_size())
      {
      poly_double_n(V.data(), V.size());
      xor_buf(V.data(), text, text_len);
      V[text_len] ^= 0x80;
      return m_mac->process(V);
      }

   m_mac->update(text, text_len - block_size());
   xor_buf(V.data(), &text[text_len - block_size()], block_size());
   m_mac->update(V);

   return m_mac->final();
   }

void SIV_Mode::set_ctr_iv(secure_vector<uint8_t> V)
   {
   V[m_bs-8] &= 0x7F;
   V[m_bs-4] &= 0x7F;

   ctr().set_iv(V.data(), V.size());
   }

void SIV_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");

   buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
   msg_buf().clear();

   const secure_vector<uint8_t> V = S2V(buffer.data() + offset, buffer.size() - offset);

   buffer.insert(buffer.begin() + offset, V.begin(), V.end());

   if(buffer.size() != offset + V.size())
      {
      set_ctr_iv(V);
      ctr().cipher1(&buffer[offset + V.size()], buffer.size() - offset - V.size());
      }
   }

void SIV_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");

   buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
   msg_buf().clear();

   const size_t sz = buffer.size() - offset;

   BOTAN_ASSERT(sz >= tag_size(), "We have the tag");

   secure_vector<uint8_t> V(buffer.data() + offset,
                            buffer.data() + offset + block_size());

   if(buffer.size() != offset + V.size())
      {
      set_ctr_iv(V);

      ctr().cipher(buffer.data() + offset + V.size(),
                   buffer.data() + offset,
                   buffer.size() - offset - V.size());
      }

   const secure_vector<uint8_t> T = S2V(buffer.data() + offset, buffer.size() - offset - V.size());

   if(!constant_time_compare(T.data(), V.data(), T.size()))
      throw Integrity_Failure("SIV tag check failed");

   buffer.resize(buffer.size() - tag_size());
   }

}
<commit_msg>Helpful comment<commit_after>/*
* SIV Mode Encryption
* (C) 2013,2017 Jack Lloyd
* (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/siv.h>
#include <botan/block_cipher.h>
#include <botan/cmac.h>
#include <botan/internal/poly_dbl.h>
#include <botan/ctr.h>

namespace Botan {

SIV_Mode::SIV_Mode(BlockCipher* cipher) :
   m_name(cipher->name() + "/SIV"),
   m_ctr(new CTR_BE(cipher->clone())),
   m_mac(new CMAC(cipher)),
   m_bs(cipher->block_size())
   {
   // Not really true but only 128 bit allowed at the moment
   if(m_bs != 16)
      throw Invalid_Argument("SIV requires a 128 bit block cipher");
   }

SIV_Mode::~SIV_Mode()
   {
   // for ~unique_ptr
   }

void SIV_Mode::clear()
   {
   m_ctr->clear();
   m_mac->clear();
   reset();
   }

void SIV_Mode::reset()
   {
   m_nonce.clear();
   m_msg_buf.clear();
   m_ad_macs.clear();
   }

std::string SIV_Mode::name() const
   {
   return m_name;
   }

bool SIV_Mode::valid_nonce_length(size_t) const
   {
   return true;
   }

size_t SIV_Mode::update_granularity() const
   {
   /*
   This value does not particularly matter as regardless SIV_Mode::update
   buffers all input, so in theory this could be 1. However as for instance
   Transform_Filter creates update_granularity() uint8_t buffers, use a
   somewhat large size to avoid bouncing on a tiny buffer.
   */
   return 128;
   }

Key_Length_Specification SIV_Mode::key_spec() const
   {
   return m_mac->key_spec().multiple(2);
   }

void SIV_Mode::key_schedule(const uint8_t key[], size_t length)
   {
   const size_t keylen = length / 2;
   m_mac->set_key(key, keylen);
   m_ctr->set_key(key + keylen, keylen);
   m_ad_macs.clear();
   }

void SIV_Mode::set_associated_data_n(size_t n, const uint8_t ad[], size_t length)
   {
   const size_t max_ads = block_size() * 8 - 2;
   if(n > max_ads)
      throw Invalid_Argument(name() + " allows no more than " + std::to_string(max_ads) + " ADs");

   if(n >= m_ad_macs.size())
      m_ad_macs.resize(n+1);

   m_ad_macs[n] = m_mac->process(ad, length);
   }

void SIV_Mode::start_msg(const uint8_t nonce[], size_t nonce_len)
   {
   if(!valid_nonce_length(nonce_len))
      throw Invalid_IV_Length(name(), nonce_len);

   if(nonce_len)
      m_nonce = m_mac->process(nonce, nonce_len);
   else
      m_nonce.clear();

   m_msg_buf.clear();
   }

size_t SIV_Mode::process(uint8_t buf[], size_t sz)
   {
   // all output is saved for processing in finish
   m_msg_buf.insert(m_msg_buf.end(), buf, buf + sz);
   return 0;
   }

secure_vector<uint8_t> SIV_Mode::S2V(const uint8_t* text, size_t text_len)
   {
   const std::vector<uint8_t> zeros(block_size());

   secure_vector<uint8_t> V = m_mac->process(zeros.data(), zeros.size());

   for(size_t i = 0; i != m_ad_macs.size(); ++i)
      {
      poly_double_n(V.data(), V.size());
      V ^= m_ad_macs[i];
      }

   if(m_nonce.size())
      {
      poly_double_n(V.data(), V.size());
      V ^= m_nonce;
      }

   if(text_len < block_size())
      {
      poly_double_n(V.data(), V.size());
      xor_buf(V.data(), text, text_len);
      V[text_len] ^= 0x80;
      return m_mac->process(V);
      }

   m_mac->update(text, text_len - block_size());
   xor_buf(V.data(), &text[text_len - block_size()], block_size());
   m_mac->update(V);

   return m_mac->final();
   }

void SIV_Mode::set_ctr_iv(secure_vector<uint8_t> V)
   {
   V[m_bs-8] &= 0x7F;
   V[m_bs-4] &= 0x7F;

   ctr().set_iv(V.data(), V.size());
   }

void SIV_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");

   buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
   msg_buf().clear();

   const secure_vector<uint8_t> V = S2V(buffer.data() + offset, buffer.size() - offset);

   buffer.insert(buffer.begin() + offset, V.begin(), V.end());

   if(buffer.size() != offset + V.size())
      {
      set_ctr_iv(V);
      ctr().cipher1(&buffer[offset + V.size()], buffer.size() - offset - V.size());
      }
   }

void SIV_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");

   buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
   msg_buf().clear();

   const size_t sz = buffer.size() - offset;

   BOTAN_ASSERT(sz >= tag_size(), "We have the tag");

   secure_vector<uint8_t> V(buffer.data() + offset,
                            buffer.data() + offset + block_size());

   if(buffer.size() != offset + V.size())
      {
      set_ctr_iv(V);

      ctr().cipher(buffer.data() + offset + V.size(),
                   buffer.data() + offset,
                   buffer.size() - offset - V.size());
      }

   const secure_vector<uint8_t> T = S2V(buffer.data() + offset, buffer.size() - offset - V.size());

   if(!constant_time_compare(T.data(), V.data(), T.size()))
      throw Integrity_Failure("SIV tag check failed");

   buffer.resize(buffer.size() - tag_size());
   }

}
<|endoftext|>


<commit_before>#if 1

#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgGA/TrackballManipulator>
#include <osgGA/AnimationPathManipulator>
#include <iostream>

void singleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
    if (!wsi)
    {
        osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
        return;
    }

    unsigned int width, height;
    wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);

    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
    traits->x = 0;
    traits->y = 0;
    traits->width = width;
    traits->height = height;
#if 0
    traits->windowDecoration = false;
#else
    traits->windowDecoration = true;
#endif
    traits->doubleBuffer = true;
    traits->sharedContext = 0;

    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());

    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
    if (gw)
    {
        osg::notify(osg::INFO)<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;

        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
    }
    else
    {
        osg::notify(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
    }

    unsigned int numCameras = 2;
    double aspectRatioScale = 1.0;///(double)numCameras;
    for(unsigned int i=0; i<numCameras;++i)
    {
        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext(gc.get());
        camera->setViewport(new osg::Viewport((i*width)/numCameras,(i*height)/numCameras, width/numCameras, height/numCameras));
        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
        camera->setDrawBuffer(buffer);
        camera->setReadBuffer(buffer);

        viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::scale(aspectRatioScale,1.0,1.0));
    }
}

void multipleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
    if (!wsi)
    {
        osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
        return;
    }

    unsigned int width, height;
    wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);

    unsigned int numCameras = 4;
    double aspectRatioScale = (double)numCameras;
    double translate_x = double(numCameras)-1;
    for(unsigned int i=0; i<numCameras;++i, translate_x -= 2.0)
    {
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->screenNum = i / 2;
        traits->x = (i*width)/numCameras;
        traits->y = 0;
        traits->width = width/numCameras-1;
        traits->height = height;
    #if 0
        traits->windowDecoration = false;
    #else
        traits->windowDecoration = true;
    #endif
        traits->doubleBuffer = true;
        traits->sharedContext = 0;

        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());

        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
        if (gw)
        {
            osg::notify(osg::INFO)<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;

            gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, traits->width, traits->height );
        }
        else
        {
            osg::notify(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
        }

        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext(gc.get());
        camera->setViewport(new osg::Viewport(0,0, width/numCameras, height));
        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
        camera->setDrawBuffer(buffer);
        camera->setReadBuffer(buffer);

        viewer.addSlave(camera.get(), osg::Matrix::scale(aspectRatioScale, 1.0, 1.0)*osg::Matrix::translate(translate_x, 0.0, 0.0), osg::Matrix() );
    }
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    std::string pathfile;
    osg::ref_ptr<osgGA::AnimationPathManipulator> apm = 0;
    while (arguments.read("-p",pathfile))
    {
        apm = new osgGA::AnimationPathManipulator(pathfile);
        if(!apm.valid() || !(apm->valid()) )
        {
            apm = 0;
        }
    }

    osgViewer::Viewer viewer;

    while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); }
    while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::Viewer::ThreadPerContext); }
    while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::Viewer::ThreadPerCamera); }

    bool limitNumberOfFrames = false;
    unsigned int maxFrames = 10;
    while (arguments.read("--run-till-frame-number",maxFrames)) { limitNumberOfFrames = true; }

    // alternative viewer window setups.
    while (arguments.read("-1")) { singleWindowMultipleCameras(viewer); }
    while (arguments.read("-2")) { multipleWindowMultipleCameras(viewer); }

    if (apm.valid()) viewer.setCameraManipulator(apm.get());
    else viewer.setCameraManipulator( new osgGA::TrackballManipulator() );

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    viewer.setSceneData(loadedModel.get());

    // viewer.realize();

    unsigned int numFrames = 0;
    while(!viewer.done() && !(limitNumberOfFrames && numFrames>=maxFrames))
    {
        viewer.frame();
        ++numFrames;
    }

    return 0;
}
#else

#include <osgViewer/Viewer>
#include <osgDB/ReadFile>

int main( int, char **)
{
    osgViewer::Viewer viewer;
    viewer.setSceneData(osgDB::readNodeFile("cow.osg"));
    viewer.run();
}
#endif
<commit_msg>Cleaned up graphics window setup and added clear graphics window to single window, multiple camera setup.<commit_after>#if 1

#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgGA/TrackballManipulator>
#include <osgGA/AnimationPathManipulator>
#include <iostream>

void singleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
    if (!wsi)
    {
        osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
        return;
    }

    unsigned int width, height;
    wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);

    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
    traits->x = 0;
    traits->y = 0;
    traits->width = width;
    traits->height = height;
    traits->windowDecoration = true;
    traits->doubleBuffer = true;
    traits->sharedContext = 0;

    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
    if (gc.valid())
    {
        osg::notify(osg::INFO)<<"  GraphicsWindow has been created successfully."<<std::endl;

        // need to ensure that the window is cleared make sure that the complete window is set the correct colour
        // rather than just the parts of the window that are under the camera's viewports
        gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f));
        gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }
    else
    {
        osg::notify(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
    }

    unsigned int numCameras = 2;
    double aspectRatioScale = 1.0;///(double)numCameras;
    for(unsigned int i=0; i<numCameras;++i)
    {
        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext(gc.get());
        camera->setViewport(new osg::Viewport((i*width)/numCameras,(i*height)/numCameras, width/numCameras, height/numCameras));
        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
        camera->setDrawBuffer(buffer);
        camera->setReadBuffer(buffer);

        viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::scale(aspectRatioScale,1.0,1.0));
    }
}

void multipleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
    if (!wsi)
    {
        osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
        return;
    }

    unsigned int width, height;
    wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);

    unsigned int numCameras = 4;
    double aspectRatioScale = (double)numCameras;
    double translate_x = double(numCameras)-1;
    for(unsigned int i=0; i<numCameras;++i, translate_x -= 2.0)
    {
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->screenNum = i / 2;
        traits->x = (i*width)/numCameras;
        traits->y = 0;
        traits->width = width/numCameras-1;
        traits->height = height;
        traits->windowDecoration = true;
        traits->doubleBuffer = true;
        traits->sharedContext = 0;

        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
        if (gc.valid())
        {
            osg::notify(osg::INFO)<<"  GraphicsWindow has been created successfully."<<std::endl;
        }
        else
        {
            osg::notify(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
        }

        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext(gc.get());
        camera->setViewport(new osg::Viewport(0,0, width/numCameras, height));
        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
        camera->setDrawBuffer(buffer);
        camera->setReadBuffer(buffer);

        viewer.addSlave(camera.get(), osg::Matrix::scale(aspectRatioScale, 1.0, 1.0)*osg::Matrix::translate(translate_x, 0.0, 0.0), osg::Matrix() );
    }
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    std::string pathfile;
    osg::ref_ptr<osgGA::AnimationPathManipulator> apm = 0;
    while (arguments.read("-p",pathfile))
    {
        apm = new osgGA::AnimationPathManipulator(pathfile);
        if(!apm.valid() || !(apm->valid()) )
        {
            apm = 0;
        }
    }

    osgViewer::Viewer viewer;

    while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); }
    while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::Viewer::ThreadPerContext); }
    while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::Viewer::ThreadPerCamera); }

    bool limitNumberOfFrames = false;
    unsigned int maxFrames = 10;
    while (arguments.read("--run-till-frame-number",maxFrames)) { limitNumberOfFrames = true; }

    // alternative viewer window setups.
    while (arguments.read("-1")) { singleWindowMultipleCameras(viewer); }
    while (arguments.read("-2")) { multipleWindowMultipleCameras(viewer); }

    if (apm.valid()) viewer.setCameraManipulator(apm.get());
    else viewer.setCameraManipulator( new osgGA::TrackballManipulator() );

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    viewer.setSceneData(loadedModel.get());

    // viewer.realize();

    unsigned int numFrames = 0;
    while(!viewer.done() && !(limitNumberOfFrames && numFrames>=maxFrames))
    {
        viewer.frame();
        ++numFrames;
    }

    return 0;
}
#else

#include <osgViewer/Viewer>
#include <osgDB/ReadFile>

int main( int, char **)
{
    osgViewer::Viewer viewer;
    viewer.setSceneData(osgDB::readNodeFile("cow.osg"));
    viewer.run();
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: namedvaluecollection.hxx,v $
 * $Revision: 1.11.20.1 $
 *
 * 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 COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX

#include <comphelper/comphelperdllapi.h>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
/** === end UNO includes === **/

#include <memory>
#include <algorithm>

//........................................................................
namespace comphelper
{
//........................................................................

    // ====================================================================
    // = NamedValueCollection
    // ====================================================================
    struct NamedValueCollection_Impl;
    /** a collection of named values, packed in various formats.
    */
    class COMPHELPER_DLLPUBLIC NamedValueCollection
    {
    private:
        ::std::auto_ptr< NamedValueCollection_Impl >    m_pImpl;

    public:
        NamedValueCollection();

        NamedValueCollection( const NamedValueCollection& _rCopySource );

        NamedValueCollection& operator=( const NamedValueCollection& i_rCopySource );

        /** constructs a collection
            @param  _rElements
                the wrapped elements of the collection. The Any might contain a sequence of
                property values, a sequence of named values, or directly a property value or named value.
                All other cases are worth an assertion in non-product builds.
        */
        NamedValueCollection( const ::com::sun::star::uno::Any& _rElements );

        /** constructs a collection
            @param _rArguments
                a sequence of Any's containing either PropertyValue's or NamedValue's.
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of PropertyValues's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of NamedValue's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        ~NamedValueCollection();

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        /// returns the number of elements in the collection
        size_t  size() const;

        /// determines whether the collection is empty
        bool    empty() const;

        /** merges the content of another collection into |this|
            @param _rAdditionalValues
                the collection whose values are to be merged
            @param _bOverwriteExisting
                defines whether or not elements which are already present in |this|
                should be overwritten (<TRUE/>) or preserved (<FALSE/>).
            @return |*this|
        */
        NamedValueCollection&
                merge(
                    const NamedValueCollection& _rAdditionalValues,
                    bool _bOverwriteExisting
                );

        /** retrieves a value with a given name from the collection, if it is present

            @param _pAsciiValueName
                the ASCII name of the value to retrieve

            @param _out_rValue
                is the output parameter taking the desired value upon successful return. If
                a value with the given name is not present in the collection, or if a wrong-typed
                value is present, then this parameter will not be touched.

            @return
                <TRUE/> if there is a value with the given name, which could successfully
                be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
                value.

                <FALSE/>, if there is no value with the given name.
            @throws IllegalArgumentException
                in case there is a value with the given name, but it cannot legally assigned to
                _out_rValue.
        */
        template < typename VALUE_TYPE >
        bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        template < typename VALUE_TYPE >
        bool    get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        /** retrieves a value with a given name, or defaults it to a given value, if its not present
            in the colllection
        */
        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
        {
            return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
        }

        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
        {
            VALUE_TYPE retVal( _rDefault );
            get_ensureType( _rValueName, retVal );
            return retVal;
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
        {
            return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
        {
            return impl_get( _rValueName );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const sal_Char* _pAsciiValueName ) const
        {
            return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const ::rtl::OUString& _rValueName ) const
        {
            return impl_has( _rValueName );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
        }

        inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
        }

        inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( _rValueName, _rValue );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const sal_Char* _pAsciiValueName )
        {
            return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const ::rtl::OUString& _rValueName )
        {
            return impl_remove( _rValueName );
        }

        /** transforms the collection to a sequence of PropertyValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues ) const;

        /** transforms the collection to a sequence of NamedValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues ) const;

        /** transforms the collection into a sequence of PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                getPropertyValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aValues;
            *this >>= aValues;
            return aValues;
        }

        /** returns a Sequence< Any >, containing PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
                getWrappedPropertyValues() const
        {
            return impl_wrap< ::com::sun::star::beans::PropertyValue >();
        }

        /** returns a Sequence< Any >, containing NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
                getWrappedNamedValues() const
        {
            return impl_wrap< ::com::sun::star::beans::NamedValue >();
        }

        /** transforms the collection into a sequence of NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >
                getNamedValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > aValues;
            *this >>= aValues;
            return aValues;
        }

    private:
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        bool    get_ensureType(
                    const ::rtl::OUString& _rValueName,
                    void* _pValueLocation,
                    const ::com::sun::star::uno::Type& _rExpectedValueType
                ) const;

        const ::com::sun::star::uno::Any&
                impl_get( const ::rtl::OUString& _rValueName ) const;

        bool    impl_has( const ::rtl::OUString& _rValueName ) const;

        bool    impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );

        bool    impl_remove( const ::rtl::OUString& _rValueName );

        template< class VALUE_TYPE >
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > impl_wrap() const
        {
            ::com::sun::star::uno::Sequence< VALUE_TYPE > aValues;
            *this >>= aValues;
            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aWrappedValues( aValues.getLength() );
            ::std::transform(
                aValues.getConstArray(),
                aValues.getConstArray() + aValues.getLength(),
                aWrappedValues.getArray(),
                ::com::sun::star::uno::makeAny< VALUE_TYPE >
            );
            return aWrappedValues;
        }
    };

//........................................................................
} // namespace comphelper
//........................................................................

#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX

<commit_msg>autorecovery: +clear<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: namedvaluecollection.hxx,v $
 * $Revision: 1.11.20.1 $
 *
 * 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 COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX

#include <comphelper/comphelperdllapi.h>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
/** === end UNO includes === **/

#include <memory>
#include <algorithm>

//........................................................................
namespace comphelper
{
//........................................................................

    // ====================================================================
    // = NamedValueCollection
    // ====================================================================
    struct NamedValueCollection_Impl;
    /** a collection of named values, packed in various formats.
    */
    class COMPHELPER_DLLPUBLIC NamedValueCollection
    {
    private:
        ::std::auto_ptr< NamedValueCollection_Impl >    m_pImpl;

    public:
        NamedValueCollection();

        NamedValueCollection( const NamedValueCollection& _rCopySource );

        NamedValueCollection& operator=( const NamedValueCollection& i_rCopySource );

        /** constructs a collection
            @param  _rElements
                the wrapped elements of the collection. The Any might contain a sequence of
                property values, a sequence of named values, or directly a property value or named value.
                All other cases are worth an assertion in non-product builds.
        */
        NamedValueCollection( const ::com::sun::star::uno::Any& _rElements );

        /** constructs a collection
            @param _rArguments
                a sequence of Any's containing either PropertyValue's or NamedValue's.
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of PropertyValues's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of NamedValue's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        ~NamedValueCollection();

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void clear()
        {
            impl_assign( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >() );
        }

        /// returns the number of elements in the collection
        size_t  size() const;

        /// determines whether the collection is empty
        bool    empty() const;

        /** merges the content of another collection into |this|
            @param _rAdditionalValues
                the collection whose values are to be merged
            @param _bOverwriteExisting
                defines whether or not elements which are already present in |this|
                should be overwritten (<TRUE/>) or preserved (<FALSE/>).
            @return |*this|
        */
        NamedValueCollection&
                merge(
                    const NamedValueCollection& _rAdditionalValues,
                    bool _bOverwriteExisting
                );

        /** retrieves a value with a given name from the collection, if it is present

            @param _pAsciiValueName
                the ASCII name of the value to retrieve

            @param _out_rValue
                is the output parameter taking the desired value upon successful return. If
                a value with the given name is not present in the collection, or if a wrong-typed
                value is present, then this parameter will not be touched.

            @return
                <TRUE/> if there is a value with the given name, which could successfully
                be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
                value.

                <FALSE/>, if there is no value with the given name.
            @throws IllegalArgumentException
                in case there is a value with the given name, but it cannot legally assigned to
                _out_rValue.
        */
        template < typename VALUE_TYPE >
        bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        template < typename VALUE_TYPE >
        bool    get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        /** retrieves a value with a given name, or defaults it to a given value, if its not present
            in the colllection
        */
        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
        {
            return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
        }

        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
        {
            VALUE_TYPE retVal( _rDefault );
            get_ensureType( _rValueName, retVal );
            return retVal;
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
        {
            return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
        {
            return impl_get( _rValueName );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const sal_Char* _pAsciiValueName ) const
        {
            return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const ::rtl::OUString& _rValueName ) const
        {
            return impl_has( _rValueName );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
        }

        inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
        }

        inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( _rValueName, _rValue );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const sal_Char* _pAsciiValueName )
        {
            return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const ::rtl::OUString& _rValueName )
        {
            return impl_remove( _rValueName );
        }

        /** transforms the collection to a sequence of PropertyValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues ) const;

        /** transforms the collection to a sequence of NamedValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues ) const;

        /** transforms the collection into a sequence of PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                getPropertyValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aValues;
            *this >>= aValues;
            return aValues;
        }

        /** returns a Sequence< Any >, containing PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
                getWrappedPropertyValues() const
        {
            return impl_wrap< ::com::sun::star::beans::PropertyValue >();
        }

        /** returns a Sequence< Any >, containing NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
                getWrappedNamedValues() const
        {
            return impl_wrap< ::com::sun::star::beans::NamedValue >();
        }

        /** transforms the collection into a sequence of NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >
                getNamedValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > aValues;
            *this >>= aValues;
            return aValues;
        }

    private:
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        bool    get_ensureType(
                    const ::rtl::OUString& _rValueName,
                    void* _pValueLocation,
                    const ::com::sun::star::uno::Type& _rExpectedValueType
                ) const;

        const ::com::sun::star::uno::Any&
                impl_get( const ::rtl::OUString& _rValueName ) const;

        bool    impl_has( const ::rtl::OUString& _rValueName ) const;

        bool    impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );

        bool    impl_remove( const ::rtl::OUString& _rValueName );

        template< class VALUE_TYPE >
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > impl_wrap() const
        {
            ::com::sun::star::uno::Sequence< VALUE_TYPE > aValues;
            *this >>= aValues;
            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aWrappedValues( aValues.getLength() );
            ::std::transform(
                aValues.getConstArray(),
                aValues.getConstArray() + aValues.getLength(),
                aWrappedValues.getArray(),
                ::com::sun::star::uno::makeAny< VALUE_TYPE >
            );
            return aWrappedValues;
        }
    };

//........................................................................
} // namespace comphelper
//........................................................................

#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX

<|endoftext|>


<commit_before>/*
 *            Copyright 2009-2019 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      Licensed under the Apache License, Version 2.0 (the "License")
 *
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *              http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "iexcitoncl.h"
#include "votca/xtp/segmentmapper.h"

#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <votca/tools/constants.h>
#include <votca/tools/propertyiomanipulator.h>
#include <votca/xtp/eeinteractor.h>
#include <votca/xtp/logger.h>

using namespace std;
using namespace boost::filesystem;
using namespace votca::tools;

namespace votca {
namespace xtp {

// +++++++++++++++++++++++++++++ //
// IEXCITON MEMBER FUNCTIONS         //
// +++++++++++++++++++++++++++++ //

void IEXCITON::Initialize(tools::Property& options) {

  cout << endl
       << "... ... Initialized with " << _nThreads << " threads. " << flush;

  _maverick = (_nThreads == 1) ? true : false;

  string key = "options." + Identify();
  _jobfile = options.ifExistsReturnElseThrowRuntimeError<std::string>(
      key + ".job_file");
  _mapfile = options.ifExistsReturnElseThrowRuntimeError<std::string>(
      key + ".map_file");

  if (options.exists(key + ".states")) {
    string parse_string = options.get(key + ".states").as<string>();
    _statemap = FillParseMaps(parse_string);
  }

  cout << "done" << endl;
}

std::map<std::string, QMState> IEXCITON::FillParseMaps(
    const string& Mapstring) {
  Tokenizer split_options(Mapstring, ", \t\n");
  std::map<std::string, QMState> type2level;
  for (const string& substring : split_options) {
    std::vector<string> segmentpnumber;
    Tokenizer tok(substring, ":");
    tok.ToVector(segmentpnumber);
    if (segmentpnumber.size() != 2) {
      throw runtime_error("Parser iqm: Segment and exciton labels:" +
                          substring + "are not separated properly");
    }
    QMState state = QMState(segmentpnumber[1]);
    if (!state.isTransition()) {
      throw std::runtime_error("State to calculate must be a transition state");
    }
    string segmentname = segmentpnumber[0];
    type2level[segmentname] = state;
  }
  return type2level;
}

Job::JobResult IEXCITON::EvalJob(Topology& top, Job& job, QMThread& opThread) {

  // report back to the progress observer
  Job::JobResult jres = Job::JobResult();

  // get the logger from the thread
  Logger& pLog = opThread.getLogger();

  // get the information about the job executed by the thread
  int job_ID = job.getId();
  Property job_input = job.getInput();
  vector<Property*> segment_list = job_input.Select("segment");
  int ID_A = segment_list.front()->getAttribute<int>("id");
  string type_A = segment_list.front()->getAttribute<string>("type");
  string mps_fileA = segment_list.front()->getAttribute<string>("mps_file");
  int ID_B = segment_list.back()->getAttribute<int>("id");
  string type_B = segment_list.back()->getAttribute<string>("type");
  string mps_fileB = segment_list.back()->getAttribute<string>("mps_file");

  Segment& seg_A = top.getSegment(ID_A);
  Segment& seg_B = top.getSegment(ID_B);
  QMNBList& nblist = top.NBList();
  QMPair* pair = nblist.FindPair(&seg_A, &seg_B);
  if (pair == nullptr) {
    throw std::runtime_error(
        "pair between segments " + std::to_string(seg_A.getId()) + ":" +
        std::to_string(seg_B.getId()) + " not found in neighborlist ");
  }

  XTP_LOG_SAVE(logINFO, pLog) << TimeStamp() << " Evaluating pair " << job_ID
                              << " [" << ID_A << ":" << ID_B << "]" << flush;

  StaticMapper map(pLog);
  map.LoadMappingFile(_mapfile);
  StaticSegment seg1 = map.map(*(pair->Seg1()), mps_fileA);
  StaticSegment seg2 = map.map(*(pair->Seg2PbCopy()), mps_fileB);
  eeInteractor actor;
  double JAB = actor.InteractStatic(seg1, seg2);
  _cutoff = 0;
  Property job_summary;
  Property& job_output = job_summary.add("output", "");
  Property& pair_summary = job_output.add("pair", "");
  string nameA = seg_A.getName();
  string nameB = seg_B.getName();
  pair_summary.setAttribute("idA", ID_A);
  pair_summary.setAttribute("idB", ID_B);
  pair_summary.setAttribute("typeA", nameA);
  pair_summary.setAttribute("typeB", nameB);
  Property& coupling_summary = pair_summary.add("Coupling", "");
  coupling_summary.setAttribute("jABstatic", JAB * tools::conv::hrt2ev);

  jres.setOutput(job_summary);
  jres.setStatus(Job::COMPLETE);

  return jres;
}

QMState IEXCITON::GetElementFromMap(const std::string& elementname) const {
  QMState state;
  try {
    state = _statemap.at(elementname);
  } catch (std::out_of_range& error) {
    std::string errormessage =
        "Map does not have segment of type: " + elementname;
    errormessage += "\n segments in map are:";
    for (const auto& s : _statemap) {
      errormessage += "\n\t" + s.first;
    }
    throw std::runtime_error(errormessage);
  }
  return state;
}

void IEXCITON::WriteJobFile(Topology& top) {

  cout << endl << "... ... Writing job file " << flush;
  std::ofstream ofs;
  ofs.open(_jobfile, std::ofstream::out);
  if (!ofs.is_open())
    throw runtime_error("\nERROR: bad file handle: " + _jobfile);
  QMNBList& nblist = top.NBList();
  int jobCount = 0;
  if (nblist.size() == 0) {
    cout << endl << "... ... No pairs in neighbor list, skip." << flush;
    return;
  }

  ofs << "<jobs>" << endl;
  string tag = "";

  for (QMPair* pair : nblist) {
    if (pair->getType() == QMPair::PairType::Excitoncl) {
      int id1 = pair->Seg1()->getId();
      string name1 = pair->Seg1()->getName();
      int id2 = pair->Seg2()->getId();
      string name2 = pair->Seg2()->getName();
      int id = ++jobCount;
      QMState state1 = GetElementFromMap(name1);
      QMState state2 = GetElementFromMap(name2);

      string mps_file1 =
          (boost::format("MP_FILES/%s_%s.mps") % name1 % state1.ToString())
              .str();
      string mps_file2 =
          (boost::format("MP_FILES/%s_%s.mps") % name1 % state2.ToString())
              .str();

      Property Input;
      Property& pInput = Input.add("input", "");
      Property& pSegment1 =
          pInput.add("segment", boost::lexical_cast<string>(id1));
      pSegment1.setAttribute<string>("type", name1);
      pSegment1.setAttribute<int>("id", id1);
      pSegment1.setAttribute<string>("mps_file", mps_file1);
      Property& pSegment2 =
          pInput.add("segment", boost::lexical_cast<string>(id2));
      pSegment2.setAttribute<string>("type", name2);
      pSegment2.setAttribute<int>("id", id2);
      pSegment2.setAttribute<string>("mps_file", mps_file2);

      Job job(id, tag, Input, Job::AVAILABLE);
      job.ToStream(ofs, "xml");
    }
  }

  // CLOSE STREAM
  ofs << "</jobs>" << endl;
  ofs.close();

  cout << endl << "... ... In total " << jobCount << " jobs" << flush;
}

void IEXCITON::ReadJobFile(Topology& top) {

  Property xml;
  vector<Property*> records;
  // gets the neighborlist from the topology
  QMNBList& nblist = top.NBList();
  int number_of_pairs = nblist.size();
  int current_pairs = 0;
  Logger log;
  log.setReportLevel(logINFO);

  // load the QC results in a vector indexed by the pair ID
  load_property_from_xml(xml, _jobfile);
  vector<Property*> jobProps = xml.Select("jobs.job");
  records.resize(number_of_pairs + 1);

  // to skip pairs which are not in the jobfile
  for (unsigned i = 0; i < records.size(); i++) {
    records[i] = NULL;
  }
  // loop over all jobs = pair records in the job file
  for (Property* prop : jobProps) {
    // if job produced an output, then continue with analysis
    if (prop->exists("output") && prop->exists("output.pair")) {
      current_pairs++;
      Property& poutput = prop->get("output.pair");
      int idA = poutput.getAttribute<int>("idA");
      int idB = poutput.getAttribute<int>("idB");
      Segment& segA = top.getSegment(idA);
      Segment& segB = top.getSegment(idB);
      QMPair* qmp = nblist.FindPair(&segA, &segB);

      if (qmp == NULL) {
        XTP_LOG_SAVE(logINFO, log)
            << "No pair " << idA << ":" << idB
            << " found in the neighbor list. Ignoring" << flush;
      } else {
        records[qmp->getId()] = &(prop->get("output.pair"));
      }
    } else {
      Property thebadone = prop->get("id");
      throw runtime_error("\nERROR: Job file incomplete.\n Job with id " +
                          thebadone.as<string>() +
                          " is not finished. Check your job file for FAIL, "
                          "AVAILABLE, or ASSIGNED. Exiting\n");
    }
  }  // finished loading from the file

  // loop over all pairs in the neighbor list
  XTP_LOG_SAVE(logINFO, log)
      << "Neighborlist size " << top.NBList().size() << flush;
  for (QMPair* pair : top.NBList()) {

    if (records[pair->getId()] == NULL)
      continue;  // skip pairs which are not in the jobfile
    double Jeff2 = 0.0;
    double jAB = 0.0;
    if (pair->getType() == QMPair::Excitoncl) {
      Property* pair_property = records[pair->getId()];
      vector<Property*> pCoupling = pair_property->Select("Coupling");
      for (Property* coup : pCoupling) {
        jAB = coup->getAttribute<double>("jABstatic");
      }
      Jeff2 = jAB * jAB * tools::conv::ev2hrt * tools::conv::ev2hrt;
      pair->setJeff2(Jeff2, QMStateType::Singlet);
    }
  }
  XTP_LOG_SAVE(logINFO, log) << "Pairs [total:updated] " << number_of_pairs
                             << ":" << current_pairs << flush;
  cout << log;
}

}  // namespace xtp
};  // namespace votca
<commit_msg>Removed unused variables<commit_after>/*
 *            Copyright 2009-2019 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      Licensed under the Apache License, Version 2.0 (the "License")
 *
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *              http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "iexcitoncl.h"
#include "votca/xtp/segmentmapper.h"

#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <votca/tools/constants.h>
#include <votca/tools/propertyiomanipulator.h>
#include <votca/xtp/eeinteractor.h>
#include <votca/xtp/logger.h>

using namespace std;
using namespace boost::filesystem;
using namespace votca::tools;

namespace votca {
namespace xtp {

// +++++++++++++++++++++++++++++ //
// IEXCITON MEMBER FUNCTIONS         //
// +++++++++++++++++++++++++++++ //

void IEXCITON::Initialize(tools::Property& options) {

  cout << endl
       << "... ... Initialized with " << _nThreads << " threads. " << flush;

  _maverick = (_nThreads == 1) ? true : false;

  string key = "options." + Identify();
  _jobfile = options.ifExistsReturnElseThrowRuntimeError<std::string>(
      key + ".job_file");
  _mapfile = options.ifExistsReturnElseThrowRuntimeError<std::string>(
      key + ".map_file");

  if (options.exists(key + ".states")) {
    string parse_string = options.get(key + ".states").as<string>();
    _statemap = FillParseMaps(parse_string);
  }

  cout << "done" << endl;
}

std::map<std::string, QMState> IEXCITON::FillParseMaps(
    const string& Mapstring) {
  Tokenizer split_options(Mapstring, ", \t\n");
  std::map<std::string, QMState> type2level;
  for (const string& substring : split_options) {
    std::vector<string> segmentpnumber;
    Tokenizer tok(substring, ":");
    tok.ToVector(segmentpnumber);
    if (segmentpnumber.size() != 2) {
      throw runtime_error("Parser iqm: Segment and exciton labels:" +
                          substring + "are not separated properly");
    }
    QMState state = QMState(segmentpnumber[1]);
    if (!state.isTransition()) {
      throw std::runtime_error("State to calculate must be a transition state");
    }
    string segmentname = segmentpnumber[0];
    type2level[segmentname] = state;
  }
  return type2level;
}

Job::JobResult IEXCITON::EvalJob(Topology& top, Job& job, QMThread& opThread) {

  // report back to the progress observer
  Job::JobResult jres = Job::JobResult();

  // get the logger from the thread
  Logger& pLog = opThread.getLogger();

  // get the information about the job executed by the thread
  int job_ID = job.getId();
  Property job_input = job.getInput();
  vector<Property*> segment_list = job_input.Select("segment");
  int ID_A = segment_list.front()->getAttribute<int>("id");
  string mps_fileA = segment_list.front()->getAttribute<string>("mps_file");
  int ID_B = segment_list.back()->getAttribute<int>("id");
  string mps_fileB = segment_list.back()->getAttribute<string>("mps_file");

  Segment& seg_A = top.getSegment(ID_A);
  Segment& seg_B = top.getSegment(ID_B);
  QMNBList& nblist = top.NBList();
  QMPair* pair = nblist.FindPair(&seg_A, &seg_B);
  if (pair == nullptr) {
    throw std::runtime_error(
        "pair between segments " + std::to_string(seg_A.getId()) + ":" +
        std::to_string(seg_B.getId()) + " not found in neighborlist ");
  }

  XTP_LOG_SAVE(logINFO, pLog) << TimeStamp() << " Evaluating pair " << job_ID
                              << " [" << ID_A << ":" << ID_B << "]" << flush;

  StaticMapper map(pLog);
  map.LoadMappingFile(_mapfile);
  StaticSegment seg1 = map.map(*(pair->Seg1()), mps_fileA);
  StaticSegment seg2 = map.map(*(pair->Seg2PbCopy()), mps_fileB);
  eeInteractor actor;
  double JAB = actor.InteractStatic(seg1, seg2);
  _cutoff = 0;
  Property job_summary;
  Property& job_output = job_summary.add("output", "");
  Property& pair_summary = job_output.add("pair", "");
  string nameA = seg_A.getName();
  string nameB = seg_B.getName();
  pair_summary.setAttribute("idA", ID_A);
  pair_summary.setAttribute("idB", ID_B);
  pair_summary.setAttribute("typeA", nameA);
  pair_summary.setAttribute("typeB", nameB);
  Property& coupling_summary = pair_summary.add("Coupling", "");
  coupling_summary.setAttribute("jABstatic", JAB * tools::conv::hrt2ev);

  jres.setOutput(job_summary);
  jres.setStatus(Job::COMPLETE);

  return jres;
}

QMState IEXCITON::GetElementFromMap(const std::string& elementname) const {
  QMState state;
  try {
    state = _statemap.at(elementname);
  } catch (std::out_of_range& error) {
    std::string errormessage =
        "Map does not have segment of type: " + elementname;
    errormessage += "\n segments in map are:";
    for (const auto& s : _statemap) {
      errormessage += "\n\t" + s.first;
    }
    throw std::runtime_error(errormessage);
  }
  return state;
}

void IEXCITON::WriteJobFile(Topology& top) {

  cout << endl << "... ... Writing job file " << flush;
  std::ofstream ofs;
  ofs.open(_jobfile, std::ofstream::out);
  if (!ofs.is_open())
    throw runtime_error("\nERROR: bad file handle: " + _jobfile);
  QMNBList& nblist = top.NBList();
  int jobCount = 0;
  if (nblist.size() == 0) {
    cout << endl << "... ... No pairs in neighbor list, skip." << flush;
    return;
  }

  ofs << "<jobs>" << endl;
  string tag = "";

  for (QMPair* pair : nblist) {
    if (pair->getType() == QMPair::PairType::Excitoncl) {
      int id1 = pair->Seg1()->getId();
      string name1 = pair->Seg1()->getName();
      int id2 = pair->Seg2()->getId();
      string name2 = pair->Seg2()->getName();
      int id = ++jobCount;
      QMState state1 = GetElementFromMap(name1);
      QMState state2 = GetElementFromMap(name2);

      string mps_file1 =
          (boost::format("MP_FILES/%s_%s.mps") % name1 % state1.ToString())
              .str();
      string mps_file2 =
          (boost::format("MP_FILES/%s_%s.mps") % name1 % state2.ToString())
              .str();

      Property Input;
      Property& pInput = Input.add("input", "");
      Property& pSegment1 =
          pInput.add("segment", boost::lexical_cast<string>(id1));
      pSegment1.setAttribute<string>("type", name1);
      pSegment1.setAttribute<int>("id", id1);
      pSegment1.setAttribute<string>("mps_file", mps_file1);
      Property& pSegment2 =
          pInput.add("segment", boost::lexical_cast<string>(id2));
      pSegment2.setAttribute<string>("type", name2);
      pSegment2.setAttribute<int>("id", id2);
      pSegment2.setAttribute<string>("mps_file", mps_file2);

      Job job(id, tag, Input, Job::AVAILABLE);
      job.ToStream(ofs, "xml");
    }
  }

  // CLOSE STREAM
  ofs << "</jobs>" << endl;
  ofs.close();

  cout << endl << "... ... In total " << jobCount << " jobs" << flush;
}

void IEXCITON::ReadJobFile(Topology& top) {

  Property xml;
  vector<Property*> records;
  // gets the neighborlist from the topology
  QMNBList& nblist = top.NBList();
  int number_of_pairs = nblist.size();
  int current_pairs = 0;
  Logger log;
  log.setReportLevel(logINFO);

  // load the QC results in a vector indexed by the pair ID
  load_property_from_xml(xml, _jobfile);
  vector<Property*> jobProps = xml.Select("jobs.job");
  records.resize(number_of_pairs + 1);

  // to skip pairs which are not in the jobfile
  for (unsigned i = 0; i < records.size(); i++) {
    records[i] = NULL;
  }
  // loop over all jobs = pair records in the job file
  for (Property* prop : jobProps) {
    // if job produced an output, then continue with analysis
    if (prop->exists("output") && prop->exists("output.pair")) {
      current_pairs++;
      Property& poutput = prop->get("output.pair");
      int idA = poutput.getAttribute<int>("idA");
      int idB = poutput.getAttribute<int>("idB");
      Segment& segA = top.getSegment(idA);
      Segment& segB = top.getSegment(idB);
      QMPair* qmp = nblist.FindPair(&segA, &segB);

      if (qmp == NULL) {
        XTP_LOG_SAVE(logINFO, log)
            << "No pair " << idA << ":" << idB
            << " found in the neighbor list. Ignoring" << flush;
      } else {
        records[qmp->getId()] = &(prop->get("output.pair"));
      }
    } else {
      Property thebadone = prop->get("id");
      throw runtime_error("\nERROR: Job file incomplete.\n Job with id " +
                          thebadone.as<string>() +
                          " is not finished. Check your job file for FAIL, "
                          "AVAILABLE, or ASSIGNED. Exiting\n");
    }
  }  // finished loading from the file

  // loop over all pairs in the neighbor list
  XTP_LOG_SAVE(logINFO, log)
      << "Neighborlist size " << top.NBList().size() << flush;
  for (QMPair* pair : top.NBList()) {

    if (records[pair->getId()] == NULL)
      continue;  // skip pairs which are not in the jobfile
    double Jeff2 = 0.0;
    double jAB = 0.0;
    if (pair->getType() == QMPair::Excitoncl) {
      Property* pair_property = records[pair->getId()];
      vector<Property*> pCoupling = pair_property->Select("Coupling");
      for (Property* coup : pCoupling) {
        jAB = coup->getAttribute<double>("jABstatic");
      }
      Jeff2 = jAB * jAB * tools::conv::ev2hrt * tools::conv::ev2hrt;
      pair->setJeff2(Jeff2, QMStateType::Singlet);
    }
  }
  XTP_LOG_SAVE(logINFO, log) << "Pairs [total:updated] " << number_of_pairs
                             << ":" << current_pairs << flush;
  cout << log;
}

}  // namespace xtp
};  // namespace votca
<|endoftext|>