<commit_before>// $Id: surface.C,v 1.3 1999/12/28 18:15:29 oliver Exp $

#include <BALL/MATHS/surface.h>

using namespace std;

namespace BALL
{

	Surface::Surface()
		:	valid_(false)
	{
	}

	Surface::Surface(const Surface& /* surface */, bool /* deep */)
	{
		// BAUSTELLE
	}

	Surface::~Surface()
	{
	}

	Size Surface::getNumberOfVertices() const
	{
		return vertices_.size();
	}

	Size Surface::getNumberOfTriangles() const
	{
		return triangles_.size();
	}

	void Surface::smoothNormals()
	{
		if (valid_ == false)
		{
			return;
		}

		Size i;
		// clear all normals
		for (i = 0; i < normals_.size(); i++)
		{
			normals_[i].set(0.0);
		}

		// iterate over all triangles, calculate their normals
		// and add them to the vertices` normals
		for (i = 0; i < triangles_.size(); i++)
		{
			Vector3 v1 = vertices_[triangles_[i].v1];
			Vector3 v2 = vertices_[triangles_[i].v2];
			Vector3 v3 = vertices_[triangles_[i].v3];
			Vector3 normal = (v2 - v1) % (v3 - v1);
			normal.normalize();
			normals_[triangles_[i].v1] += normal;
			normals_[triangles_[i].v2] += normal;
			normals_[triangles_[i].v3] += normal;
		}

		// iterate over all normals and normalize them
		for (i = 0; i < normals_.size(); ++i)
		{
			normals_[i].normalize();
		}
	}

	void Surface::readMSMSFile(const String& vert_filename, const String& face_filename)
	{
		// delete old contents
		normals_.clear();
		vertices_.clear();
		triangles_.clear();

		ifstream	file(vert_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, vert_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		String line;
		while ((line.countFields() != 9) && file)
		{
			line.getline(file);
		}

		String s[6];
		while (file && (line.countFields() == 9))
		{
			// read the vertex coordinates and the normal vector
			line.split(s, 6);
			vertices_.push_back(Vector3(s[0].toFloat(), s[1].toFloat(), s[2].toFloat()));
			normals_.push_back(Vector3(s[3].toFloat(), s[4].toFloat(), s[5].toFloat()));

			// read the next line
			line.getline(file);
		}
		file.close();

		// now read the faces file:
		file.open(face_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, face_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		while ((line.countFields() != 5) && file)
		{
			line.getline(file);
		}

		Triangle t;
		Size number_of_vertices = vertices_.size();
		while (file && (line.countFields() == 5))
		{
			Log.info() << "reading line " << line << endl;
			// read the vertex indices
			line.split(s, 5);
			t.v1 = (Index)s[0].toInt() - 1;
			t.v2 = (Index)s[1].toInt() - 1;
			t.v3 = (Index)s[2].toInt() - 1;

			// if all three vertex indices are valid, insert the triangle
			if ((t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0))
			{
				triangles_.push_back(t);
			}

			// read the next line
			line.getline(file);
		}
		file.close();
	}

	float Surface::getVolume() const
	{
		// BAUSTELLE
		return 0;
	}

	float Surface::getArea() const
	{
		float area = 0;
		// add the areas of all triangles
		for (Size i = 0; i < triangles_.size(); i++)
		{
			//Vector3 v1 = vertices_[triangles_[i].v1];
			//Vector3 v2 = vertices_[triangles_[i].v2];
			//Vector3 v3 = vertices_[triangles_[i].v3];

			// projection of v3 onto v1-v2
			//Vector3	v4 =
			// BAUSTELLE
		}

		return area;
	}

	Surface::Triangle Surface::triangle(Size index) const
	{
		return triangles_[index];
	}

	Vector3 Surface::vertex(Size index) const
	{
		return vertices_[index];
	}

	Vector3 Surface::normal(Size index) const
	{
		return normals_[index];
	}

} // namespace BALL
<commit_msg>removed> superfluous bool argument to copy ctor<commit_after>// $Id: surface.C,v 1.4 2000/03/27 09:08:24 oliver Exp $

#include <BALL/MATHS/surface.h>

using namespace std;

namespace BALL
{

	Surface::Surface()
		:	valid_(false)
	{
	}

	Surface::Surface(const Surface& /* surface */)
	{
		// BAUSTELLE
	}

	Surface::~Surface()
	{
	}

	Size Surface::getNumberOfVertices() const
	{
		return vertices_.size();
	}

	Size Surface::getNumberOfTriangles() const
	{
		return triangles_.size();
	}

	void Surface::smoothNormals()
	{
		if (valid_ == false)
		{
			return;
		}

		Size i;
		// clear all normals
		for (i = 0; i < normals_.size(); i++)
		{
			normals_[i].set(0.0);
		}

		// iterate over all triangles, calculate their normals
		// and add them to the vertices` normals
		for (i = 0; i < triangles_.size(); i++)
		{
			Vector3 v1 = vertices_[triangles_[i].v1];
			Vector3 v2 = vertices_[triangles_[i].v2];
			Vector3 v3 = vertices_[triangles_[i].v3];
			Vector3 normal = (v2 - v1) % (v3 - v1);
			normal.normalize();
			normals_[triangles_[i].v1] += normal;
			normals_[triangles_[i].v2] += normal;
			normals_[triangles_[i].v3] += normal;
		}

		// iterate over all normals and normalize them
		for (i = 0; i < normals_.size(); ++i)
		{
			normals_[i].normalize();
		}
	}

	void Surface::readMSMSFile(const String& vert_filename, const String& face_filename)
	{
		// delete old contents
		normals_.clear();
		vertices_.clear();
		triangles_.clear();

		ifstream	file(vert_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, vert_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		String line;
		while ((line.countFields() != 9) && file)
		{
			line.getline(file);
		}

		String s[6];
		while (file && (line.countFields() == 9))
		{
			// read the vertex coordinates and the normal vector
			line.split(s, 6);
			vertices_.push_back(Vector3(s[0].toFloat(), s[1].toFloat(), s[2].toFloat()));
			normals_.push_back(Vector3(s[3].toFloat(), s[4].toFloat(), s[5].toFloat()));

			// read the next line
			line.getline(file);
		}
		file.close();

		// now read the faces file:
		file.open(face_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, face_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		while ((line.countFields() != 5) && file)
		{
			line.getline(file);
		}

		Triangle t;
		Size number_of_vertices = vertices_.size();
		while (file && (line.countFields() == 5))
		{
			Log.info() << "reading line " << line << endl;
			// read the vertex indices
			line.split(s, 5);
			t.v1 = (Index)s[0].toInt() - 1;
			t.v2 = (Index)s[1].toInt() - 1;
			t.v3 = (Index)s[2].toInt() - 1;

			// if all three vertex indices are valid, insert the triangle
			if ((t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0))
			{
				triangles_.push_back(t);
			}

			// read the next line
			line.getline(file);
		}
		file.close();
	}

	float Surface::getVolume() const
	{
		// BAUSTELLE
		return 0;
	}

	float Surface::getArea() const
	{
		float area = 0;
		// add the areas of all triangles
		for (Size i = 0; i < triangles_.size(); i++)
		{
			//Vector3 v1 = vertices_[triangles_[i].v1];
			//Vector3 v2 = vertices_[triangles_[i].v2];
			//Vector3 v3 = vertices_[triangles_[i].v3];

			// projection of v3 onto v1-v2
			//Vector3	v4 =
			// BAUSTELLE
		}

		return area;
	}

	Surface::Triangle Surface::triangle(Size index) const
	{
		return triangles_[index];
	}

	Vector3 Surface::vertex(Size index) const
	{
		return vertices_[index];
	}

	Vector3 Surface::normal(Size index) const
	{
		return normals_[index];
	}

} // namespace BALL
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: sm3.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: May 11, 2015
 *  Time: 22:13:27
 *  Description: SM3
 *****************************************************************************/
#include <cstring>
#include <cinttypes>
#include <iostream>
#include <fstream>
#include <streambuf>

void sm3_iteration(const uint8_t* data, uint32_t hi[]) {
    // rotate function
    auto left_rotate = [](uint32_t x, const size_t i)->uint32_t {
        return x << i | x >> (sizeof(uint32_t) * 8 - i);
    };

    uint32_t T[64];
    for (size_t i =  0; i < 16; ++i) T[i] = 0x79CC4519;
    for (size_t i = 16; i < 64; ++i) T[i] = 0x7A879D8A;

    uint32_t W[68];
    for (size_t i =  0; i < 16; ++i)
        W[i] = data[4 * i + 0] << 24 | data[4 * i + 1] << 16 |
               data[4 * i + 2] <<  8 | data[4 * i + 3] <<  0;
    //for (int i = 0; i < 16; ++i) std::cout << std::hex << W[i] << ' '; std::cout << std::endl;
    for (size_t i = 16; i < 68; ++i) {
        uint32_t tmp = W[i - 16] ^ W[i - 9] ^ left_rotate(W[i - 3], 15);
        tmp = tmp ^ left_rotate(tmp, 15) ^ left_rotate(tmp, 23);
        W[i] = tmp ^ left_rotate(W[i - 13], 7) ^ W[i - 6];
    }

    //for (int i = 0; i < 68; ++i) std::cout << std::hex << W[i] << ' ';std::cout << std::endl;

    uint32_t W1[64];
    for (size_t i = 0; i < 64; ++i)
        W1[i] = W[i] ^ W[i + 4];
    //for (int i = 0; i < 64; ++i) std::cout << std::hex << W1[i] << ' '; std::cout << std::endl;

    uint32_t A = hi[0], B = hi[1], C = hi[2], D = hi[3],
             E = hi[4], F = hi[5], G = hi[6], H = hi[7];

    for (size_t i = 0; i < 16; ++i) {
        std::cout << std::dec << i << std::hex << ' ' << A << ' ' << B << ' ' << C << ' ' << D << ' ' << E << ' ' << F << ' ' << G << ' ' << H << std::endl;
        uint32_t SS1 = left_rotate(left_rotate(A, 12) + E + left_rotate(T[i], i), 7);
        uint32_t SS2 = SS1 ^ left_rotate(A, 12);
        uint32_t TT1 = (A ^ B ^ C) + D + SS2 + W1[i];
        uint32_t TT2 = (E ^ F ^ G) + H + SS1 + W[i];
        D = C;
        C = left_rotate(B, 9);
        B = A;
        A = TT1;
        H = G;
        G = left_rotate(F, 19);
        F = E;
        E = TT2 ^ left_rotate(TT2, 9) ^ left_rotate(TT2, 17);
    }

    for (size_t i = 16; i < 64; ++i) {
        std::cout << std::dec << i << std::hex << ' ' << A << ' ' << B << ' ' << C << ' ' << D << ' ' << E << ' ' << F << ' ' << G << ' ' << H << std::endl;
        uint32_t SS1 = left_rotate(left_rotate(A, 12) + E + left_rotate(T[i], i), 7);
        uint32_t SS2 = SS1 ^ left_rotate(A, 12);
        uint32_t TT1 = ((A & B) | (B & C) | (A & C)) + D + SS2 + W1[i];
        uint32_t TT2 = ((E & F) | (~E & G)) + H + SS1 + W[i];
        D = C;
        C = left_rotate(B, 9);
        B = A;
        A = TT1;
        H = G;
        G = left_rotate(F, 19);
        F = E;
        E = TT2 ^ left_rotate(TT2, 9) ^ left_rotate(TT2, 17);
    }

    hi[0] ^= A, hi[1] ^= B, hi[2] ^= C, hi[3] ^= D,
    hi[4] ^= E, hi[5] ^= F, hi[6] ^= G, hi[7] ^= H;
}

// len: in bytes
// hash: at least 32 bytes available
void sm3(const void* data, size_t len, char* hash) {
    uint8_t* data_ = (uint8_t*)data;
    constexpr size_t block_size = 64;

    uint32_t h[8] = { 0x7380166F, 0x4914B2B9, 0x172442D7, 0xDA8A0600,
                      0xA96F30BC, 0x163138AA, 0xE38DEE4D, 0xB0FB0E4E };

    size_t ml = len * 8;

    for (size_t i = 0; i < len / block_size; ++i)
        sm3_iteration(data_ + i * block_size, h);

    uint8_t buffer[block_size];

    memcpy(buffer, data_ + len / block_size * block_size, len % block_size);
    len %= block_size;

    // append bit '1'
    buffer[len++] = 0x80;

    if (len % block_size == 0) {
        sm3_iteration(buffer, h);
        len = 0;
    }

    // append until the resulting message length (in bits) is congruent to 448 (mod 512)
    while (len % block_size != 56) {
        buffer[len++] = 0x00;
        if (len % block_size == 0) {
            sm3_iteration(buffer, h);
            len = 0;
        }
    }

    // append length
    buffer[len++] = ml >> 56, buffer[len++] = ml >> 48,
    buffer[len++] = ml >> 40, buffer[len++] = ml >> 32,
    buffer[len++] = ml >> 24, buffer[len++] = ml >> 16,
    buffer[len++] = ml >>  8, buffer[len++] = ml;

    sm3_iteration(buffer, h);

    for (size_t i = 0; i < 32; i += 4)
        hash[i] = h[i / 4] >> 24, hash[i + 1] = h[i / 4] >> 16,
        hash[i + 2] = h[i / 4] >> 8, hash[i + 3] = h[i / 4];
}

int main(int argc, char** argv) {
    uint8_t hash[32];

    if (argc == 1) return 0;

    std::ifstream fin(argv[1]);

    fin.seekg(0, std::ios::end);
    std::string buffer;
    buffer.reserve(fin.tellg());
    fin.seekg(0, std::ios::beg);

    buffer.assign((std::istreambuf_iterator<char>(fin)),
                   std::istreambuf_iterator<char>());

    sm3(buffer.data(), buffer.length(), (char*)hash);

    for (int i = 0; i < 32; ++i)
        printf("%02x", int(hash[i]) & 0xff);
    printf("\n");

}
<commit_msg>remove debug info<commit_after>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: sm3.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: May 11, 2015
 *  Time: 22:13:27
 *  Description: SM3
 *****************************************************************************/
#include <cstring>
#include <cinttypes>
#include <iostream>
#include <fstream>
#include <streambuf>

void sm3_iteration(const uint8_t* data, uint32_t hi[]) {
    // rotate function
    auto left_rotate = [](uint32_t x, const size_t i)->uint32_t {
        return x << i | x >> (sizeof(uint32_t) * 8 - i);
    };

    uint32_t T[64];
    for (size_t i =  0; i < 16; ++i) T[i] = 0x79CC4519;
    for (size_t i = 16; i < 64; ++i) T[i] = 0x7A879D8A;

    uint32_t W[68];
    for (size_t i =  0; i < 16; ++i)
        W[i] = data[4 * i + 0] << 24 | data[4 * i + 1] << 16 |
               data[4 * i + 2] <<  8 | data[4 * i + 3] <<  0;
    for (size_t i = 16; i < 68; ++i) {
        uint32_t tmp = W[i - 16] ^ W[i - 9] ^ left_rotate(W[i - 3], 15);
        tmp = tmp ^ left_rotate(tmp, 15) ^ left_rotate(tmp, 23);
        W[i] = tmp ^ left_rotate(W[i - 13], 7) ^ W[i - 6];
    }

    uint32_t W1[64];
    for (size_t i = 0; i < 64; ++i)
        W1[i] = W[i] ^ W[i + 4];

    uint32_t A = hi[0], B = hi[1], C = hi[2], D = hi[3],
             E = hi[4], F = hi[5], G = hi[6], H = hi[7];

    for (size_t i = 0; i < 16; ++i) {
        uint32_t SS1 = left_rotate(left_rotate(A, 12) + E + left_rotate(T[i], i), 7);
        uint32_t SS2 = SS1 ^ left_rotate(A, 12);
        uint32_t TT1 = (A ^ B ^ C) + D + SS2 + W1[i];
        uint32_t TT2 = (E ^ F ^ G) + H + SS1 + W[i];
        D = C;
        C = left_rotate(B, 9);
        B = A;
        A = TT1;
        H = G;
        G = left_rotate(F, 19);
        F = E;
        E = TT2 ^ left_rotate(TT2, 9) ^ left_rotate(TT2, 17);
    }

    for (size_t i = 16; i < 64; ++i) {
        uint32_t SS1 = left_rotate(left_rotate(A, 12) + E + left_rotate(T[i], i), 7);
        uint32_t SS2 = SS1 ^ left_rotate(A, 12);
        uint32_t TT1 = ((A & B) | (B & C) | (A & C)) + D + SS2 + W1[i];
        uint32_t TT2 = ((E & F) | (~E & G)) + H + SS1 + W[i];
        D = C;
        C = left_rotate(B, 9);
        B = A;
        A = TT1;
        H = G;
        G = left_rotate(F, 19);
        F = E;
        E = TT2 ^ left_rotate(TT2, 9) ^ left_rotate(TT2, 17);
    }

    hi[0] ^= A, hi[1] ^= B, hi[2] ^= C, hi[3] ^= D,
    hi[4] ^= E, hi[5] ^= F, hi[6] ^= G, hi[7] ^= H;
}

// len: in bytes
// hash: at least 32 bytes available
void sm3(const void* data, size_t len, char* hash) {
    uint8_t* data_ = (uint8_t*)data;
    constexpr size_t block_size = 64;

    uint32_t h[8] = { 0x7380166F, 0x4914B2B9, 0x172442D7, 0xDA8A0600,
                      0xA96F30BC, 0x163138AA, 0xE38DEE4D, 0xB0FB0E4E };

    size_t ml = len * 8;

    for (size_t i = 0; i < len / block_size; ++i)
        sm3_iteration(data_ + i * block_size, h);

    uint8_t buffer[block_size];

    memcpy(buffer, data_ + len / block_size * block_size, len % block_size);
    len %= block_size;

    // append bit '1'
    buffer[len++] = 0x80;

    if (len % block_size == 0) {
        sm3_iteration(buffer, h);
        len = 0;
    }

    // append until the resulting message length (in bits) is congruent to 448 (mod 512)
    while (len % block_size != 56) {
        buffer[len++] = 0x00;
        if (len % block_size == 0) {
            sm3_iteration(buffer, h);
            len = 0;
        }
    }

    // append length
    buffer[len++] = ml >> 56, buffer[len++] = ml >> 48,
    buffer[len++] = ml >> 40, buffer[len++] = ml >> 32,
    buffer[len++] = ml >> 24, buffer[len++] = ml >> 16,
    buffer[len++] = ml >>  8, buffer[len++] = ml;

    sm3_iteration(buffer, h);

    for (size_t i = 0; i < 32; i += 4)
        hash[i] = h[i / 4] >> 24, hash[i + 1] = h[i / 4] >> 16,
        hash[i + 2] = h[i / 4] >> 8, hash[i + 3] = h[i / 4];
}

int main(int argc, char** argv) {
    uint8_t hash[32];

    if (argc == 1) return 0;

    std::ifstream fin(argv[1]);

    fin.seekg(0, std::ios::end);
    std::string buffer;
    buffer.reserve(fin.tellg());
    fin.seekg(0, std::ios::beg);

    buffer.assign((std::istreambuf_iterator<char>(fin)),
                   std::istreambuf_iterator<char>());

    sm3(buffer.data(), buffer.length(), (char*)hash);

    for (int i = 0; i < 32; ++i)
        printf("%02x", int(hash[i]) & 0xff);
    printf("\n");

}
<|endoftext|>


<commit_before>/* Copyright 2017 CyberTech Labs Ltd.
 *
 * 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 "searchLinePanel.h"

#include <QtWidgets/QPushButton>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QAbstractScrollArea>
#include <QtWidgets/QStyle>
#include <QtWidgets/QLineEdit>
#include <QtCore/QEvent>
#include <QtGui/QResizeEvent>
#include <QtCore/QPropertyAnimation>

#include "searchLineEdit.h"

using namespace qReal;
using namespace qReal::ui;

SearchLinePanel::SearchLinePanel(QWidget *parent)
	: QFrame(parent)
	, mSearchLineEdit(new SearchLineEdit(this, false))
	, mNextButton(new QPushButton(this))
	, mPreviousButton(new QPushButton(this))
	, mCloseButton(new QPushButton(this))
	, mReplaceButton(new QPushButton(this))
	, mReplaceLineEdit(new QLineEdit(this))
{
	auto gridLayout = new QGridLayout(this);
	auto hLayoutFst = new QHBoxLayout(this);
	auto hLayoutSnd = new QHBoxLayout(this);
	gridLayout->setSizeConstraint(QLayout::SizeConstraint::SetMinimumSize);

	hLayoutFst->addWidget(mSearchLineEdit);

	mNextButton->setIcon(style()->standardIcon(QStyle::SP_ArrowDown));
	mNextButton->setFlat(true);
	mNextButton->setFixedWidth(mNextButton->height());
	hLayoutFst->addWidget(mNextButton);

	mPreviousButton->setIcon(style()->standardIcon(QStyle::SP_ArrowUp));
	mPreviousButton->setFlat(true);
	mPreviousButton->setFixedWidth(mPreviousButton->height());
	hLayoutFst->addWidget(mPreviousButton);

	mCloseButton->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
	mCloseButton->setFlat(true);
	mCloseButton->setFixedWidth(mCloseButton->height());
	hLayoutFst->addWidget(mCloseButton);

	hLayoutSnd->setSizeConstraint(QLayout::SizeConstraint::SetMinimumSize);
	hLayoutSnd->addWidget(mReplaceLineEdit);
	mReplaceButton->setIcon(style()->standardIcon(QStyle::SP_DialogYesButton));
	mReplaceButton->setFlat(true);
	mReplaceButton->setFixedWidth(mReplaceButton->height());
	hLayoutSnd->addWidget(mReplaceButton);

	gridLayout->setContentsMargins(0, 0, 0, 0);
	gridLayout->setMargin(0);
	gridLayout->setSpacing(0);

	gridLayout->addLayout(hLayoutFst, 0, 0);
	gridLayout->addLayout(hLayoutSnd, 1, 0);
	setFrameShape(QFrame::StyledPanel);
	setLayout(gridLayout);

	connect(mSearchLineEdit, &SearchLineEdit::textChanged, [this](const QRegExp &text){
		setSearchLineColor(QColor("white"));
		emit findTextChanged(text);
	});
	connect(mReplaceLineEdit, &QLineEdit::textChanged, this, &SearchLinePanel::replaceTextChanged);
	connect(mNextButton, &QPushButton::pressed, this, &SearchLinePanel::nextPressed);
	connect(mPreviousButton, &QPushButton::pressed, this, &SearchLinePanel::previousPressed);
	connect(mReplaceButton, &QPushButton::pressed, this, &SearchLinePanel::replacePressed);
	connect(mCloseButton, &QPushButton::pressed, [this](){
		emit closePressed();
		detach();
		hide();
	});

	setMode(OperationOptions::Find);
	hide();
}

void SearchLinePanel::reportError()
{
	QPropertyAnimation *animation = new QPropertyAnimation(this, "searchLineColor");
	animation->setDuration(300);
	animation->setStartValue(QColor(255, 0, 0, 0));
	animation->setKeyValueAt(0.5, QColor(255, 0, 0, 255));
	animation->setEndValue(QColor("white"));
	animation->start();
}

void SearchLinePanel::attachTo(QWidget *parent)
{
	detach();
	setParent(parent);
	parent->installEventFilter(this);
	show();
	moveAndAlign();

	mSearchLineEdit->focusMe();
}

void SearchLinePanel::detach()
{
	parent()->removeEventFilter(this);
}

void SearchLinePanel::setMode(const SearchLinePanel::OperationOptions &option)
{
	mCurrentOption = option;

	switch (option) {
		case SearchLinePanel::OperationOptions::Find: {
			mReplaceButton->hide();
			mReplaceLineEdit->hide();
			mPreviousButton->show();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(true);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("Enter search text..."));
			break;
		}

		case SearchLinePanel::OperationOptions::FindAndReplace: {
			mReplaceButton->show();
			mReplaceLineEdit->show();
			mPreviousButton->show();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(true);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("Enter search text..."));
			break;
		}

		case SearchLinePanel::OperationOptions::GoToLineAndColumn: {
			mReplaceButton->hide();
			mReplaceLineEdit->hide();
			mSearchLineEdit->clearText();
			mPreviousButton->hide();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(false);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("<line>:<column>"));
			break;
		}
	}
}

SearchLinePanel::OperationOptions SearchLinePanel::getMode() const
{
	return mCurrentOption;
}

QString SearchLinePanel::getTextForReplace() const
{
	return mReplaceLineEdit->text();
}

QString SearchLinePanel::getTextForFind() const
{
	return mSearchLineEdit->getText();
}

QColor SearchLinePanel::getSearchLineColor() const
{
	return mSearchLineColor;
}

void SearchLinePanel::setSearchLineColor(const QColor &color)
{
	mSearchLineColor = color;
	mSearchLineEdit->setLineEditColor(color);
}

bool SearchLinePanel::eventFilter(QObject *obj, QEvent *event)
{
	if (event->type() == QEvent::Resize) {
		auto resizeEvent = static_cast<QResizeEvent *>(event);
		move(resizeEvent->size().width() - width(), 0);
	}

	if (event->type() == QEvent::LayoutRequest) {
		moveAndAlign();
	}

	return QObject::eventFilter(obj, event);
}

void SearchLinePanel::keyPressEvent(QKeyEvent *event)
{
	if ((event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Return) {
		mPreviousButton->animateClick();
		event->accept();
	} else if (event->key() == Qt::Key_Escape) {
		mCloseButton->animateClick();
		event->accept();
	} else if (not event->modifiers() && event->key() == Qt::Key_Return) {
		mNextButton->animateClick();
		event->accept();
	} else if (event->key() == Qt::Key_Tab && mReplaceLineEdit->isVisible()) {
		mReplaceLineEdit->setFocus(Qt::ShortcutFocusReason);
		event->accept();
	} else if (event->key() == Qt::Key_Backtab && mReplaceLineEdit->isVisible()) {
		mSearchLineEdit->focusMe();
		event->accept();
	} else {
		QFrame::keyPressEvent(event);
	}
}

void SearchLinePanel::moveAndAlign()
{
	if (QWidget *parent = parentWidget()) {
		auto scrollArea = dynamic_cast<QAbstractScrollArea *>(parent);
		if (scrollArea) {
			move(scrollArea->viewport()->width() - width(), 0);
		} else {
			move(parentWidget()->width() - width(), 0);
		}
	}
}
<commit_msg>update button style of search panel button<commit_after>/* Copyright 2017 CyberTech Labs Ltd.
 *
 * 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 "searchLinePanel.h"

#include <QtWidgets/QPushButton>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QAbstractScrollArea>
#include <QtWidgets/QStyle>
#include <QtWidgets/QLineEdit>
#include <QtCore/QEvent>
#include <QtGui/QResizeEvent>
#include <QtCore/QPropertyAnimation>

#include "searchLineEdit.h"

using namespace qReal;
using namespace qReal::ui;

SearchLinePanel::SearchLinePanel(QWidget *parent)
	: QFrame(parent)
	, mSearchLineEdit(new SearchLineEdit(this, false))
	, mNextButton(new QPushButton(this))
	, mPreviousButton(new QPushButton(this))
	, mCloseButton(new QPushButton(this))
	, mReplaceButton(new QPushButton(this))
	, mReplaceLineEdit(new QLineEdit(this))
{
	auto gridLayout = new QGridLayout(this);
	auto hLayoutFst = new QHBoxLayout(this);
	auto hLayoutSnd = new QHBoxLayout(this);
	gridLayout->setSizeConstraint(QLayout::SizeConstraint::SetMinimumSize);

	hLayoutFst->addWidget(mSearchLineEdit);

	mNextButton->setIcon(style()->standardIcon(QStyle::SP_ArrowDown));
	mNextButton->setFlat(true);
	mNextButton->setFixedWidth(mNextButton->height());
	hLayoutFst->addWidget(mNextButton);

	mPreviousButton->setIcon(style()->standardIcon(QStyle::SP_ArrowUp));
	mPreviousButton->setFlat(true);
	mPreviousButton->setFixedWidth(mPreviousButton->height());
	hLayoutFst->addWidget(mPreviousButton);

	mCloseButton->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
	mCloseButton->setFlat(true);
	mCloseButton->setFixedWidth(mCloseButton->height());
	hLayoutFst->addWidget(mCloseButton);

	hLayoutSnd->setSizeConstraint(QLayout::SizeConstraint::SetMinimumSize);
	hLayoutSnd->addWidget(mReplaceLineEdit);
	mReplaceButton->setIcon(style()->standardIcon(QStyle::SP_DialogApplyButton));
	mReplaceButton->setFlat(true);
	mReplaceButton->setFixedWidth(mReplaceButton->height());
	hLayoutSnd->addWidget(mReplaceButton);

	gridLayout->setContentsMargins(0, 0, 0, 0);
	gridLayout->setMargin(0);
	gridLayout->setSpacing(0);

	gridLayout->addLayout(hLayoutFst, 0, 0);
	gridLayout->addLayout(hLayoutSnd, 1, 0);
	setFrameShape(QFrame::StyledPanel);
	setLayout(gridLayout);

	connect(mSearchLineEdit, &SearchLineEdit::textChanged, [this](const QRegExp &text){
		setSearchLineColor(QColor("white"));
		emit findTextChanged(text);
	});
	connect(mReplaceLineEdit, &QLineEdit::textChanged, this, &SearchLinePanel::replaceTextChanged);
	connect(mNextButton, &QPushButton::pressed, this, &SearchLinePanel::nextPressed);
	connect(mPreviousButton, &QPushButton::pressed, this, &SearchLinePanel::previousPressed);
	connect(mReplaceButton, &QPushButton::pressed, this, &SearchLinePanel::replacePressed);
	connect(mCloseButton, &QPushButton::pressed, [this](){
		emit closePressed();
		detach();
		hide();
	});

	setMode(OperationOptions::Find);
	hide();
}

void SearchLinePanel::reportError()
{
	QPropertyAnimation *animation = new QPropertyAnimation(this, "searchLineColor");
	animation->setDuration(300);
	animation->setStartValue(QColor(255, 0, 0, 0));
	animation->setKeyValueAt(0.5, QColor(255, 0, 0, 255));
	animation->setEndValue(QColor("white"));
	animation->start();
}

void SearchLinePanel::attachTo(QWidget *parent)
{
	detach();
	setParent(parent);
	parent->installEventFilter(this);
	show();
	moveAndAlign();

	mSearchLineEdit->focusMe();
}

void SearchLinePanel::detach()
{
	parent()->removeEventFilter(this);
}

void SearchLinePanel::setMode(const SearchLinePanel::OperationOptions &option)
{
	mCurrentOption = option;

	switch (option) {
		case SearchLinePanel::OperationOptions::Find: {
			mReplaceButton->hide();
			mReplaceLineEdit->hide();
			mPreviousButton->show();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(true);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("Enter search text..."));
			break;
		}

		case SearchLinePanel::OperationOptions::FindAndReplace: {
			mReplaceButton->show();
			mReplaceLineEdit->show();
			mPreviousButton->show();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(true);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("Enter search text..."));
			break;
		}

		case SearchLinePanel::OperationOptions::GoToLineAndColumn: {
			mReplaceButton->hide();
			mReplaceLineEdit->hide();
			mSearchLineEdit->clearText();
			mPreviousButton->hide();
			mSearchLineEdit->setSearchOption(SearchLineEdit::SearchOptions::CaseInsensitive);
			mSearchLineEdit->makeSearchOptionsSelectable(false);
			mSearchLineEdit->setPlaceHolderTextToLineEdit(tr("<line>:<column>"));
			break;
		}
	}
}

SearchLinePanel::OperationOptions SearchLinePanel::getMode() const
{
	return mCurrentOption;
}

QString SearchLinePanel::getTextForReplace() const
{
	return mReplaceLineEdit->text();
}

QString SearchLinePanel::getTextForFind() const
{
	return mSearchLineEdit->getText();
}

QColor SearchLinePanel::getSearchLineColor() const
{
	return mSearchLineColor;
}

void SearchLinePanel::setSearchLineColor(const QColor &color)
{
	mSearchLineColor = color;
	mSearchLineEdit->setLineEditColor(color);
}

bool SearchLinePanel::eventFilter(QObject *obj, QEvent *event)
{
	if (event->type() == QEvent::Resize) {
		auto resizeEvent = static_cast<QResizeEvent *>(event);
		move(resizeEvent->size().width() - width(), 0);
	}

	if (event->type() == QEvent::LayoutRequest) {
		moveAndAlign();
	}

	return QObject::eventFilter(obj, event);
}

void SearchLinePanel::keyPressEvent(QKeyEvent *event)
{
	if ((event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Return) {
		mPreviousButton->animateClick();
		event->accept();
	} else if (event->key() == Qt::Key_Escape) {
		mCloseButton->animateClick();
		event->accept();
	} else if (not event->modifiers() && event->key() == Qt::Key_Return) {
		mNextButton->animateClick();
		event->accept();
	} else if (event->key() == Qt::Key_Tab && mReplaceLineEdit->isVisible()) {
		mReplaceLineEdit->setFocus(Qt::ShortcutFocusReason);
		event->accept();
	} else if (event->key() == Qt::Key_Backtab && mReplaceLineEdit->isVisible()) {
		mSearchLineEdit->focusMe();
		event->accept();
	} else {
		QFrame::keyPressEvent(event);
	}
}

void SearchLinePanel::moveAndAlign()
{
	if (QWidget *parent = parentWidget()) {
		auto scrollArea = dynamic_cast<QAbstractScrollArea *>(parent);
		if (scrollArea) {
			move(scrollArea->viewport()->width() - width(), 0);
		} else {
			move(parentWidget()->width() - width(), 0);
		}
	}
}
<|endoftext|>


<commit_before>#include "StateSpace.h"

StateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max, PriorityQueue<Action*,double> queue ):
	angle_max(_angle_max),
	velocity_max(_velocity_max),
	space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (queue)))
{}

StateSpace::~StateSpace()
{
	//ridiculously extensive clean-up
	for(unsigned int i=0 ; i<angle_max ; ++i)
	{
		for(unsigned int j=0 ; j<velocity_max ; ++j)
		{
			PriorityQueue<Action*,double>& queue1=space1[i][j];
			PriorityQueue<Action*,double>& queue2=space2[i][j];

			for(auto iter=queue1.begin(),queue1=list.end() ; iter!=end ; ++iter)
			{
				delete *iter;
			}

			for(auto iter=queue2.begin(),queue2=list.end() ; iter!=end ; ++iter)
			{
				delete *iter;
			}
		}
	}
}

StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
	if(robot_state>1)throw std::domain_error("action index exceeded");
	//return proxy object to accept second [] operator
	return SubscriptProxy1( robot_state ? space1 : space2 );
}

//searches state space by state object
PriorityQueue<Action *, double> StateSpace::StateSearch(State & state)
{
	return (*this)[state->RobotState][state->theta][state->theta_dot];
}
<commit_msg>changed state search function to be a subscript operator overload<commit_after>#include "StateSpace.h"

StateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max, PriorityQueue<Action*,double> queue ):
	angle_max(_angle_max),
	velocity_max(_velocity_max),
	space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (queue)))
{}

StateSpace::~StateSpace()
{
	//ridiculously extensive clean-up
	for(unsigned int i=0 ; i<angle_max ; ++i)
	{
		for(unsigned int j=0 ; j<velocity_max ; ++j)
		{
			PriorityQueue<Action*,double>& queue1=space1[i][j];
			PriorityQueue<Action*,double>& queue2=space2[i][j];

			for(auto iter=queue1.begin(),queue1=list.end() ; iter!=end ; ++iter)
			{
				delete *iter;
			}

			for(auto iter=queue2.begin(),queue2=list.end() ; iter!=end ; ++iter)
			{
				delete *iter;
			}
		}
	}
}

StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
	if(robot_state>1)throw std::domain_error("action index exceeded");
	//return proxy object to accept second [] operator
	return SubscriptProxy1( robot_state ? space1 : space2 );
}

//searches state space by state object
PriorityQueue<Action *, double>& StateSpace::operator[](State & state)
{
	return (*this)[state.RobotState][state.theta][state.theta_dot];
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file  timestamp.cpp
//----------------------------------------------------------------------------
/// \brief Implementation of timestamp class.
//----------------------------------------------------------------------------
// Copyright (c) 2011 Serge Aleynikov <saleyn@gmail.com>
// Created: 2011-09-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2011 Serge Aleynikov <saleyn@gmail.com>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty 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

***** END LICENSE BLOCK *****
*/

#include <utxx/convert.hpp>
#include <utxx/timestamp.hpp>
#include <utxx/compiler_hints.hpp>
#include <utxx/string.hpp>
#include <utxx/time.hpp>
#include <utxx/error.hpp>
#include <stdio.h>

namespace utxx {

boost::mutex            timestamp::s_mutex;
__thread hrtime_t       timestamp::s_last_hrtime;
__thread struct timeval timestamp::s_last_time = {0,0};
__thread time_t         timestamp::s_next_local_midnight_seconds = 0;
__thread time_t         timestamp::s_next_utc_midnight_seconds   = 0;
__thread time_t         timestamp::s_utc_offset = 0;
__thread char           timestamp::s_local_timestamp[16];
__thread char           timestamp::s_utc_timestamp[16];

#ifdef DEBUG_TIMESTAMP
volatile long timestamp::s_hrcalls;
volatile long timestamp::s_syscalls;
#endif

namespace {
    static const char* s_values[] = {
        "none", "time",   "time-msec", "time-usec",
        "date-time", "date-time-msec", "date-time-usec"
    };
}

stamp_type parse_stamp_type(const std::string& a_line) {
    stamp_type t = find_index<stamp_type>(s_values, a_line, (stamp_type)-1, true);

    if (int(t) == -1)
        throw badarg_error("parse_stamp_tpe: invalid timestamp type: ", a_line);
    return t;
}

const char* to_string(stamp_type a_type) {
    assert(a_type < length(s_values));
    return s_values[a_type];
}

char* timestamp::write_time(
    char* a_buf,  const time_val& a_time, stamp_type a_type, bool a_utc,
    char  a_delim, char a_sep)
{
    auto tsec = a_utc ? a_time.sec() : a_time.sec() + s_utc_offset;
    unsigned long n  = tsec/86400;
                  n  = tsec - n*86400;
    int hour = n / 3600;    n -= hour*3600;
    int min  = n / 60;
    int sec  = n - min*60;  n = hour / 10;
    char*  p = a_buf;
    *p++ = '0' + n;     hour -= n*10;
    *p++ = '0' + hour;  n = min / 10;
    if (a_delim) *p++ = a_delim;
    *p++ = '0' + n;     min  -= n*10;
    *p++ = '0' + min;   n = sec / 10;
    if (a_delim) *p++ = a_delim;
    *p++ = '0' + n;     sec -= n*10;
    *p++ = '0' + sec;
    switch (a_type) {
        case TIME:
            break;
        case TIME_WITH_MSEC: {
            if (a_sep) *p++ = a_sep;
            int msec = a_time.msec();
            (void)itoa_right<int, 3>(p, msec, '0');
            p += 3;
            break;
        }
        case TIME_WITH_USEC: {
            if (a_sep) *p++ = a_sep;
            int usec = a_time.usec();
            (void)itoa_right<int, 6>(p, usec, '0');
            p += 6;
            break;
        }
        default:
            throw logic_error("timestamp::write_time: invalid a_type value: ", a_type);
    }
    return p;
}

void timestamp::internal_write_date(
    char* a_buf, time_t a_utc_seconds, bool a_utc, size_t eos_pos, char a_sep)
{
    assert(s_next_utc_midnight_seconds);

    if (!a_utc) a_utc_seconds += timestamp::s_utc_offset;
    int y; unsigned m,d;
    std::tie(y,m,d) = from_gregorian_time(a_utc_seconds);
    int   n = y / 1000;
    char* p = a_buf;
    *p++ = '0' + n; y -= n*1000; n = y/100;
    *p++ = '0' + n; y -= n*100;  n = y/10;
    *p++ = '0' + n; y -= n*10;
    *p++ = '0' + y; n  = m / 10;
    if (a_sep) *p++ = a_sep;
    *p++ = '0' + n; m -= n*10;
    *p++ = '0' + m; n  = d / 10;
    if (a_sep) *p++ = a_sep;
    *p++ = '0' + n; d -= n*10;
    *p++ = '0' + d;
    *p++ = '-';
    if (eos_pos) a_buf[eos_pos] = '\0';
}

void timestamp::write_date(
    char* a_buf, time_t a_utc_seconds, bool a_utc, size_t eos_pos, char a_sep)
{
    // If same day - use cached string value
    if (unlikely(a_utc_seconds >= s_next_utc_midnight_seconds))
        internal_write_date(a_buf, a_utc_seconds, a_utc, eos_pos, a_sep);
    else {
        strncpy(a_buf, a_utc ? s_utc_timestamp : s_local_timestamp, 9);
        if (eos_pos) a_buf[eos_pos] = '\0';
    }
}

void timestamp::update_midnight_seconds(const time_val& a_now)
{
    struct tm tm;
    localtime_r(&a_now.tv_sec(), &tm);
    s_utc_offset = tm.tm_gmtoff;
    s_next_utc_midnight_seconds   = (a_now.sec() - a_now.sec() % 86400) + 86400;
    s_next_local_midnight_seconds = s_next_utc_midnight_seconds  - s_utc_offset;

    // the mutex is not needed here at all - s_timestamp lives in TLS storage
    internal_write_date(s_local_timestamp, a_now.sec(), false, 9, '\0');
    internal_write_date(s_utc_timestamp, a_now.sec(), true, 9, '\0');
}

const time_val& timestamp::now() {
    // thread safe - we use TLV storage
    s_last_time   = time_val::universal_time().timeval();
    s_last_hrtime = high_res_timer::gettime();
    return last_time();
}

void timestamp::update_slow()
{
    now();
    #ifdef DEBUG_TIMESTAMP
    atomic::inc(&s_syscalls);
    #endif

    // FIXME: the method below will produce incorrect time stamps during
    // switch to/from daylight savings time because of the unaccounted
    // utc_offset change.
    if (unlikely(last_time().sec() >= s_next_utc_midnight_seconds))
        update_midnight_seconds(last_time());
}

size_t timestamp::format_size(stamp_type a_tp)
{
    switch (a_tp) {
        case NO_TIMESTAMP:          return 0;
        case TIME:                  return 8;
        case TIME_WITH_USEC:        return 15;
        case TIME_WITH_MSEC:        return 12;
        case DATE_TIME:             return 17;
        case DATE_TIME_WITH_USEC:   return 24;
        case DATE_TIME_WITH_MSEC:   return 21;
        default:
            assert(false);
    }
}

int timestamp::format(stamp_type a_tp,
    const struct timeval* tv, char* a_buf, size_t a_sz, bool a_utc)
{
    BOOST_ASSERT((a_tp < DATE_TIME && a_sz > 14) || a_sz > 25);

    if (unlikely(a_tp == NO_TIMESTAMP)) {
        a_buf[0] = '\0';
        return 0;
    }

    long midnight = a_utc ? s_next_utc_midnight_seconds : s_next_local_midnight_seconds;
    if (unlikely(tv->tv_sec >= midnight)) {
        timestamp ts; ts.update();
    }

    // If small time is given, it's a relative value.
    bool l_rel  = tv->tv_sec < 86400;
    time_t sec  = l_rel ? tv->tv_sec : tv->tv_sec + (a_utc ? 0 : s_utc_offset);
    long l_usec = tv->tv_usec;

    switch (a_tp) {
        case TIME:
            write_time(a_buf, sec, 8);
            return 8;
        case TIME_WITH_USEC:
            write_time(a_buf, sec, 15);
            a_buf[8] = '.';
            itoa_right(a_buf+9, 6, l_usec, '0');
            return 15;
        case TIME_WITH_MSEC:
            write_time(a_buf, sec, 12);
            a_buf[8] = '.';
            itoa_right(a_buf+9, 3, l_usec / 1000, '0');
            return 12;
        case DATE_TIME:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 8);
            return 17;
        case DATE_TIME_WITH_USEC:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 15);
            a_buf[17] = '.';
            itoa_right(a_buf+18, 6, l_usec, '0');
            return 24;
        case DATE_TIME_WITH_MSEC:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 12);
            a_buf[17] = '.';
            itoa_right(a_buf+18, 3, l_usec / 1000, '0');
            return 21;
        default:
            strcpy(a_buf, "UNDEFINED");
            return -1;
    }
}

time_val timestamp::from_string(const char* a_datetime, size_t n, bool a_utc) {
    if (unlikely(a_datetime[8] != '-' ||
                 a_datetime[11] != ':' || a_datetime[14] != ':' ||
                 n < 17))
        throw badarg_error("Invalid time format: ", std::string(a_datetime, n));

    const char* p = a_datetime;

    auto parse = [&p](int digits) {
        int i = 0; const char* end = p + digits;
        for (; p != end; ++p) i = (10*i) + (*p - '0');
        return i;
    };

    int      year = parse(4);
    unsigned mon  = parse(2);
    unsigned day  = parse(2); p++;
    unsigned hour = parse(2); p++;
    unsigned min  = parse(2); p++;
    unsigned sec  = parse(2);
    unsigned usec = 0;

    const char* dot = p++;

    if (*dot == '.' && n > 17)
    {
        const char* end = p + std::min<size_t>(6, n - (p - a_datetime));
        while (*p >= '0' && *p <= '9' && p != end)
            usec = 10*usec + (*p++ - '0');

        int len = p - dot - 1;
        switch (len)
        {
            case 3:  usec *= 1000; break;
            case 6:  break;
            default: throw badarg_error("Invalid millisecond format: ",
                                        std::string(a_datetime, end - a_datetime));
        }
    }

    return a_utc
         ? time_val::universal_time(year, mon, day, hour, min, sec, usec)
         : time_val::local_time(year, mon, day, hour, min, sec, usec);
}

} // namespace utxx
<commit_msg>Fixed an assert problem<commit_after>//----------------------------------------------------------------------------
/// \file  timestamp.cpp
//----------------------------------------------------------------------------
/// \brief Implementation of timestamp class.
//----------------------------------------------------------------------------
// Copyright (c) 2011 Serge Aleynikov <saleyn@gmail.com>
// Created: 2011-09-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2011 Serge Aleynikov <saleyn@gmail.com>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty 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

***** END LICENSE BLOCK *****
*/

#include <utxx/convert.hpp>
#include <utxx/timestamp.hpp>
#include <utxx/compiler_hints.hpp>
#include <utxx/string.hpp>
#include <utxx/time.hpp>
#include <utxx/error.hpp>
#include <stdio.h>

namespace utxx {

boost::mutex            timestamp::s_mutex;
__thread hrtime_t       timestamp::s_last_hrtime;
__thread struct timeval timestamp::s_last_time = {0,0};
__thread time_t         timestamp::s_next_local_midnight_seconds = 0;
__thread time_t         timestamp::s_next_utc_midnight_seconds   = 0;
__thread time_t         timestamp::s_utc_offset = 0;
__thread char           timestamp::s_local_timestamp[16];
__thread char           timestamp::s_utc_timestamp[16];

#ifdef DEBUG_TIMESTAMP
volatile long timestamp::s_hrcalls;
volatile long timestamp::s_syscalls;
#endif

namespace {
    static const char* s_values[] = {
        "none", "time",   "time-msec", "time-usec",
        "date-time", "date-time-msec", "date-time-usec"
    };
}

stamp_type parse_stamp_type(const std::string& a_line) {
    stamp_type t = find_index<stamp_type>(s_values, a_line, (stamp_type)-1, true);

    if (int(t) == -1)
        throw badarg_error("parse_stamp_tpe: invalid timestamp type: ", a_line);
    return t;
}

const char* to_string(stamp_type a_type) {
    assert(a_type < length(s_values));
    return s_values[a_type];
}

char* timestamp::write_time(
    char* a_buf,  const time_val& a_time, stamp_type a_type, bool a_utc,
    char  a_delim, char a_sep)
{
    auto tsec = a_utc ? a_time.sec() : a_time.sec() + s_utc_offset;
    unsigned long n  = tsec/86400;
                  n  = tsec - n*86400;
    int hour = n / 3600;    n -= hour*3600;
    int min  = n / 60;
    int sec  = n - min*60;  n = hour / 10;
    char*  p = a_buf;
    *p++ = '0' + n;     hour -= n*10;
    *p++ = '0' + hour;  n = min / 10;
    if (a_delim) *p++ = a_delim;
    *p++ = '0' + n;     min  -= n*10;
    *p++ = '0' + min;   n = sec / 10;
    if (a_delim) *p++ = a_delim;
    *p++ = '0' + n;     sec -= n*10;
    *p++ = '0' + sec;
    switch (a_type) {
        case TIME:
            break;
        case TIME_WITH_MSEC: {
            if (a_sep) *p++ = a_sep;
            int msec = a_time.msec();
            (void)itoa_right<int, 3>(p, msec, '0');
            p += 3;
            break;
        }
        case TIME_WITH_USEC: {
            if (a_sep) *p++ = a_sep;
            int usec = a_time.usec();
            (void)itoa_right<int, 6>(p, usec, '0');
            p += 6;
            break;
        }
        default:
            throw logic_error("timestamp::write_time: invalid a_type value: ", a_type);
    }
    return p;
}

void timestamp::internal_write_date(
    char* a_buf, time_t a_utc_seconds, bool a_utc, size_t eos_pos, char a_sep)
{
    assert(s_next_utc_midnight_seconds);

    if (!a_utc) a_utc_seconds += timestamp::s_utc_offset;
    int y; unsigned m,d;
    std::tie(y,m,d) = from_gregorian_time(a_utc_seconds);
    int   n = y / 1000;
    char* p = a_buf;
    *p++ = '0' + n; y -= n*1000; n = y/100;
    *p++ = '0' + n; y -= n*100;  n = y/10;
    *p++ = '0' + n; y -= n*10;
    *p++ = '0' + y; n  = m / 10;
    if (a_sep) *p++ = a_sep;
    *p++ = '0' + n; m -= n*10;
    *p++ = '0' + m; n  = d / 10;
    if (a_sep) *p++ = a_sep;
    *p++ = '0' + n; d -= n*10;
    *p++ = '0' + d;
    *p++ = '-';
    if (eos_pos) a_buf[eos_pos] = '\0';
}

void timestamp::write_date(
    char* a_buf, time_t a_utc_seconds, bool a_utc, size_t eos_pos, char a_sep)
{
    // If same day - use cached string value
    if (unlikely(a_utc_seconds >= s_next_utc_midnight_seconds)) {
        update_midnight_seconds(now_utc());
        internal_write_date(a_buf, a_utc_seconds, a_utc, eos_pos, a_sep);
    } else {
        strncpy(a_buf, a_utc ? s_utc_timestamp : s_local_timestamp, 9);
        if (eos_pos) a_buf[eos_pos] = '\0';
    }
}

void timestamp::update_midnight_seconds(const time_val& a_now)
{
    struct tm tm;
    localtime_r(&a_now.tv_sec(), &tm);
    s_utc_offset = tm.tm_gmtoff;
    s_next_utc_midnight_seconds   = (a_now.sec() - a_now.sec() % 86400) + 86400;
    s_next_local_midnight_seconds = s_next_utc_midnight_seconds  - s_utc_offset;

    // the mutex is not needed here at all - s_timestamp lives in TLS storage
    internal_write_date(s_local_timestamp, a_now.sec(), false, 9, '\0');
    internal_write_date(s_utc_timestamp, a_now.sec(), true, 9, '\0');
}

const time_val& timestamp::now() {
    // thread safe - we use TLV storage
    s_last_time   = time_val::universal_time().timeval();
    s_last_hrtime = high_res_timer::gettime();
    return last_time();
}

void timestamp::update_slow()
{
    now();
    #ifdef DEBUG_TIMESTAMP
    atomic::inc(&s_syscalls);
    #endif

    // FIXME: the method below will produce incorrect time stamps during
    // switch to/from daylight savings time because of the unaccounted
    // utc_offset change.
    if (unlikely(last_time().sec() >= s_next_utc_midnight_seconds))
        update_midnight_seconds(last_time());
}

size_t timestamp::format_size(stamp_type a_tp)
{
    switch (a_tp) {
        case NO_TIMESTAMP:          return 0;
        case TIME:                  return 8;
        case TIME_WITH_USEC:        return 15;
        case TIME_WITH_MSEC:        return 12;
        case DATE_TIME:             return 17;
        case DATE_TIME_WITH_USEC:   return 24;
        case DATE_TIME_WITH_MSEC:   return 21;
        default:
            assert(false);
    }
}

int timestamp::format(stamp_type a_tp,
    const struct timeval* tv, char* a_buf, size_t a_sz, bool a_utc)
{
    BOOST_ASSERT((a_tp < DATE_TIME && a_sz > 14) || a_sz > 25);

    if (unlikely(a_tp == NO_TIMESTAMP)) {
        a_buf[0] = '\0';
        return 0;
    }

    long midnight = a_utc ? s_next_utc_midnight_seconds : s_next_local_midnight_seconds;
    if (unlikely(tv->tv_sec >= midnight)) {
        timestamp ts; ts.update();
    }

    // If small time is given, it's a relative value.
    bool l_rel  = tv->tv_sec < 86400;
    time_t sec  = l_rel ? tv->tv_sec : tv->tv_sec + (a_utc ? 0 : s_utc_offset);
    long l_usec = tv->tv_usec;

    switch (a_tp) {
        case TIME:
            write_time(a_buf, sec, 8);
            return 8;
        case TIME_WITH_USEC:
            write_time(a_buf, sec, 15);
            a_buf[8] = '.';
            itoa_right(a_buf+9, 6, l_usec, '0');
            return 15;
        case TIME_WITH_MSEC:
            write_time(a_buf, sec, 12);
            a_buf[8] = '.';
            itoa_right(a_buf+9, 3, l_usec / 1000, '0');
            return 12;
        case DATE_TIME:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 8);
            return 17;
        case DATE_TIME_WITH_USEC:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 15);
            a_buf[17] = '.';
            itoa_right(a_buf+18, 6, l_usec, '0');
            return 24;
        case DATE_TIME_WITH_MSEC:
            write_date(a_buf, l_rel ? s_last_time.tv_sec : tv->tv_sec, a_utc, 9);
            write_time(a_buf+9, sec, 12);
            a_buf[17] = '.';
            itoa_right(a_buf+18, 3, l_usec / 1000, '0');
            return 21;
        default:
            strcpy(a_buf, "UNDEFINED");
            return -1;
    }
}

time_val timestamp::from_string(const char* a_datetime, size_t n, bool a_utc) {
    if (unlikely(a_datetime[8] != '-' ||
                 a_datetime[11] != ':' || a_datetime[14] != ':' ||
                 n < 17))
        throw badarg_error("Invalid time format: ", std::string(a_datetime, n));

    const char* p = a_datetime;

    auto parse = [&p](int digits) {
        int i = 0; const char* end = p + digits;
        for (; p != end; ++p) i = (10*i) + (*p - '0');
        return i;
    };

    int      year = parse(4);
    unsigned mon  = parse(2);
    unsigned day  = parse(2); p++;
    unsigned hour = parse(2); p++;
    unsigned min  = parse(2); p++;
    unsigned sec  = parse(2);
    unsigned usec = 0;

    const char* dot = p++;

    if (*dot == '.' && n > 17)
    {
        const char* end = p + std::min<size_t>(6, n - (p - a_datetime));
        while (*p >= '0' && *p <= '9' && p != end)
            usec = 10*usec + (*p++ - '0');

        int len = p - dot - 1;
        switch (len)
        {
            case 3:  usec *= 1000; break;
            case 6:  break;
            default: throw badarg_error("Invalid millisecond format: ",
                                        std::string(a_datetime, end - a_datetime));
        }
    }

    return a_utc
         ? time_val::universal_time(year, mon, day, hour, min, sec, usec)
         : time_val::local_time(year, mon, day, hour, min, sec, usec);
}

} // namespace utxx
<|endoftext|>


<commit_before>#include <iostream>

#include "orbital_space.h"
#include "wdiag_operator.h"
#include "wdiag_theorem.h"
#include "wsum.h"

using namespace std;

int main(int argc, const char *argv[]) {
  osi = std::make_shared<OrbitalSpaceInfo>();
  osi->add_space("o", DMStructure::DoublyOccupied,
                 {"i", "j", "k", "l", "m", "n"});
  osi->add_space("v", DMStructure::Unoccupied, {"a", "b", "c", "d", "e", "f"});
  // Convenience variables
  std::string o = "o";
  std::string v = "v";

  auto opT1 = make_diag_operator("t", {v}, {o});
  auto opT2 = make_diag_operator("t", {v, v}, {o, o});

  auto opH1oo = make_diag_operator("f", {o}, {o});
  auto opH1ov = make_diag_operator("f", {o}, {v});
  auto opH1vo = make_diag_operator("f", {v}, {o});
  auto opH1vv = make_diag_operator("f", {v}, {v});

  auto opH2oooo = make_diag_operator("v", {o, o}, {o, o});
  auto opH2ovoo = make_diag_operator("v", {o, v}, {o, o});
  auto opH2ooov = make_diag_operator("v", {o, o}, {o, v});
  auto opH2ovov = make_diag_operator("v", {o, v}, {o, v});
  auto opH2vvoo = make_diag_operator("v", {v, v}, {o, o});
  auto opH2oovv = make_diag_operator("v", {o, o}, {v, v});
  auto opH2vvov = make_diag_operator("v", {v, v}, {o, v});
  auto opH2ovvv = make_diag_operator("v", {o, v}, {v, v});
  auto opH2vvvv = make_diag_operator("v", {v, v}, {v, v});

  auto opR1 = make_diag_operator("R1", {o}, {v});
  auto opR2 = make_diag_operator("R2", {o, o}, {v, v});

  WDiagTheorem wdt;
  WSum sum;

  sum += wdt.contract(1, {opH1ov, opT1}, 0, 0);
  //  auto e2 = wdt.contract(1, {opH2oovv, opT2}, 0, 0);
  //  auto e3 = wdt.contract(r1_2, {opH2oovv, opT1, opT1}, 0, 0);

  WIndex o0(0, 0);
  WIndex v0(1, 0);

  WAlgebraicTerm e1_term;
  e1_term.add(WTensor("f", {o0}, {v0}));
  e1_term.add(WTensor("t", {v0}, {o0}));
  WSum e1_sum;
  e1_sum.add(e1_term);
  e1_sum.add(e1_term);

  e1_sum -= sum;

  cout << "Sum of all terms:" << endl;
  cout << sum << endl;
  cout << e1_sum << endl;
  auto size = e1_sum.sum().size();
  return size;
}
<commit_msg>Fix test.<commit_after>#include <iostream>

#include "orbital_space.h"
#include "wdiag_operator.h"
#include "wdiag_theorem.h"
#include "wsum.h"

using namespace std;

int main(int argc, const char *argv[]) {
  osi = std::make_shared<OrbitalSpaceInfo>();
  osi->add_space("o", DMStructure::DoublyOccupied,
                 {"i", "j", "k", "l", "m", "n"});
  osi->add_space("v", DMStructure::Unoccupied, {"a", "b", "c", "d", "e", "f"});
  // Convenience variables
  std::string o = "o";
  std::string v = "v";

  auto opT1 = make_diag_operator("t", {v}, {o});
  auto opT2 = make_diag_operator("t", {v, v}, {o, o});

  auto opH1oo = make_diag_operator("f", {o}, {o});
  auto opH1ov = make_diag_operator("f", {o}, {v});
  auto opH1vo = make_diag_operator("f", {v}, {o});
  auto opH1vv = make_diag_operator("f", {v}, {v});

  auto opH2oooo = make_diag_operator("v", {o, o}, {o, o});
  auto opH2ovoo = make_diag_operator("v", {o, v}, {o, o});
  auto opH2ooov = make_diag_operator("v", {o, o}, {o, v});
  auto opH2ovov = make_diag_operator("v", {o, v}, {o, v});
  auto opH2vvoo = make_diag_operator("v", {v, v}, {o, o});
  auto opH2oovv = make_diag_operator("v", {o, o}, {v, v});
  auto opH2vvov = make_diag_operator("v", {v, v}, {o, v});
  auto opH2ovvv = make_diag_operator("v", {o, v}, {v, v});
  auto opH2vvvv = make_diag_operator("v", {v, v}, {v, v});

  auto opR1 = make_diag_operator("R1", {o}, {v});
  auto opR2 = make_diag_operator("R2", {o, o}, {v, v});

  WDiagTheorem wdt;
  WSum sum;

  sum += wdt.contract(1, {opH1ov, opT1}, 0, 0);
  //  auto e2 = wdt.contract(1, {opH2oovv, opT2}, 0, 0);
  //  auto e3 = wdt.contract(r1_2, {opH2oovv, opT1, opT1}, 0, 0);

  WIndex o0(0, 0);
  WIndex v0(1, 0);

  WAlgebraicTerm e1_term;
  e1_term.add(WTensor("f", {o0}, {v0}));
  e1_term.add(WTensor("t", {v0}, {o0}));
  WSum e1_sum;
  e1_sum.add(e1_term);

  e1_sum -= sum;

//  cout << "Sum of all terms:" << endl;
//  cout << sum << endl;
//  cout << e1_sum << endl;
  auto size = e1_sum.sum().size();
  return size;
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2012 The LibYuv Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS. All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "libyuv/basic_types.h"

#include "libyuv/compare_row.h"
#include "libyuv/row.h"

#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif

#if !defined(LIBYUV_DISABLE_NEON) && defined(__ARM_NEON__) && \
    !defined(__aarch64__)

// 256 bits at a time
uint32 HammingDistance_NEON(const uint8* src_a, const uint8* src_b, int count) {
  uint32 diff;
  uint32 total_diff = 0;

  for (int i = 0; i < count; i += 32, src_a += 32, src_b += 32) {

  __asm__ volatile(
      // Load constants.
      "vmov.u8             q12, #0x55          \n\t"  // m1.
      "vmov.u8             q13, #0x33          \n\t"  // m2.
      "vmov.u8             q14, #0x0f          \n\t"  // m4.
      "vmov.u8             q15, #0x01          \n\t"  // h01.

      // Load d1
      "vld1.32             {q0,q1}, [%1]       \n\t"  // load d1.

      // Load d2
      "vld1.32             {q2, q3}, [%2]      \n\t"  // load d2.

      // xor
      "veor.32             q0, q0, q2          \n\t"  // xor left side.
      "veor.32             q3, q1, q3          \n\t"  // xor right side.

      // x -= (x >> 1) & m1;
      "vshr.u32            q1, q0, #1           \n\t"
      "vshr.u32            q4, q3, #1           \n\t"
      "vand.32             q1, q1, q12         \n\t"
      "vand.32             q4, q4, q12         \n\t"
      "vsub.u32            q0, q0, q1          \n\t"
      "vsub.u32            q3, q3, q4          \n\t"

      // x = (x & m2) + ((x >> 2) & m2);
      "vand.32             q1, q0, q13         \n\t"
      "vand.32             q4, q3, q13         \n\t"
      "vshr.u32            q2, q0, #2           \n\t"
      "vshr.u32            q5, q3, #2           \n\t"
      "vand.32             q2, q2, q13         \n\t"
      "vand.32             q5, q5, q13         \n\t"
      "vadd.u32            q0, q1, q2          \n\t"
      "vadd.u32            q3, q4, q5          \n\t"

      // x = (x + (x >> 4)) & m4;
      "vshr.u32            q1, q0, #4           \n\t"
      "vshr.u32            q4, q3, #4           \n\t"
      "vadd.u32            q0, q0, q1          \n\t"
      "vadd.u32            q3, q3, q4          \n\t"
      "vand.32             q0, q0, q14         \n\t"
      "vand.32             q3, q3, q14         \n\t"

      // (x * h01) >> 24;
      "vmul.u32            q0, q0, q15         \n\t"
      "vmul.u32            q3, q3, q15         \n\t"
      "vshr.u32            q0, q0, #24          \n\t"
      "vshr.u32            q3, q3, #24          \n\t"

      // sum distances
      "vpadd.u32           d0, d0, d1          \n\t"
      "vpadd.u32           d6, d6, d7          \n\t"
      "vpadd.u32           d0, d0, d0          \n\t"
      "vpadd.u32           d6, d6, d6          \n\t"

      // add d0,d6.
      "vadd.u32            d0, d0, d6          \n\t"

      // Move distance to return register.
      "vmov.32             %0, d0[0]           \n\t"

      // Output.
      : "=r"(diff), "+r"(src_a), "+r"(src_b)
        // input
      :
      // Clobber list.
      : "q0", "q1", "q2", "q3", "q4", "q5", "q12", "q13", "q14", "q15");
    total_diff += diff;
  }
  return total_diff;
}

uint32 SumSquareError_NEON(const uint8* src_a, const uint8* src_b, int count) {
  uint32 sse;
  asm volatile (
    "vmov.u8    q8, #0                         \n"
    "vmov.u8    q10, #0                        \n"
    "vmov.u8    q9, #0                         \n"
    "vmov.u8    q11, #0                        \n"

  "1:                                          \n"
    MEMACCESS(0)
    "vld1.8     {q0}, [%0]!                    \n"
    MEMACCESS(1)
    "vld1.8     {q1}, [%1]!                    \n"
    "subs       %2, %2, #16                    \n"
    "vsubl.u8   q2, d0, d2                     \n"
    "vsubl.u8   q3, d1, d3                     \n"
    "vmlal.s16  q8, d4, d4                     \n"
    "vmlal.s16  q9, d6, d6                     \n"
    "vmlal.s16  q10, d5, d5                    \n"
    "vmlal.s16  q11, d7, d7                    \n"
    "bgt        1b                             \n"

    "vadd.u32   q8, q8, q9                     \n"
    "vadd.u32   q10, q10, q11                  \n"
    "vadd.u32   q11, q8, q10                   \n"
    "vpaddl.u32 q1, q11                        \n"
    "vadd.u64   d0, d2, d3                     \n"
    "vmov.32    %3, d0[0]                      \n"
    : "+r"(src_a),
      "+r"(src_b),
      "+r"(count),
      "=r"(sse)
    :
    : "memory", "cc", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11");
  return sse;
}

#endif  // defined(__ARM_NEON__) && !defined(__aarch64__)

#ifdef __cplusplus
}  // extern "C"
}  // namespace libyuv
#endif
<commit_msg>HammingDistance_NEON optimized looping<commit_after>/*
 *  Copyright 2012 The LibYuv Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS. All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "libyuv/basic_types.h"

#include "libyuv/compare_row.h"
#include "libyuv/row.h"

#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif

#if !defined(LIBYUV_DISABLE_NEON) && defined(__ARM_NEON__) && \
    !defined(__aarch64__)

// 256 bits at a time
uint32 HammingDistance_NEON(const uint8* src_a, const uint8* src_b, int count) {
  uint32 diff;

  asm volatile (
    // Load constants.
    "vmov.u8    q4, #0                         \n"  // accumulator

  "1:                                          \n"
    "vld1.8     {q0, q1}, [%0]!                \n"
    "vld1.8     {q2, q3}, [%1]!                \n"
    "veor.32    q0, q0, q2                     \n"
    "veor.32    q1, q1, q3                     \n"
    "vcnt.i8    q0, q0                         \n"
    "vcnt.i8    q1, q1                         \n"
    "subs       %2, %2, #32                    \n"
    "vadd.u8    q0, q0, q1                     \n"  // 16 byte counts
    "vpaddl.u8  q0, q0                         \n"  // 8 shorts
    "vpadal.u16 q4, q0                         \n"  // 4 ints
    "bgt        1b                             \n"

    "vpadd.u32  d0, d8, d9                     \n"
    "vpadd.u32  d0, d0, d0                     \n"
    // Move distance to return register.
    "vmov.32    %3, d0[0]                      \n"

    : "+r"(src_a),
      "+r"(src_b),
      "+r"(count),
      "=r"(diff)
    :
    :  "cc", "q0", "q1", "q2", "q3", "q4");
  return diff;
}

uint32 SumSquareError_NEON(const uint8* src_a, const uint8* src_b, int count) {
  uint32 sse;
  asm volatile (
    "vmov.u8    q8, #0                         \n"
    "vmov.u8    q10, #0                        \n"
    "vmov.u8    q9, #0                         \n"
    "vmov.u8    q11, #0                        \n"

  "1:                                          \n"
    MEMACCESS(0)
    "vld1.8     {q0}, [%0]!                    \n"
    MEMACCESS(1)
    "vld1.8     {q1}, [%1]!                    \n"
    "subs       %2, %2, #16                    \n"
    "vsubl.u8   q2, d0, d2                     \n"
    "vsubl.u8   q3, d1, d3                     \n"
    "vmlal.s16  q8, d4, d4                     \n"
    "vmlal.s16  q9, d6, d6                     \n"
    "vmlal.s16  q10, d5, d5                    \n"
    "vmlal.s16  q11, d7, d7                    \n"
    "bgt        1b                             \n"

    "vadd.u32   q8, q8, q9                     \n"
    "vadd.u32   q10, q10, q11                  \n"
    "vadd.u32   q11, q8, q10                   \n"
    "vpaddl.u32 q1, q11                        \n"
    "vadd.u64   d0, d2, d3                     \n"
    "vmov.32    %3, d0[0]                      \n"
    : "+r"(src_a),
      "+r"(src_b),
      "+r"(count),
      "=r"(sse)
    :
    : "memory", "cc", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11");
  return sse;
}

#endif  // defined(__ARM_NEON__) && !defined(__aarch64__)

#ifdef __cplusplus
}  // extern "C"
}  // namespace libyuv
#endif
<|endoftext|>


<commit_before>/*
 * TTBlue Library
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTBlue.h"
#include "TTSymbolTable.h"
#include "TTEnvironment.h"
#include "TTGlobal.h"
#include "TTSymbolCache.h"
#include "TTValueCache.h"

static bool TTBlueHasInitialized = false;

/****************************************************************************************************/

void TTBlueInit()
{
	if(!TTBlueHasInitialized){
		ttSymbolTable = new TTSymbolTable;
		ttEnvironment = new TTEnvironment;
		ttGlobalObject = new TTGlobal;

		TTSymbolCacheInit();
		TTValueCacheInit();

		printf("TTBlue -- Version 0.5.2\n");

		// do we need to do anything with the global object?
		// init the queue -- runs in a new thread

		TTBlueHasInitialized = true;
	}
}

<commit_msg>When the TTBlue library initializes, it adds some classes to the environment's registry.  We still need to add the remaining classes, but this is enough to prove that it works.<commit_after>/*
 * TTBlue Library
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTBlue.h"
#include "TTSymbolTable.h"
#include "TTEnvironment.h"
#include "TTGlobal.h"
#include "TTSymbolCache.h"
#include "TTValueCache.h"

static bool TTBlueHasInitialized = false;

void TTBlueRegisterInternalClasses();
TTObject* TTBlueInstantiateInternalClass(TTSymbol* className, TTValue& arguments);

/****************************************************************************************************/
void TTBlueInit()
{
	if(!TTBlueHasInitialized){
		ttSymbolTable = new TTSymbolTable;
		ttEnvironment = new TTEnvironment;
		ttGlobalObject = new TTGlobal;

		TTSymbolCacheInit();
		TTValueCacheInit();

		printf("TTBlue -- Version 0.5.2\n");

		TTBlueRegisterInternalClasses();

		// do we need to do anything with the global object?
		// init the queue -- runs in a new thread

		TTBlueHasInitialized = true;
	}
}

/****************************************************************************************************/
#include "TTBuffer.h"
#include "TTCrossfade.h"
#include "TTDegrade.h"
#include "TTDelay.h"
#include "TTOperator.h"
#include "TTOverdrive.h"

void TTBlueRegisterInternalClasses()
{
	TTClassRegister(TT("buffer"), &TTBlueInstantiateInternalClass);
	TTClassRegister(TT("crossfade"), &TTBlueInstantiateInternalClass);
	TTClassRegister(TT("degrade"), &TTBlueInstantiateInternalClass);
	TTClassRegister(TT("delay"), &TTBlueInstantiateInternalClass);
	TTClassRegister(TT("operator"), &TTBlueInstantiateInternalClass);
	TTClassRegister(TT("overdrive"), &TTBlueInstantiateInternalClass);
}

TTObject* TTBlueInstantiateInternalClass(TTSymbol* className, TTValue& arguments)
{
	if(className == TT("buffer"))
		return new TTBuffer;
	else if(className == TT("crossfade"))
		return new TTCrossfade(arguments);
	else if(className == TT("degrade"))
		return new TTDegrade(arguments);
	else if(className == TT("delay"))
		return new TTDelay(arguments);
	else if(className == TT("operator"))
		return new TTOperator(arguments);
	else if(className == TT("overdrive"))
		return new TTOverdrive(arguments);

	else{
		TTLogError("TTBlue: cannot instantiate object of %s class.  No such class.", className->getString());
		return NULL;
	}
}

<|endoftext|>


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

#include "chrome/browser/extensions/extensions_service.h"

#include "base/file_util.h"
#include "base/values.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/json_value_serializer.h"

// ExtensionsService

const FilePath::CharType* ExtensionsService::kInstallDirectoryName =
    FILE_PATH_LITERAL("Extensions");

ExtensionsService::ExtensionsService(const FilePath& profile_directory)
    : message_loop_(MessageLoop::current()),
      backend_(new ExtensionsServiceBackend),
      install_directory_(profile_directory.Append(kInstallDirectoryName)) {
}

ExtensionsService::~ExtensionsService() {
  for (ExtensionList::iterator iter = extensions_.begin();
       iter != extensions_.end(); ++iter) {
    delete *iter;
  }
}

bool ExtensionsService::Init() {
  // TODO(aa): This message loop should probably come from a backend
  // interface, similar to how the message loop for the frontend comes
  // from the frontend interface.
  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(backend_.get(),
          &ExtensionsServiceBackend::LoadExtensionsFromDirectory,
          install_directory_,
          scoped_refptr<ExtensionsServiceFrontendInterface>(this)));
  // TODO(aa): Load extensions from other registered directories.

  return true;
}

MessageLoop* ExtensionsService::GetMessageLoop() {
  return message_loop_;
}

void ExtensionsService::OnExtensionsLoadedFromDirectory(
    ExtensionList* new_extensions) {
  extensions_.insert(extensions_.end(), new_extensions->begin(),
                     new_extensions->end());
  delete new_extensions;

  // TODO(aa): Notify extensions are loaded.
}

void ExtensionsService::OnExtensionLoadError(const std::string& error) {
  // TODO(aa): Print the error message out somewhere better. I think we are
  // going to need some sort of 'extension inspector'.
  LOG(WARNING) << error;
}

// ExtensionsServicesBackend

bool ExtensionsServiceBackend::LoadExtensionsFromDirectory(
    const FilePath& path,
    scoped_refptr<ExtensionsServiceFrontendInterface> frontend) {
  // Find all child directories in the install directory and load their
  // manifests. Post errors and results to the frontend.
  scoped_ptr<ExtensionList> extensions(new ExtensionList);
  file_util::FileEnumerator enumerator(path.ToWStringHack(),
                                       false, // not recursive
                                       file_util::FileEnumerator::DIRECTORIES);
  for (std::wstring child_path = enumerator.Next(); !child_path.empty();
       child_path = enumerator.Next()) {
     FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(
         Extension::kManifestFilename);
    if (!file_util::PathExists(manifest_path)) {
      ReportExtensionLoadError(frontend.get(), child_path,
                               Extension::kInvalidManifestError);
      continue;
    }

    JSONFileValueSerializer serializer(manifest_path.ToWStringHack());
    Value* root = NULL;
    std::string error;
    if (!serializer.Deserialize(&root, &error)) {
      ReportExtensionLoadError(frontend.get(), child_path, error);
      continue;
    }

    scoped_ptr<Value> scoped_root(root);
    if (!root->IsType(Value::TYPE_DICTIONARY)) {
      ReportExtensionLoadError(frontend.get(), child_path,
                               Extension::kInvalidManifestError);
      continue;
    }

    scoped_ptr<Extension> extension(new Extension());
    if (!extension->InitFromValue(*static_cast<DictionaryValue*>(root),
                                  &error)) {
      ReportExtensionLoadError(frontend.get(), child_path, error);
      continue;
    }

    extensions->push_back(extension.release());
    delete root;
  }

  ReportExtensionsLoaded(frontend.get(), extensions.release());
  return true;
}

void ExtensionsServiceBackend::ReportExtensionLoadError(
    ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,
    const std::string &error) {
  std::string message = StringPrintf("Could not load extension from '%s'. %s",
                                     WideToASCII(path).c_str(), error.c_str());
  frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
      frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,
      message));
}

void ExtensionsServiceBackend::ReportExtensionsLoaded(
    ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {
  frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
      frontend,
      &ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,
      extensions));
}
<commit_msg>bad merge, no need to delete a scoped_ptr<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extensions_service.h"

#include "base/file_util.h"
#include "base/values.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/json_value_serializer.h"

// ExtensionsService

const FilePath::CharType* ExtensionsService::kInstallDirectoryName =
    FILE_PATH_LITERAL("Extensions");

ExtensionsService::ExtensionsService(const FilePath& profile_directory)
    : message_loop_(MessageLoop::current()),
      backend_(new ExtensionsServiceBackend),
      install_directory_(profile_directory.Append(kInstallDirectoryName)) {
}

ExtensionsService::~ExtensionsService() {
  for (ExtensionList::iterator iter = extensions_.begin();
       iter != extensions_.end(); ++iter) {
    delete *iter;
  }
}

bool ExtensionsService::Init() {
  // TODO(aa): This message loop should probably come from a backend
  // interface, similar to how the message loop for the frontend comes
  // from the frontend interface.
  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(backend_.get(),
          &ExtensionsServiceBackend::LoadExtensionsFromDirectory,
          install_directory_,
          scoped_refptr<ExtensionsServiceFrontendInterface>(this)));
  // TODO(aa): Load extensions from other registered directories.

  return true;
}

MessageLoop* ExtensionsService::GetMessageLoop() {
  return message_loop_;
}

void ExtensionsService::OnExtensionsLoadedFromDirectory(
    ExtensionList* new_extensions) {
  extensions_.insert(extensions_.end(), new_extensions->begin(),
                     new_extensions->end());
  delete new_extensions;

  // TODO(aa): Notify extensions are loaded.
}

void ExtensionsService::OnExtensionLoadError(const std::string& error) {
  // TODO(aa): Print the error message out somewhere better. I think we are
  // going to need some sort of 'extension inspector'.
  LOG(WARNING) << error;
}

// ExtensionsServicesBackend

bool ExtensionsServiceBackend::LoadExtensionsFromDirectory(
    const FilePath& path,
    scoped_refptr<ExtensionsServiceFrontendInterface> frontend) {
  // Find all child directories in the install directory and load their
  // manifests. Post errors and results to the frontend.
  scoped_ptr<ExtensionList> extensions(new ExtensionList);
  file_util::FileEnumerator enumerator(path.ToWStringHack(),
                                       false, // not recursive
                                       file_util::FileEnumerator::DIRECTORIES);
  for (std::wstring child_path = enumerator.Next(); !child_path.empty();
       child_path = enumerator.Next()) {
     FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(
         Extension::kManifestFilename);
    if (!file_util::PathExists(manifest_path)) {
      ReportExtensionLoadError(frontend.get(), child_path,
                               Extension::kInvalidManifestError);
      continue;
    }

    JSONFileValueSerializer serializer(manifest_path.ToWStringHack());
    Value* root = NULL;
    std::string error;
    if (!serializer.Deserialize(&root, &error)) {
      ReportExtensionLoadError(frontend.get(), child_path, error);
      continue;
    }

    scoped_ptr<Value> scoped_root(root);
    if (!root->IsType(Value::TYPE_DICTIONARY)) {
      ReportExtensionLoadError(frontend.get(), child_path,
                               Extension::kInvalidManifestError);
      continue;
    }

    scoped_ptr<Extension> extension(new Extension());
    if (!extension->InitFromValue(*static_cast<DictionaryValue*>(root),
                                  &error)) {
      ReportExtensionLoadError(frontend.get(), child_path, error);
      continue;
    }

    extensions->push_back(extension.release());
  }

  ReportExtensionsLoaded(frontend.get(), extensions.release());
  return true;
}

void ExtensionsServiceBackend::ReportExtensionLoadError(
    ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,
    const std::string &error) {
  std::string message = StringPrintf("Could not load extension from '%s'. %s",
                                     WideToASCII(path).c_str(), error.c_str());
  frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
      frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,
      message));
}

void ExtensionsServiceBackend::ReportExtensionsLoaded(
    ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {
  frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
      frontend,
      &ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,
      extensions));
}
<|endoftext|>


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

#include "chrome/browser/ui/views/instant_confirm_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/instant/instant_confirm_dialog.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/layout/grid_layout.h"
#include "views/layout/layout_constants.h"
#include "views/widget/widget.h"

InstantConfirmView::InstantConfirmView(Profile* profile) : profile_(profile) {
  views::Label* description_label = new views::Label(
      l10n_util::GetStringUTF16(IDS_INSTANT_OPT_IN_MESSAGE));
  description_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  description_label->SetMultiLine(true);

  views::Link* learn_more_link = new views::Link(
      l10n_util::GetStringUTF16(IDS_LEARN_MORE));
  learn_more_link->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  learn_more_link->set_listener(this);

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  const int first_column_set = 1;
  views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING, 1,
                        views::GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, first_column_set);
  layout->AddView(description_label);
  layout->StartRow(0, first_column_set);
  layout->AddView(learn_more_link);
}

bool InstantConfirmView::Accept(bool window_closing) {
  return Accept();
}

bool InstantConfirmView::Accept() {
  InstantController::Enable(profile_);
  return true;
}

bool InstantConfirmView::Cancel() {
  return true;
}

views::View* InstantConfirmView::GetContentsView() {
  return this;
}

string16 InstantConfirmView::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(IDS_INSTANT_OPT_IN_TITLE);
}

gfx::Size InstantConfirmView::GetPreferredSize() {
  DCHECK(GetLayoutManager());
  int pref_width = views::Widget::GetLocalizedContentsWidth(
      IDS_INSTANT_CONFIRM_DIALOG_WIDTH_CHARS);
  int pref_height =
      GetLayoutManager()->GetPreferredHeightForWidth(this, pref_width);
  return gfx::Size(pref_width, pref_height);
}

bool InstantConfirmView::IsModal() const {
  return true;
}

void InstantConfirmView::LinkClicked(views::Link* source, int event_flags) {
  Browser* browser = BrowserList::GetLastActive();
  browser->OpenURL(browser::InstantLearnMoreURL(), GURL(),
                   NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_TYPED);
}

namespace browser {

void ShowInstantConfirmDialog(gfx::NativeWindow parent, Profile* profile) {
  views::Widget::CreateWindowWithParent(new InstantConfirmView(profile),
                                        parent)->Show();
}

}  // namespace browser
<commit_msg>Ensure that InstantConfirmView gets the browser corresponding to its stored |profile_|.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/instant_confirm_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/instant/instant_confirm_dialog.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/layout/grid_layout.h"
#include "views/layout/layout_constants.h"
#include "views/widget/widget.h"

InstantConfirmView::InstantConfirmView(Profile* profile) : profile_(profile) {
  views::Label* description_label = new views::Label(
      l10n_util::GetStringUTF16(IDS_INSTANT_OPT_IN_MESSAGE));
  description_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  description_label->SetMultiLine(true);

  views::Link* learn_more_link = new views::Link(
      l10n_util::GetStringUTF16(IDS_LEARN_MORE));
  learn_more_link->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  learn_more_link->set_listener(this);

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  const int first_column_set = 1;
  views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING, 1,
                        views::GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, first_column_set);
  layout->AddView(description_label);
  layout->StartRow(0, first_column_set);
  layout->AddView(learn_more_link);
}

bool InstantConfirmView::Accept(bool window_closing) {
  return Accept();
}

bool InstantConfirmView::Accept() {
  InstantController::Enable(profile_);
  return true;
}

bool InstantConfirmView::Cancel() {
  return true;
}

views::View* InstantConfirmView::GetContentsView() {
  return this;
}

string16 InstantConfirmView::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(IDS_INSTANT_OPT_IN_TITLE);
}

gfx::Size InstantConfirmView::GetPreferredSize() {
  DCHECK(GetLayoutManager());
  int pref_width = views::Widget::GetLocalizedContentsWidth(
      IDS_INSTANT_CONFIRM_DIALOG_WIDTH_CHARS);
  int pref_height =
      GetLayoutManager()->GetPreferredHeightForWidth(this, pref_width);
  return gfx::Size(pref_width, pref_height);
}

bool InstantConfirmView::IsModal() const {
  return true;
}

void InstantConfirmView::LinkClicked(views::Link* source, int event_flags) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
  browser->OpenURL(browser::InstantLearnMoreURL(), GURL(),
                   NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_TYPED);
}

namespace browser {

void ShowInstantConfirmDialog(gfx::NativeWindow parent, Profile* profile) {
  views::Widget::CreateWindowWithParent(new InstantConfirmView(profile),
                                        parent)->Show();
}

}  // namespace browser
<|endoftext|>