<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

// Sanity check integration test for hash
// Spec file: specs/hash.table

#include <osquery/tests/integration/tables/helper.h>

namespace osquery {
namespace table_tests {

namespace fs = boost::filesystem;

class Hash : public testing::Test {
 public:
  void SetUp() override {
    setUpEnvironment();
    path = fs::temp_directory_path() /
           fs::unique_path("osquery.tests.file.hashes");

    auto fout = std::ofstream(path.native(), std::ios::out | std::ios::binary);
    fout << "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
  }

  void TearDown() override {
    fs::remove(path.native());
  }

  fs::path path;
};

TEST_F(Hash, test_sanity) {
  const std::string query =
      "select * from hash where path = '" + path.native() + "'";

  QueryData data = execute_query(query);

  ASSERT_EQ(data.size(), 1ul);

  ValidatatioMap row_map = {
      {"path", NonEmptyString},
      {"directory", NonEmptyString},
      {"md5", NonEmptyString},
      {"sha1", NonEmptyString},
      {"sha256", NonEmptyString},
      {"ssdeep", NonEmptyString},
  };

  ASSERT_EQ(data[0]["path"], path.native());
  ASSERT_EQ(data[0]["directory"], path.parent_path().native());
  ASSERT_EQ(data[0]["md5"], "35899082e51edf667f14477ac000cbba");
  ASSERT_EQ(data[0]["sha1"], "e7505beb754bed863e3885f73e3bb6866bdd7f8c");
  ASSERT_EQ(data[0]["sha256"],
            "a58dd8680234c1f8cc2ef2b325a43733605a7f16f288e072de8eae81fd8d6433");
  ASSERT_EQ(data[0]["ssdeep"], "3:f4oo8MRwRJFGW1gC64:f4kPvtHF");

  validate_rows(data, row_map);
}

} // namespace table_tests
} // namespace osquery
<commit_msg>Fix up hash table integration test for windows: ssdeep is posix specific column<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

// Sanity check integration test for hash
// Spec file: specs/hash.table

#include <osquery/tests/integration/tables/helper.h>

#include <osquery/utils/info/platform_type.h>

namespace osquery {
namespace table_tests {

namespace fs = boost::filesystem;

class Hash : public testing::Test {
 public:
  void SetUp() override {
    setUpEnvironment();
    path = fs::temp_directory_path() /
           fs::unique_path("osquery.tests.file.hashes");

    auto fout = std::ofstream(path.native(), std::ios::out | std::ios::binary);
    fout << "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
  }

  void TearDown() override {
    fs::remove(path.native());
  }

  fs::path path;
};

TEST_F(Hash, test_sanity) {
  const std::string query = std::string{"select * from hash where path = '"} +
                            path.string() + std::string{"'"};

  QueryData data = execute_query(query);

  ASSERT_EQ(data.size(), 1ul);

  ValidatatioMap row_map = {
      {"path", NonEmptyString},
      {"directory", NonEmptyString},
      {"md5", NonEmptyString},
      {"sha1", NonEmptyString},
      {"sha256", NonEmptyString},
  };

  if (isPlatform(PlatformType::TYPE_POSIX)) {
    row_map.emplace("ssdeep", NonEmptyString);
  }

  ASSERT_EQ(data[0]["path"], path.string());
  ASSERT_EQ(data[0]["directory"], path.parent_path().string());
  ASSERT_EQ(data[0]["md5"], "35899082e51edf667f14477ac000cbba");
  ASSERT_EQ(data[0]["sha1"], "e7505beb754bed863e3885f73e3bb6866bdd7f8c");
  ASSERT_EQ(data[0]["sha256"],
            "a58dd8680234c1f8cc2ef2b325a43733605a7f16f288e072de8eae81fd8d6433");
  if (isPlatform(PlatformType::TYPE_POSIX)) {
    ASSERT_EQ(data[0]["ssdeep"], "3:f4oo8MRwRJFGW1gC64:f4kPvtHF");
  }

  validate_rows(data, row_map);
}

} // namespace table_tests
} // namespace osquery
<|endoftext|>


<commit_before>#include "glincludes.h"
#include "camera.h"
#include <stdio.h>
#include "volumeRenderer.h"
#include "voxelization.h"

static VoxelMaker* voxel_maker_ptr_s;
static GLuint texName;
static int _x,_y,_z;
//box and its index

static GLfloat vertice[] ={
	-1.0f, 1.0f, -1.0f,
	1.0f, 1.0f, -1.0f,
	1.0f, 1.0f, 1.0f,
	-1.0f, 1.0f, 1.0f,
	-1.0f, -1.0f, -1.0f,
	1.0f, -1.0f, -1.0f,
	1.0f, -1.0f, 1.0f,
	-1.0f, -1.0f, 1.0f
};

static GLfloat color[] = {
	0.0f, 0.0f, 0.0f,
	0.0f, 0.0f, 1.0f,
	0.0f, 1.0f, 0.0f,
	0.0f, 1.0f, 1.0f,
	1.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 1.0f,
	1.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 1.0f
};

static GLfloat texcoord[] = {
	0.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 1.0f,
	0.0f, 1.0f, 1.0f,
	0.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 1.0f,
	0.0f, 0.0f, 1.0f
};

static GLushort index[] =
{
	3, 2, 6, 7,
	1, 5, 6, 2,
	6, 5, 4, 7,
	5, 1, 0, 4,
	0, 3, 7, 4,
	0, 1, 2, 3
};

//the file is .raw
bool loadTextures() {

	/*	FILE *pFile = fopen(RAWFILENAME,"rb");
	if (NULL == pFile) {
	return false;
	}

	int size = XMAX*YMAX*ZMAX;
	unsigned char *pVolume = new unsigned char[size];
	bool ok = (size == fread(pVolume,sizeof(unsigned char), size,pFile));
	fclose(pFile);*/

	voxel_maker_ptr_s->GetSize(_x, _y, _z);
	int *pVolume = voxel_maker_ptr_s->data_buffer_loc_;

	float* image_data = new float[_x*_y*_z*4];

	for (int i = 0; i < _x*_y*_z; i++)
	{
		if (pVolume[i] == 2)//if outside, black
		{
			image_data[i*4] = 0.0f;
			image_data[i*4+1] = 0.0f;
			image_data[i*4+2] = 0.0f;
			image_data[i*4+3] = 0.0f;
		}

		else if (pVolume[i] == 1)//if inside surface, white
		{
			image_data[i*4] = 1.0f;
			image_data[i*4+1] = 1.0f;
			image_data[i*4+2] = 1.0f;
			image_data[i*4+3] = 0.5f;
		}
		else if (pVolume[i] == 0)//if not sure, red
		{
			image_data[i*4] = 0.1f;
			image_data[i*4+1] = 0.0f;
			image_data[i*4+2] = 0.0f;
			image_data[i*4+3] = 0.1f;
		}
		else//other materials, blue or green
		{
			float color = (glm::atan((float)pVolume[i])
				+ 3.1416f/2.0f) / 3.1416f;
			//color = 0.0f;
			if (color > 0.5f)
			{
				image_data[i*4] = 0.0f;
				image_data[i*4+1] = color;
				image_data[i*4+2] = 0.0f;
				image_data[i*4+3] = 0.1f;
			}
			else
			{
				image_data[i*4] = 0.0f;
				image_data[i*4+1] = 0.0f;
				image_data[i*4+2] = color;
				image_data[i*4+3] = 0.1f;
			}
		}
	}
	delete voxel_maker_ptr_s;

	glGenTextures(1,&texName);

	glBindTexture(GL_TEXTURE_3D,texName);

	// set the texture parameters
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	//glTexImage3D(GL_TEXTURE_3D,0,GL_INTENSITY,_x,_y,_z,0,GL_LUMINANCE,GL_INT,pVolume);
	//glTexImage3D(GL_TEXTURE_3D,0,GL_INTENSITY,XMAX,YMAX,ZMAX,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,pVolume);
	glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, _x, _y, _z, 0, GL_RGBA, GL_FLOAT, image_data);
	//glTextureImage3DEXT(texName, GL_TEXTURE_3D,0,GL_INTENSITY,_x,_y,_z,0,
	//	GL_LUMINANCE,GL_UNSIGNED_BYTE,pVolume);
	//delete [] pVolume;

	glBindTexture(GL_TEXTURE_3D, 0);

	delete image_data;

	return true;
}

void init(void)
{
	glewInit();
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glShadeModel(GL_SMOOTH);
	/***************test voxel maker*************************/
	voxel_maker_ptr_s = VoxelMaker::MakeObjToVoxel("2.obj", 290);
	/***************test voxel maker*************************/

	/***************test renderer*************************/
	loadTextures();
	/***************test renderer*************************/
}

void display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	/***************test renderer*************************/
	cameraDisplay();
	glm::mat4 mv = View * Model;
	glm::mat4 p = Projection;
	//int _x,_y,_z;
	//voxel_maker_ptr_s->GetSize(_x, _y, _z);
	//VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,XMAX, YMAX, ZMAX);
	VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,_x, _y, _z);
	/***************test renderer*************************/

	/***************test voxel maker*************************/
	//int _x,_y,_z;
	//voxel_maker_ptr_s->GetSize(_x, _y, _z);
	//voxel_maker_ptr_s->DrawDepth(glm::ivec3(0, 0, 0), glm::ivec3(_x, _y, _z));
	/***************test voxel maker*************************/

	glutPostRedisplay();
	glutSwapBuffers();
}

int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(SCREENWIDTH, SCREENHEIGHT);
	glutInitWindowPosition(0, 0);
	glutCreateWindow(argv[0]);
	init();

	glutDisplayFunc(display);
	cameraLoop();

	glutMainLoop();

	return 0;
}
<commit_msg>from master<commit_after>#include "glincludes.h"
#include "camera.h"
#include <stdio.h>
#include "volumeRenderer.h"
#include "voxelization.h"

static VoxelMaker* voxel_maker_ptr_s;
static GLuint texName;
static int _x,_y,_z;
//box and its index

static GLfloat vertice[] ={
	-1.0f, 1.0f, -1.0f,
	1.0f, 1.0f, -1.0f,
	1.0f, 1.0f, 1.0f,
	-1.0f, 1.0f, 1.0f,
	-1.0f, -1.0f, -1.0f,
	1.0f, -1.0f, -1.0f,
	1.0f, -1.0f, 1.0f,
	-1.0f, -1.0f, 1.0f
};

static GLfloat color[] = {
	0.0f, 0.0f, 0.0f,
	0.0f, 0.0f, 1.0f,
	0.0f, 1.0f, 0.0f,
	0.0f, 1.0f, 1.0f,
	1.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 1.0f,
	1.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 1.0f
};

static GLfloat texcoord[] = {
	0.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 0.0f,
	1.0f, 1.0f, 1.0f,
	0.0f, 1.0f, 1.0f,
	0.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 0.0f,
	1.0f, 0.0f, 1.0f,
	0.0f, 0.0f, 1.0f
};

static GLushort index[] =
{
	3, 2, 6, 7,
	1, 5, 6, 2,
	6, 5, 4, 7,
	5, 1, 0, 4,
	0, 3, 7, 4,
	0, 1, 2, 3
};

//the file is .raw
bool loadTextures() {

	/*	FILE *pFile = fopen(RAWFILENAME,"rb");
	if (NULL == pFile) {
	return false;
	}

	int size = XMAX*YMAX*ZMAX;
	unsigned char *pVolume = new unsigned char[size];
	bool ok = (size == fread(pVolume,sizeof(unsigned char), size,pFile));
	fclose(pFile);*/

	voxel_maker_ptr_s->GetSize(_x, _y, _z);
	int *pVolume = voxel_maker_ptr_s->data_buffer_loc_;

	float* image_data = new float[_x*_y*_z*4];

	for (int i = 0; i < _x*_y*_z; i++)
	{
		if (pVolume[i] == 2)//if outside, black
		{
			image_data[i*4] = 0.0f;
			image_data[i*4+1] = 0.0f;
			image_data[i*4+2] = 0.0f;
			image_data[i*4+3] = 0.0f;
		}

		else if (pVolume[i] == 1)//if inside surface, white
		{
			image_data[i*4] = 1.0f;
			image_data[i*4+1] = 1.0f;
			image_data[i*4+2] = 1.0f;
			image_data[i*4+3] = 0.5f;
		}
		else if (pVolume[i] == 0)//if not sure, red
		{
			image_data[i*4] = 0.1f;
			image_data[i*4+1] = 0.0f;
			image_data[i*4+2] = 0.0f;
			image_data[i*4+3] = 0.1f;
		}
		else//other materials, blue or green
		{
			float color = (glm::atan((float)pVolume[i])
				+ 3.1416f/2.0f) / 3.1416f;
			//color = 0.0f;
			if (color > 0.5f)
			{
				image_data[i*4] = 0.0f;
				image_data[i*4+1] = color;
				image_data[i*4+2] = 0.0f;
				image_data[i*4+3] = 0.1f;
			}
			else
			{
				image_data[i*4] = 0.0f;
				image_data[i*4+1] = 0.0f;
				image_data[i*4+2] = color;
				image_data[i*4+3] = 0.1f;
			}
		}
	}
	delete voxel_maker_ptr_s;

	glGenTextures(1,&texName);

	glBindTexture(GL_TEXTURE_3D,texName);

	// set the texture parameters
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	//glTexImage3D(GL_TEXTURE_3D,0,GL_INTENSITY,_x,_y,_z,0,GL_LUMINANCE,GL_INT,pVolume);
	//glTexImage3D(GL_TEXTURE_3D,0,GL_INTENSITY,XMAX,YMAX,ZMAX,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,pVolume);
	glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, _x, _y, _z, 0, GL_RGBA, GL_FLOAT, image_data);
	//glTextureImage3DEXT(texName, GL_TEXTURE_3D,0,GL_INTENSITY,_x,_y,_z,0,
	//	GL_LUMINANCE,GL_UNSIGNED_BYTE,pVolume);
	//delete [] pVolume;

	glBindTexture(GL_TEXTURE_3D, 0);

	delete image_data;

	return true;
}

void init(void)
{
	glewInit();
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glShadeModel(GL_SMOOTH);
	/***************test voxel maker*************************/
	voxel_maker_ptr_s = VoxelMaker::MakeObjToVoxel("2.obj", 330);
	/***************test voxel maker*************************/

	/***************test renderer*************************/
	loadTextures();
	/***************test renderer*************************/
}

void display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	/***************test renderer*************************/
	cameraDisplay();
	glm::mat4 mv = View * Model;
	glm::mat4 p = Projection;
	//int _x,_y,_z;
	//voxel_maker_ptr_s->GetSize(_x, _y, _z);
	//VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,XMAX, YMAX, ZMAX);
	VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,_x, _y, _z);
	/***************test renderer*************************/

	/***************test voxel maker*************************/
	//int _x,_y,_z;
	//voxel_maker_ptr_s->GetSize(_x, _y, _z);
	//voxel_maker_ptr_s->DrawDepth(glm::ivec3(0, 0, 0), glm::ivec3(_x, _y, _z));
	/***************test voxel maker*************************/

	glutPostRedisplay();
	glutSwapBuffers();
}

int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(SCREENWIDTH, SCREENHEIGHT);
	glutInitWindowPosition(0, 0);
	glutCreateWindow(argv[0]);
	init();

	glutDisplayFunc(display);
	cameraLoop();

	glutMainLoop();

	return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2008 Bertjan Broeksema <b.broeksema@kdemail.net>
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "singlefileresourcebase.h"

#include <akonadi/changerecorder.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>

#include <kio/job.h>
#include <kio/jobuidelegate.h>
#include <KDebug>
#include <KDirWatch>
#include <KLocale>
#include <KStandardDirs>

#include <QtCore/QDir>

using namespace Akonadi;

SingleFileResourceBase::SingleFileResourceBase( const QString & id )
  : ResourceBase( id ), mDownloadJob( 0 ), mUploadJob( 0 )
{
  connect( &mDirtyTimer, SIGNAL( timeout() ), SLOT( writeFile() ) );
  mDirtyTimer.setSingleShot( true );

  connect( this, SIGNAL( reloadConfiguration() ), SLOT( reloadFile() ) );
  QTimer::singleShot( 0, this, SLOT( readFile() ) );

  changeRecorder()->itemFetchScope().fetchFullPayload();
  changeRecorder()->fetchCollection( true );

  connect( KDirWatch::self(), SIGNAL( dirty( QString ) ), SLOT( fileChanged( QString ) ) );
}

QString SingleFileResourceBase::cacheFile() const
{
  return KStandardDirs::locateLocal( "cache", "akonadi/" + identifier() );
}

void SingleFileResourceBase::setSupportedMimetypes( const QStringList & mimeTypes, const QString &icon )
{
  mSupportedMimetypes = mimeTypes;
  mCollectionIcon = icon;
}

void SingleFileResourceBase::collectionChanged( const Akonadi::Collection & collection )
{
  QString newName = collection.name();
  if ( collection.hasAttribute<EntityDisplayAttribute>() ) {
    EntityDisplayAttribute *attr = collection.attribute<EntityDisplayAttribute>();
    if ( !attr->displayName().isEmpty() )
      newName = attr->displayName();
  }

  if ( newName != name() )
    setName( newName );
}

void SingleFileResourceBase::reloadFile()
{
  // Update the network setting.
  setNeedsNetwork( !mCurrentUrl.isEmpty() && !mCurrentUrl.isLocalFile() );

  // if we have something loaded already, make sure we write that back in case
  // the settings changed
  if ( !mCurrentUrl.isEmpty() )
    writeFile();

  readFile();
  synchronize();
}

void SingleFileResourceBase::handleProgress( KJob *, unsigned long pct )
{
  emit percent( pct );
}

void SingleFileResourceBase::fileChanged( const QString & fileName )
{
  if ( fileName != mCurrentUrl.path() )
    return;

  // handle conflicts
  if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {
    const KUrl prevUrl = mCurrentUrl;
    int i = 0;
    QString lostFoundFileName;
    do {
      lostFoundFileName = KStandardDirs::locateLocal( "data", identifier() + QDir::separator()
          + prevUrl.fileName() + "-" + QString::number( ++i ) );
    } while ( KStandardDirs::exists( lostFoundFileName ) );
    mCurrentUrl = KUrl( lostFoundFileName );
    writeFile();
    emit warning( i18n( "The file '%1' was changed on disk while there were still pending changes in Akonadi. "
        "To avoid dataloss, a backup of the internal changes has been created at '%2'.",
         prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );
    mCurrentUrl = prevUrl;
  }

  readFile();
  synchronize();
}

void SingleFileResourceBase::slotDownloadJobResult( KJob *job )
{
  if ( job->error() && job->error() != KIO::ERR_DOES_NOT_EXIST ) {
    emit status( Broken, i18n( "Could not load file '%1'.", mCurrentUrl.prettyUrl() ) );
  } else {
    readFromFile( KUrl( cacheFile() ).url() );
  }

  mDownloadJob = 0;
  KGlobal::deref();

  emit status( Idle, i18nc( "@info:status", "Ready" ) );
}

void SingleFileResourceBase::slotUploadJobResult( KJob *job )
{
  if ( job->error() ) {
    emit status( Broken, i18n( "Could not save file '%1'.", mCurrentUrl.prettyUrl() ) );
  }

  mUploadJob = 0;
  KGlobal::deref();

  emit status( Idle, i18nc( "@info:status", "Ready" ) );
}

#include "singlefileresourcebase.moc"
<commit_msg>Don't deadlock the resource scheduler when getting a collection change notification.<commit_after>/*
    Copyright (c) 2008 Bertjan Broeksema <b.broeksema@kdemail.net>
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "singlefileresourcebase.h"

#include <akonadi/changerecorder.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>

#include <kio/job.h>
#include <kio/jobuidelegate.h>
#include <KDebug>
#include <KDirWatch>
#include <KLocale>
#include <KStandardDirs>

#include <QtCore/QDir>

using namespace Akonadi;

SingleFileResourceBase::SingleFileResourceBase( const QString & id )
  : ResourceBase( id ), mDownloadJob( 0 ), mUploadJob( 0 )
{
  connect( &mDirtyTimer, SIGNAL( timeout() ), SLOT( writeFile() ) );
  mDirtyTimer.setSingleShot( true );

  connect( this, SIGNAL( reloadConfiguration() ), SLOT( reloadFile() ) );
  QTimer::singleShot( 0, this, SLOT( readFile() ) );

  changeRecorder()->itemFetchScope().fetchFullPayload();
  changeRecorder()->fetchCollection( true );

  connect( KDirWatch::self(), SIGNAL( dirty( QString ) ), SLOT( fileChanged( QString ) ) );
}

QString SingleFileResourceBase::cacheFile() const
{
  return KStandardDirs::locateLocal( "cache", "akonadi/" + identifier() );
}

void SingleFileResourceBase::setSupportedMimetypes( const QStringList & mimeTypes, const QString &icon )
{
  mSupportedMimetypes = mimeTypes;
  mCollectionIcon = icon;
}

void SingleFileResourceBase::collectionChanged( const Akonadi::Collection & collection )
{
  QString newName = collection.name();
  if ( collection.hasAttribute<EntityDisplayAttribute>() ) {
    EntityDisplayAttribute *attr = collection.attribute<EntityDisplayAttribute>();
    if ( !attr->displayName().isEmpty() )
      newName = attr->displayName();
  }

  if ( newName != name() )
    setName( newName );

  changeCommitted( collection );
}

void SingleFileResourceBase::reloadFile()
{
  // Update the network setting.
  setNeedsNetwork( !mCurrentUrl.isEmpty() && !mCurrentUrl.isLocalFile() );

  // if we have something loaded already, make sure we write that back in case
  // the settings changed
  if ( !mCurrentUrl.isEmpty() )
    writeFile();

  readFile();
  synchronize();
}

void SingleFileResourceBase::handleProgress( KJob *, unsigned long pct )
{
  emit percent( pct );
}

void SingleFileResourceBase::fileChanged( const QString & fileName )
{
  if ( fileName != mCurrentUrl.path() )
    return;

  // handle conflicts
  if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {
    const KUrl prevUrl = mCurrentUrl;
    int i = 0;
    QString lostFoundFileName;
    do {
      lostFoundFileName = KStandardDirs::locateLocal( "data", identifier() + QDir::separator()
          + prevUrl.fileName() + "-" + QString::number( ++i ) );
    } while ( KStandardDirs::exists( lostFoundFileName ) );
    mCurrentUrl = KUrl( lostFoundFileName );
    writeFile();
    emit warning( i18n( "The file '%1' was changed on disk while there were still pending changes in Akonadi. "
        "To avoid dataloss, a backup of the internal changes has been created at '%2'.",
         prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );
    mCurrentUrl = prevUrl;
  }

  readFile();
  synchronize();
}

void SingleFileResourceBase::slotDownloadJobResult( KJob *job )
{
  if ( job->error() && job->error() != KIO::ERR_DOES_NOT_EXIST ) {
    emit status( Broken, i18n( "Could not load file '%1'.", mCurrentUrl.prettyUrl() ) );
  } else {
    readFromFile( KUrl( cacheFile() ).url() );
  }

  mDownloadJob = 0;
  KGlobal::deref();

  emit status( Idle, i18nc( "@info:status", "Ready" ) );
}

void SingleFileResourceBase::slotUploadJobResult( KJob *job )
{
  if ( job->error() ) {
    emit status( Broken, i18n( "Could not save file '%1'.", mCurrentUrl.prettyUrl() ) );
  }

  mUploadJob = 0;
  KGlobal::deref();

  emit status( Idle, i18nc( "@info:status", "Ready" ) );
}

#include "singlefileresourcebase.moc"
<|endoftext|>


<commit_before><commit_msg>legion: small bug fix for local fields<commit_after><|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CG_INTERFACE_HH
#define DUNE_GDT_SPACES_CG_INTERFACE_HH

#include <algorithm>

#include <boost/numeric/conversion/cast.hpp>

#include <dune/common/dynvector.hh>
#include <dune/common/version.hh>
#include <dune/common/typetraits.hh>

#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/common/type_utils.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

static constexpr ChooseSpaceBackend default_cg_backend = default_space_backend;

template <class ImpTraits, size_t domainDim, size_t rangeDim, size_t rangeDimCols = 1>
class CGInterface : public SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols>
{
  typedef SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> BaseType;
  typedef CGInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> ThisType;

public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

private:
  static const constexpr RangeFieldType compare_tolerance_ = 1e-13;

public:
  /**
   * \defgroup interface ´´These methods have to be implemented!''
   * @{
   **/
  std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    CHECK_CRTP(this->as_imp().lagrange_points(entity));
    return this->as_imp().lagrange_points(entity);
  } // ... lagrange_points(...)

  std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    CHECK_CRTP(this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo));
    return this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo);
  } // ... local_dirichlet_DoFs(...)
  /** @} */

  /**
   * \defgroup provided ´´These methods are provided by the interface for convenience.''
   * @{
   **/

  /**
   * \todo Use our FloatCmp with the correct comparison method gainst 0 and 1!
   */
  std::vector<DomainType> lagrange_points_order_1(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Does not work for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view().indexSet().contains(entity));
    // get the basis and reference element
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    const auto num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(boost::numeric_cast<size_t>(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
    // loop over all vertices
    for (auto ii : DSC::valueRange(num_vertices)) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, tmp_basis_values);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs((tmp_basis_values)[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs((tmp_basis_values)[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points_order_1(...)

  /**
   * \attention The current search strategy is not rubust with respect to the grid (see note)!
   * \note      We only look in the intersections of entity and its direct neighbors for dirichlet vertices and might
   *            miss some (see also https://github.com/pymor/dune-gdt/issues/51)!
   */
  std::set<size_t> local_dirichlet_DoFs_order_1(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view().indexSet().contains(entity));
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> global_dirichlet_vertices;
    // find all dirichlet vertices of this entity and its neighbors (in global coordinates)
    add_dirichlet_vertices(boundaryInfo, entity, /*recursion_level = */ 1, global_dirichlet_vertices);
    // keep those local to this entity
    std::vector<DomainType> dirichlet_vertices;
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    for (const auto& global_vertex : global_dirichlet_vertices) {
      auto local_vertex = entity.geometry().local(global_vertex);
      if (reference_element.checkInside(local_vertex)
          && std::find(dirichlet_vertices.begin(), dirichlet_vertices.end(), local_vertex) == dirichlet_vertices.end())
        dirichlet_vertices.push_back(local_vertex);
    }
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    for (const auto& dirichlet_vertex : dirichlet_vertices) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertex, tmp_basis_values);
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(tmp_basis_values[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(tmp_basis_values[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs_order_1(...)

  using BaseType::compute_pattern;

  template <class G, class S, size_t d, size_t r, size_t rC>
  PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S, d, r, rC>& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  using BaseType::local_constraints;

  template <class S, size_t d, size_t r, size_t rC, class ConstraintsType>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& /*entity*/,
                         ConstraintsType& /*ret*/) const
  {
    static_assert(AlwaysFalse<S>::value, "Not implemented for these constraints!");
  }

  template <class S, size_t d, size_t r, size_t rC>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& entity,
                         DirichletConstraints<IntersectionType>& ret) const
  {
    const auto local_DoFs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
    if (local_DoFs.size() > 0) {
      const auto global_indices = this->mapper().globalIndices(entity);
      for (const auto& local_DoF : local_DoFs) {
        ret.insert(global_indices[local_DoF]);
      }
    }
  } // ... local_constraints(..., Constraints::Dirichlet< ... > ...)
  /** @} */

private:
  void add_dirichlet_vertices(const BoundaryInfoType& boundaryInfo, const EntityType& entity,
                              const ssize_t recursion_level, std::vector<DomainType>& dirichlet_vertices) const
  {
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view().iend(entity);
    for (auto intersection_it = this->grid_view().ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      const auto& intersection = *intersection_it;
      // only work on dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (auto cc : DSC::valueRange(geometry.corners()))
          dirichlet_vertices.emplace_back(geometry.corner(cc));
      } // only work on dirichlet intersections + process boundaries for parallel runs
      if (recursion_level > 0) {
        // also call myself on all neighbors
        if (intersection.neighbor()) {
          const auto neighbor_ptr = intersection.outside();
          add_dirichlet_vertices(boundaryInfo, *neighbor_ptr, recursion_level - 1, dirichlet_vertices);
        }
      } // if (level > 0)
    } // loop over all intersections
  } // ... add_dirichlet_vertices(...)
}; // class CGInterface

} // namespace Spaces
namespace internal {

template <class S>
struct is_cg_space_helper
{
  DSC_has_typedef_initialize_once(Traits) DSC_has_static_member_initialize_once(dimDomain)
      DSC_has_static_member_initialize_once(dimRange) DSC_has_static_member_initialize_once(dimRangeCols)

          static const
      bool is_candidate = DSC_has_typedef(Traits)<S>::value && DSC_has_static_member(dimDomain)<S>::value
                          && DSC_has_static_member(dimRange)<S>::value && DSC_has_static_member(dimRangeCols)<S>::value;
}; // class is_cg_space_helper

} // namespace internal

template <class S, bool candidate = internal::is_cg_space_helper<S>::is_candidate>
struct is_cg_space
    : public std::is_base_of<Spaces::CGInterface<typename S::Traits, S::dimDomain, S::dimRange, S::dimRangeCols>, S>
{
};

template <class S>
struct is_cg_space<S, false> : public std::false_type
{
};

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CG_INTERFACE_HH
<commit_msg>Revert "[spaces.cg.interface] update findind of dirichlet DoFs, refs #51"<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CG_INTERFACE_HH
#define DUNE_GDT_SPACES_CG_INTERFACE_HH

#include <boost/numeric/conversion/cast.hpp>

#include <dune/common/dynvector.hh>
#include <dune/common/version.hh>
#include <dune/common/typetraits.hh>

#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

static constexpr ChooseSpaceBackend default_cg_backend = default_space_backend;

template <class ImpTraits, size_t domainDim, size_t rangeDim, size_t rangeDimCols = 1>
class CGInterface : public SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols>
{
  typedef SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> BaseType;
  typedef CGInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> ThisType;

public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

private:
  static const constexpr RangeFieldType compare_tolerance_ = 1e-13;

public:
  /**
   * \defgroup interface ´´These methods have to be implemented!''
   * @{
   **/
  std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    CHECK_CRTP(this->as_imp().lagrange_points(entity));
    return this->as_imp().lagrange_points(entity);
  } // ... lagrange_points(...)

  std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    CHECK_CRTP(this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo));
    return this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo);
  } // ... local_dirichlet_DoFs(...)
  /** @} */

  /**
   * \defgroup provided ´´These methods are provided by the interface for convenience.''
   * @{
   **/
  std::vector<DomainType> lagrange_points_order_1(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view().indexSet().contains(entity));
    // get the basis and reference element
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    const auto num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(boost::numeric_cast<size_t>(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
    // loop over all vertices
    for (auto ii : DSC::valueRange(num_vertices)) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, tmp_basis_values);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs((tmp_basis_values)[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs((tmp_basis_values)[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points_order_1(...)

  std::set<size_t> local_dirichlet_DoFs_order_1(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view().indexSet().contains(entity));
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view().iend(entity);
    for (auto intersection_it = this->grid_view().ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      // actual dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (auto cc : DSC::valueRange(geometry.corners()))
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], tmp_basis_values);
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(tmp_basis_values[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(tmp_basis_values[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs_order_1(...)

  using BaseType::compute_pattern;

  template <class G, class S, size_t d, size_t r, size_t rC>
  PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S, d, r, rC>& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  using BaseType::local_constraints;

  template <class S, size_t d, size_t r, size_t rC, class ConstraintsType>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& /*entity*/,
                         ConstraintsType& /*ret*/) const
  {
    static_assert(AlwaysFalse<S>::value, "Not implemented for these constraints!");
  }

  template <class S, size_t d, size_t r, size_t rC>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& entity,
                         DirichletConstraints<IntersectionType>& ret) const
  {
    const auto local_DoFs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
    if (local_DoFs.size() > 0) {
      const auto global_indices = this->mapper().globalIndices(entity);
      for (const auto& local_DoF : local_DoFs) {
        ret.insert(global_indices[local_DoF]);
      }
    }
  } // ... local_constraints(..., Constraints::Dirichlet< ... > ...)
  /** @} */
}; // class CGInterface

} // namespace Spaces
namespace internal {

template <class S>
struct is_cg_space_helper
{
  DSC_has_typedef_initialize_once(Traits) DSC_has_static_member_initialize_once(dimDomain)
      DSC_has_static_member_initialize_once(dimRange) DSC_has_static_member_initialize_once(dimRangeCols)

          static const
      bool is_candidate = DSC_has_typedef(Traits)<S>::value && DSC_has_static_member(dimDomain)<S>::value
                          && DSC_has_static_member(dimRange)<S>::value && DSC_has_static_member(dimRangeCols)<S>::value;
}; // class is_cg_space_helper

} // namespace internal

template <class S, bool candidate = internal::is_cg_space_helper<S>::is_candidate>
struct is_cg_space
    : public std::is_base_of<Spaces::CGInterface<typename S::Traits, S::dimDomain, S::dimRange, S::dimRangeCols>, S>
{
};

template <class S>
struct is_cg_space<S, false> : public std::false_type
{
};

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CG_INTERFACE_HH
<|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: cachedbitmap.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <canvas/debug.hxx>

#include "cachedbitmap.hxx"
#include "repainttarget.hxx"

#include <com/sun/star/rendering/RepaintResult.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/tools/canvastools.hxx>

using namespace ::com::sun::star;

namespace vclcanvas
{
    CachedBitmap::CachedBitmap( const GraphicObjectSharedPtr&               rGraphicObject,
                                const ::Point&                              rPoint,
                                const ::Size&                               rSize,
                                const GraphicAttr&                          rAttr,
                                const rendering::ViewState&                 rUsedViewState,
                                const rendering::RenderState&               rUsedRenderState,
                                const uno::Reference< rendering::XCanvas >& rTarget ) :
        CachedPrimitiveBase( rUsedViewState, rTarget, true ),
        mpGraphicObject( rGraphicObject ),
        maRenderState(rUsedRenderState),
        maPoint( rPoint ),
        maSize( rSize ),
        maAttributes( rAttr )
    {
    }

    void SAL_CALL CachedBitmap::disposing()
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        mpGraphicObject.reset();

        CachedPrimitiveBase::disposing();
    }

    ::sal_Int8 CachedBitmap::doRedraw( const rendering::ViewState&                  rNewState,
                                       const rendering::ViewState&                  rOldState,
                                       const uno::Reference< rendering::XCanvas >&  rTargetCanvas,
                                       bool                                         bSameViewTransform )
    {
        ENSURE_AND_THROW( bSameViewTransform,
                          "CachedBitmap::doRedraw(): base called with changed view transform "
                          "(told otherwise during construction)" );

        // TODO(P1): Could adapt to modified clips as well
        if( rNewState.Clip != rOldState.Clip )
            return rendering::RepaintResult::FAILED;

        RepaintTarget* pTarget = dynamic_cast< RepaintTarget* >(rTargetCanvas.get());

        ENSURE_AND_THROW( pTarget,
                          "CachedBitmap::redraw(): cannot cast target to RepaintTarget" );

        if( !pTarget->repaint( mpGraphicObject,
                               rNewState,
                               maRenderState,
                               maPoint,
                               maSize,
                               maAttributes ) )
        {
            // target failed to repaint
            return rendering::RepaintResult::FAILED;
        }

        return rendering::RepaintResult::REDRAWN;
    }
}
<commit_msg>INTEGRATION: CWS canvas05 (1.6.68); FILE MERGED 2008/04/21 07:29:05 thb 1.6.68.3: RESYNC: (1.7-1.8); FILE MERGED 2007/11/06 12:36:46 thb 1.6.68.2: RESYNC: (1.6-1.7); FILE MERGED 2007/10/01 13:02:03 thb 1.6.68.1: #i78888# #i78925# #i79258# #i79437# Merge from CWS picom<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: cachedbitmap.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>

#include "cachedbitmap.hxx"
#include "repainttarget.hxx"

#include <com/sun/star/rendering/RepaintResult.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/tools/canvastools.hxx>

using namespace ::com::sun::star;

namespace vclcanvas
{
    CachedBitmap::CachedBitmap( const GraphicObjectSharedPtr&               rGraphicObject,
                                const ::Point&                              rPoint,
                                const ::Size&                               rSize,
                                const GraphicAttr&                          rAttr,
                                const rendering::ViewState&                 rUsedViewState,
                                const rendering::RenderState&               rUsedRenderState,
                                const uno::Reference< rendering::XCanvas >& rTarget ) :
        CachedPrimitiveBase( rUsedViewState, rTarget, true ),
        mpGraphicObject( rGraphicObject ),
        maRenderState(rUsedRenderState),
        maPoint( rPoint ),
        maSize( rSize ),
        maAttributes( rAttr )
    {
    }

    void SAL_CALL CachedBitmap::disposing()
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        mpGraphicObject.reset();

        CachedPrimitiveBase::disposing();
    }

    ::sal_Int8 CachedBitmap::doRedraw( const rendering::ViewState&                  rNewState,
                                       const rendering::ViewState&                  rOldState,
                                       const uno::Reference< rendering::XCanvas >&  rTargetCanvas,
                                       bool                                         bSameViewTransform )
    {
        ENSURE_OR_THROW( bSameViewTransform,
                         "CachedBitmap::doRedraw(): base called with changed view transform "
                         "(told otherwise during construction)" );

        // TODO(P1): Could adapt to modified clips as well
        if( rNewState.Clip != rOldState.Clip )
            return rendering::RepaintResult::FAILED;

        RepaintTarget* pTarget = dynamic_cast< RepaintTarget* >(rTargetCanvas.get());

        ENSURE_OR_THROW( pTarget,
                          "CachedBitmap::redraw(): cannot cast target to RepaintTarget" );

        if( !pTarget->repaint( mpGraphicObject,
                               rNewState,
                               maRenderState,
                               maPoint,
                               maSize,
                               maAttributes ) )
        {
            // target failed to repaint
            return rendering::RepaintResult::FAILED;
        }

        return rendering::RepaintResult::REDRAWN;
    }
}
<|endoftext|>


<commit_before>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#include <boost/test/unit_test.hpp>
#include <memory>
#include <atomic>
#include <string>
#include <functional>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
#include "httpp/utils/Exception.hpp"
#include "httpp/http/Utils.hpp"
#include <boost/log/trivial.hpp>

using namespace HTTPP;

using HTTPP::HttpServer;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;

const int DEFAULT_NUMBER_OF_CHUNKS = 3;
const int DEFAULT_CHUNK_SIZE = 100;

//
// Helper that constructs a stream functor for the specified number of chunks,
// each chunk being 'chunkSize' bytes.
//
std::function<std::string()> make_stream(int numChunks, int chunkSize)
{
    auto stream = [numChunks,chunkSize]() mutable -> std::string
    {
        if (numChunks > 0)
        {
            BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":Sending Chunk ";
            numChunks--;
            return std::string(chunkSize, 'X');
        }
        else
        {
            BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":End of Stream ";
            return "";
        }
    };
    return stream;
}

void chunked_data_handler(Connection* connection, Request&&)
{
    auto body = make_stream(DEFAULT_NUMBER_OF_CHUNKS, DEFAULT_CHUNK_SIZE);
    connection->response().setCode(HTTP::HttpCode::Ok).setBody(body);
    connection->sendResponse();
}

//
// Test we correctly set the Transfer-Encoding header when streaming
//
BOOST_AUTO_TEST_CASE(test_transfer_encoding_header_is_set_correctly)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    auto headers = response.getSortedHeaders();
    BOOST_CHECK_EQUAL(headers["Transfer-Encoding"], "chunked");
}

//
// Test that the client will receive the expected payload. Since we use CUrl, we
// receive the
// re-assembled payload, not the raw payload of individual chunks.
//
BOOST_AUTO_TEST_CASE(test_client_receives_expected_body)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    std::string body(response.body.begin(), response.body.end());

    std::string expectedBody(DEFAULT_CHUNK_SIZE * DEFAULT_NUMBER_OF_CHUNKS, 'X');
    BOOST_CHECK_EQUAL(expectedBody, body);
}

//
// Test we can send an empty response with no data. Should return 200 OK, but
// nothing in the payload.
//
void empty_chunk_response(Connection* connection, Request&&)
{
    auto empty_response = []()
    { return ""; };

    connection->response().setCode(HTTP::HttpCode::Ok).setBody(empty_response);
    connection->sendResponse();
}

BOOST_AUTO_TEST_CASE(test_empty_chunk_response)
{
    HttpServer server;
    server.start();
    server.setSink(&empty_chunk_response);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    auto headers = response.getSortedHeaders();

    BOOST_CHECK_EQUAL(headers["Transfer-Encoding"], "chunked");
    BOOST_CHECK_EQUAL(true, response.body.empty());
    BOOST_CHECK_EQUAL(getDefaultMessage(HTTP::HttpCode::Ok),
                      getDefaultMessage(response.code));
}

//
// Test we can cancel a streaming request. Also check the client api gets the
// correct exception.
//
void infinite_response(Connection* connection, Request&&)
{
    connection->response()
        .setCode(HTTP::HttpCode::Ok)
        .setBody([]() { return "XXX"; });
    connection->sendResponse();
}

BOOST_AUTO_TEST_CASE(test_cancelling_request_while_streaming_stops_functor)
{
    HttpServer server;
    server.start();
    server.setSink(&infinite_response);
    server.bind("localhost", "8080");
    BOOST_CHECK_EQUAL(server.getNbConnection(), 1);

    {
        HttpClient::Request request;
        request.url("http://localhost:8080");
        HttpClient client;

        auto handler = client.async_get(
            std::move(request),
            [](HttpClient::Future&& fut)
            { BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        BOOST_CHECK_EQUAL(server.getNbConnection(), 2);
        handler.cancelOperation();
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    BOOST_CHECK_EQUAL(server.getNbConnection(), 1);
}

//
// Test the raw response contains the correct header and chunk data.
//

std::string GetRawResponse()
{
    using boost::asio::ip::tcp;

    boost::asio::io_service io_service;
    tcp::socket sock(io_service);
    tcp::resolver resolver(io_service);

    // send request
    const std::string REQUEST("GET / HTTP/1.1\r\n\r\n");
    boost::asio::connect(sock, resolver.resolve({ "localhost", "8080" }));
    boost::asio::write(sock, boost::asio::buffer(REQUEST));

    // read until end-of-stream
    boost::asio::streambuf response;
    auto bytes = boost::asio::read_until(sock, response, "0\r\n\r\n");

    // convert buffer to a string
    auto responseData = response.data();
    std::string str(boost::asio::buffers_begin(responseData), boost::asio::buffers_begin(responseData) + bytes);
    return str;
}

BOOST_AUTO_TEST_CASE(test_format_of_raw_response)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    auto rawResponse = GetRawResponse();

    auto startOfBody = rawResponse.find("\r\n\r\n");
    //sBOOST_CHECK_NOT_EQUAL(startOfBody, std::string::npos);
    startOfBody += 4;

    // each chunk should start with 64\r\n (100 byte chunks)
    auto chunkIterator = startOfBody;
    for (int i=0; i<3; i++)
    {
        auto chunkHeader = rawResponse.substr(chunkIterator, 4);
        BOOST_CHECK_EQUAL(chunkHeader, "64\r\n");
        chunkIterator += 4;
        auto chunkBody = rawResponse.substr(chunkIterator, 100);
        BOOST_CHECK_EQUAL(chunkBody, std::string(DEFAULT_CHUNK_SIZE, 'X'));
        chunkIterator += 100;
        auto chunkTrailer = rawResponse.substr(chunkIterator, 2);
        BOOST_CHECK_EQUAL(chunkTrailer, "\r\n");
        chunkIterator += 2;
    }
}

<commit_msg>Add test for format of chunked response<commit_after>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#include <boost/test/unit_test.hpp>
#include <memory>
#include <atomic>
#include <string>
#include <functional>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
#include "httpp/utils/Exception.hpp"
#include "httpp/http/Utils.hpp"
#include <boost/log/trivial.hpp>

using namespace HTTPP;

using HTTPP::HttpServer;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;

const int DEFAULT_NUMBER_OF_CHUNKS = 3;
const int DEFAULT_CHUNK_SIZE = 100;

//
// Helper that constructs a stream functor for the specified number of chunks,
// each chunk being 'chunkSize' bytes.
//
std::function<std::string()> make_stream(int numChunks, int chunkSize)
{
    auto stream = [numChunks,chunkSize]() mutable -> std::string
    {
        if (numChunks > 0)
        {
            BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":Sending Chunk ";
            numChunks--;
            return std::string(chunkSize, 'X');
        }
        else
        {
            BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":End of Stream ";
            return "";
        }
    };
    return stream;
}

void chunked_data_handler(Connection* connection, Request&&)
{
    auto body = make_stream(DEFAULT_NUMBER_OF_CHUNKS, DEFAULT_CHUNK_SIZE);
    connection->response().setCode(HTTP::HttpCode::Ok).setBody(body);
    connection->sendResponse();
}

//
// Test we correctly set the Transfer-Encoding header when streaming
//
BOOST_AUTO_TEST_CASE(test_transfer_encoding_header_is_set_correctly)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    auto headers = response.getSortedHeaders();
    BOOST_CHECK_EQUAL(headers["Transfer-Encoding"], "chunked");
}

//
// Test that the client will receive the expected payload. Since we use CUrl, we
// receive the
// re-assembled payload, not the raw payload of individual chunks.
//
BOOST_AUTO_TEST_CASE(test_client_receives_expected_body)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    std::string body(response.body.begin(), response.body.end());

    std::string expectedBody(DEFAULT_CHUNK_SIZE * DEFAULT_NUMBER_OF_CHUNKS, 'X');
    BOOST_CHECK_EQUAL(expectedBody, body);
}

//
// Test we can send an empty response with no data. Should return 200 OK, but
// nothing in the payload.
//
void empty_chunk_response(Connection* connection, Request&&)
{
    auto empty_response = []()
    { return ""; };

    connection->response().setCode(HTTP::HttpCode::Ok).setBody(empty_response);
    connection->sendResponse();
}

BOOST_AUTO_TEST_CASE(test_empty_chunk_response)
{
    HttpServer server;
    server.start();
    server.setSink(&empty_chunk_response);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request.url("http://localhost:8080");
    HttpClient client;

    auto response = client.get(std::move(request));
    auto headers = response.getSortedHeaders();

    BOOST_CHECK_EQUAL(headers["Transfer-Encoding"], "chunked");
    BOOST_CHECK_EQUAL(true, response.body.empty());
    BOOST_CHECK_EQUAL(getDefaultMessage(HTTP::HttpCode::Ok),
                      getDefaultMessage(response.code));
}

//
// Test we can cancel a streaming request. Also check the client api gets the
// correct exception.
//
void infinite_response(Connection* connection, Request&&)
{
    connection->response()
        .setCode(HTTP::HttpCode::Ok)
        .setBody([]() { return "XXX"; });
    connection->sendResponse();
}

BOOST_AUTO_TEST_CASE(test_cancelling_request_while_streaming_stops_functor)
{
    HttpServer server;
    server.start();
    server.setSink(&infinite_response);
    server.bind("localhost", "8080");
    BOOST_CHECK_EQUAL(server.getNbConnection(), 1);

    {
        HttpClient::Request request;
        request.url("http://localhost:8080");
        HttpClient client;

        auto handler = client.async_get(
            std::move(request),
            [](HttpClient::Future&& fut)
            { BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        BOOST_CHECK_EQUAL(server.getNbConnection(), 2);
        handler.cancelOperation();
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    BOOST_CHECK_EQUAL(server.getNbConnection(), 1);
}

//
// Test the raw response contains the correct header and chunk data.
//

std::string GetRawResponse()
{
    using boost::asio::ip::tcp;

    boost::asio::io_service io_service;
    tcp::socket sock(io_service);
    tcp::resolver resolver(io_service);

    // send request
    const std::string REQUEST("GET / HTTP/1.1\r\n\r\n");
    boost::asio::connect(sock, resolver.resolve({ "localhost", "8080" }));
    boost::asio::write(sock, boost::asio::buffer(REQUEST));

    // read until end-of-stream
    boost::asio::streambuf response;
    auto bytes = boost::asio::read_until(sock, response, "\r\n0\r\n\r\n");

    // convert buffer to a string
    auto responseData = response.data();
    std::string str(boost::asio::buffers_begin(responseData), boost::asio::buffers_begin(responseData) + bytes);
    return str;
}

BOOST_AUTO_TEST_CASE(test_format_of_raw_response)
{
    HttpServer server;
    server.start();
    server.setSink(&chunked_data_handler);
    server.bind("localhost", "8080");

    auto rawResponse = GetRawResponse();
    auto startOfBody = rawResponse.find("\r\n\r\n");
    startOfBody += 4;

    // each chunk should start with "64\r\n" and end with "\r\n".
    auto chunkIterator = startOfBody;
    for (int i=0; i<3; i++)
    {
        auto chunkHeader = rawResponse.substr(chunkIterator, 4);
        BOOST_CHECK_EQUAL(chunkHeader, "64\r\n");
        chunkIterator += 4;
        auto chunkBody = rawResponse.substr(chunkIterator, 100);
        BOOST_CHECK_EQUAL(chunkBody, std::string(DEFAULT_CHUNK_SIZE, 'X'));
        chunkIterator += 100;
        auto chunkTrailer = rawResponse.substr(chunkIterator, 2);
        BOOST_CHECK_EQUAL(chunkTrailer, "\r\n");
        chunkIterator += 2;
    }
}

<|endoftext|>


<commit_before>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"

namespace tamproxy {
    Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha) : _encL(lEncoder), _encR(rEncoder), _gyro(gyro), _alpha(alpha), _lastTime(micros())   {
    }

    std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
    {
        if (request[0] == ODOMETER_READ_CODE) {
            if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};

            // here be dragons
            uint32_t val = *reinterpret_cast<uint32_t*>(&_angle);

            return {
                static_cast<uint8_t>(val>>24),
                static_cast<uint8_t>(val>>16),
                static_cast<uint8_t>(val>>8),
                static_cast<uint8_t>(val)
            };
        }
        else {
            return {REQUEST_BODY_INVALID_CODE};
        }
    }

    void Odometer::update()
    {
        const float ticksPerRev = 3200.0;
        const float wheelDiam = 3.78125;
        const float baseWidth = 17; //inches

        uint32_t lEncVal = _encL.read();
        uint32_t rEncVal = _encR.read();

        // be careful about overflow here
        int32_t diffEnc = lEncVal - rEncVal;
        int32_t meanEnc = rEncVal + diffEnc/2;

        bool ok;
        float gyroRead = _gyro.read(ok);
        if(!ok) return;

        _gyroTot += gyroRead*(micros()-_lastTime); //Get the right number out of _gyro.read()
        float encAngle = (diffEnc/ticksPerRev)*wheelDiam/(baseWidth*M_PI);
        _angle = _alpha*_gyroTot + (1-_alpha)*encAngle;

        _lastTime = micros();
    }
}<commit_msg>Fix width declaration<commit_after>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"

namespace tamproxy {
    Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha) : _encL(lEncoder), _encR(rEncoder), _gyro(gyro), _alpha(alpha), _lastTime(micros())   {
    }

    std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
    {
        if (request[0] == ODOMETER_READ_CODE) {
            if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};

            // here be dragons
            uint32_t val = *reinterpret_cast<uint32_t*>(&_angle);

            return {
                static_cast<uint8_t>(val>>24),
                static_cast<uint8_t>(val>>16),
                static_cast<uint8_t>(val>>8),
                static_cast<uint8_t>(val)
            };
        }
        else {
            return {REQUEST_BODY_INVALID_CODE};
        }
    }

    void Odometer::update()
    {
        const float ticksPerRev = 3200.0;
        const float wheelDiam = 3.78125;
        const float baseWidth = 15.3; //inches

        uint32_t lEncVal = _encL.read();
        uint32_t rEncVal = _encR.read();

        // be careful about overflow here
        int32_t diffEnc = lEncVal - rEncVal;
        int32_t meanEnc = rEncVal + diffEnc/2;

        bool ok;
        float gyroRead = _gyro.read(ok);
        if(!ok) return;

        _gyroTot += gyroRead*(micros()-_lastTime);
        float encAngle = (diffEnc/ticksPerRev)*wheelDiam/baseWidth;
        _angle = _alpha*_gyroTot + (1-_alpha)*encAngle;

        _lastTime = micros();
    }
}<|endoftext|>


<commit_before>/* Gearman server and library
 * Copyright (C) 2008 Brian Aker, Eric Day
 * All rights reserved.
 *
 * Use and distribution licensed under the BSD license.  See
 * the COPYING file in the parent directory for full text.
 */

/**
 * @file
 * @brief libmemcached Queue Storage Definitions
 */

#include <config.h>
#include <libgearman-server/common.h>

#include <libgearman-server/plugins/queue/base.h>
#include <libgearman-server/plugins/queue/libmemcached/queue.h>
#include <libmemcached/memcached.h>

#pragma GCC diagnostic ignored "-Wold-style-cast"

using namespace gearmand;

/**
 * @addtogroup gearmand::plugins::queue::Libmemcachedatic Static libmemcached Queue Storage Functions
 * @ingroup gearman_queue_libmemcached
 * @{
 */

/**
 * Default values.
 */
#define GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX "gear_"

namespace gearmand { namespace plugins { namespace queue { class Libmemcached;  }}}

namespace gearmand {
namespace plugins {
namespace queue {

class Libmemcached : public gearmand::plugins::Queue {
public:
  Libmemcached ();
  ~Libmemcached ();

  gearmand_error_t initialize();

  memcached_st memc;
  std::string server_list;
private:

};

Libmemcached::Libmemcached() :
  Queue("libmemcached")
{
  memcached_create(&memc);

  command_line_options().add_options()
    ("libmemcached-servers", boost::program_options::value(&server_list), "List of Memcached servers to use.");
}

Libmemcached::~Libmemcached()
{
  memcached_free(&memc);
}

static gearmand_error_t _initialize(plugins::queue::Libmemcached *queue,
                                    gearman_server_st *server)
{

  gearmand_info("Initializing libmemcached module");

  memcached_server_st *servers= memcached_servers_parse(queue->server_list.c_str());
  if (servers == NULL)
  {
    gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "memcached_servers_parse");

    return GEARMAN_QUEUE_ERROR;
  }

  memcached_server_push(&queue->memc, servers);
  memcached_server_list_free(servers);

#if 0
  gearman_server_set_queue(server, queue, _libmemcached_add, _libmemcached_flush, _libmemcached_done, _libmemcached_replay);
#endif

  return GEARMAN_SUCCESS;
}

gearmand_error_t Libmemcached::initialize()
{
  return _initialize(this, &Gearmand()->server);
}

void initialize_libmemcached()
{
  static Libmemcached local_instance;
}

} // namespace queue
} // namespace plugins
} // namespace gearmand

/* Queue callback functions. */

namespace gearmand {
namespace queue {

class Libmemcached : public gearmand::queue::Context
{
public:
  Libmemcached()
  {
  }

  ~Libmemcached()
  {
  }

  gearmand_error_t add(gearman_server_st *server,
                       void *context,
                       const char *unique, size_t unique_size,
                       const char *function_name, size_t function_name_size,
                       const void *data, size_t data_size,
                       gearmand_job_priority_t priority,
                       int64_t when);

  gearmand_error_t flush(gearman_server_st *server,
                         void *context);

  gearmand_error_t done(gearman_server_st *server,
                        void *context,
                        const char *unique, size_t unique_size,
                        const char *function_name, size_t function_name_size);

  gearmand_error_t replay(gearman_server_st *server,
                          void *context,
                          gearman_queue_add_fn *add_fn,
                          void *add_context);

private:
};

/** @} */

/*
 * Public definitions
 */

/*
 * Static definitions
 */

gearmand_error_t Libmemcached::flush(gearman_server_st *server,
                                     void *context)
{
  gearmand_debug("libmemcached flush");
  (void)server;
  (void)context;

  return GEARMAN_SUCCESS;
}

gearmand_error_t Libmemcached::done(gearman_server_st *server,
                                    void *context,
                                    const char *unique, size_t unique_size,
                                    const char *function_name, size_t function_name_size)
{
  size_t key_length;
  char key[MEMCACHED_MAX_KEY];
  gearmand::plugins::queue::Libmemcached *queue= (gearmand::plugins::queue::Libmemcached *)context;
  (void)server;

  gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached done: %.*s", (uint32_t)unique_size, (char *)unique);

  key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s",
                               GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX,
                               (int)function_name_size,
                               (const char *)function_name, (int)unique_size,
                               (const char *)unique);

  /* For the moment we will assume it happened */
  memcached_return rc= memcached_delete(&queue->memc, (const char *)key, key_length, 0);
  if (rc != MEMCACHED_SUCCESS)
  {
    return GEARMAN_QUEUE_ERROR;
  }

  return GEARMAN_SUCCESS;
}

struct replay_context
{
  memcached_st clone;
  gearman_server_st *server;
  gearman_queue_add_fn *add_fn;
  void *add_context;
};

static memcached_return callback_loader(const memcached_st *ptr __attribute__((unused)),
                                        memcached_result_st *result __attribute__((unused)),
                                        void *context)
{
  struct replay_context *container= (struct replay_context *)context;
  const char *key;
  const char *unique;
  const char *function;
  size_t function_len;
  char *data;
  size_t data_size;

  key= memcached_result_key_value(result);
  if (strncmp(key, GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, strlen(GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX)))
    return MEMCACHED_SUCCESS;

  function= key + strlen(GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX);

  unique= index(function, '-');

  if (! unique)
    return MEMCACHED_SUCCESS;

  function_len = (size_t) (unique-function);
  unique++;

  assert(unique);
  assert(strlen(unique));
  assert(function);
  assert(function_len);

  data_size= (size_t) memcached_result_length(result);
  /* need to make a copy here ... gearman_server_job_free will free it later */
  data= (char *)malloc(data_size);
  if (data == NULL)
  {
    gearmand_perror("malloc");
    return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
  }
  memcpy(data, memcached_result_value(result), data_size);

  /* Currently not looking at failure cases */
  (void)(*container->add_fn)(container->server, container->add_context,
                             unique, strlen(unique),
                             function, function_len,
                             data, data_size,
                             static_cast<gearmand_job_priority_t>(memcached_result_flags(result)), 0);

  return MEMCACHED_SUCCESS;
}

/* Grab the object and load it into the loader */
static memcached_return callback_for_key(const memcached_st *ptr __attribute__((unused)),
                                         const char *key, size_t key_length,
                                         void *context)
{
  struct replay_context *container= (struct replay_context *)context;
  memcached_execute_function callbacks[1];
  char *passable[1];

  callbacks[0]= (memcached_execute_fn)&callback_loader;

  passable[0]= (char *)key;
  memcached_return_t rc= memcached_mget(&container->clone, passable, &key_length, 1);
  (void)rc;

  /* Just void errors for the moment, since other treads might have picked up the object. */
  (void)memcached_fetch_execute(&container->clone, callbacks, context, 1);

  return MEMCACHED_SUCCESS;
}

/*
  If we have any failures for loading values back into replay we just ignore them.
*/
gearmand_error_t Libmemcached::replay(gearman_server_st *server, void *context,
                                      gearman_queue_add_fn *add_fn,
                                      void *add_context)
{
  gearmand::plugins::queue::Libmemcached *queue= (gearmand::plugins::queue::Libmemcached *)context;
  struct replay_context container;
  memcached_st *check_for_failure;
  memcached_dump_func callbacks[1];

  callbacks[0]= (memcached_dump_fn)&callback_for_key;

  gearmand_info("libmemcached replay start");

  memset(&container, 0, sizeof(struct replay_context));
  check_for_failure= memcached_clone(&container.clone, &queue->memc);
  container.server= server;
  container.add_fn= add_fn;
  container.add_context= add_context;

  assert(check_for_failure);

  (void)memcached_dump(&queue->memc, callbacks, (void *)&container, 1);

  memcached_free(&container.clone);

  return GEARMAN_SUCCESS;
}

} // queue
} // gearmand

<commit_msg>Update the libmemcached queue.<commit_after>/* Gearman server and library
 * Copyright (C) 2008 Brian Aker, Eric Day
 * All rights reserved.
 *
 * Use and distribution licensed under the BSD license.  See
 * the COPYING file in the parent directory for full text.
 */

/**
 * @file
 * @brief libmemcached Queue Storage Definitions
 */

#include <config.h>
#include <libgearman-server/common.h>

#include <libgearman-server/plugins/queue/base.h>
#include <libgearman-server/plugins/queue/libmemcached/queue.h>
#include <libmemcached/memcached.h>

#pragma GCC diagnostic ignored "-Wold-style-cast"

using namespace gearmand;

/**
 * @addtogroup gearmand::plugins::queue::Libmemcachedatic Static libmemcached Queue Storage Functions
 * @ingroup gearman_queue_libmemcached
 * @{
 */

/**
 * Default values.
 */
#define GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX "gear_"

namespace gearmand { namespace plugins { namespace queue { class Libmemcached;  }}}

namespace gearmand {
namespace queue {

class LibmemcachedQueue : public gearmand::queue::Context
{
public:
  LibmemcachedQueue(plugins::queue::Libmemcached* arg) :
    __queue(arg)
  {
  }

  ~LibmemcachedQueue()
  {
  }

  gearmand_error_t add(gearman_server_st *server,
                       const char *unique, size_t unique_size,
                       const char *function_name, size_t function_name_size,
                       const void *data, size_t data_size,
                       gearmand_job_priority_t priority,
                       int64_t when);

  gearmand_error_t flush(gearman_server_st *server);

  gearmand_error_t done(gearman_server_st *server,
                        const char *unique, size_t unique_size,
                        const char *function_name, size_t function_name_size);

  gearmand_error_t replay(gearman_server_st *server);

private:
  gearmand::plugins::queue::Libmemcached *__queue;
};

} // namespace queue
} // namespace gearmand

namespace gearmand {
namespace plugins {
namespace queue {

class Libmemcached : public gearmand::plugins::Queue {
public:
  Libmemcached ();
  ~Libmemcached ();

  gearmand_error_t initialize();

  memcached_st* memc;
  std::string server_list;
private:

};

Libmemcached::Libmemcached() :
  Queue("libmemcached")
{
  memc= memcached_create(NULL);

  command_line_options().add_options()
    ("libmemcached-servers", boost::program_options::value(&server_list), "List of Memcached servers to use.");
}

Libmemcached::~Libmemcached()
{
  memcached_free(memc);
  memc= NULL;
}

gearmand_error_t Libmemcached::initialize()
{
  gearmand_info("Initializing libmemcached module");

  memcached_server_st *servers= memcached_servers_parse(queue->server_list.c_str());
  if (servers == NULL)
  {
    gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "memcached_servers_parse");

    return GEARMAN_QUEUE_ERROR;
  }

  memcached_server_push(queue->memc, servers);
  memcached_server_list_free(servers);

  gearmand::queue::SqliteQueue* exec_queue= new gearmand::queue::SqliteQueue(this);
  gearman_server_set_queue(&Gearmand()->server, exec_queue);

  return GEARMAN_SUCCESS;
}

void initialize_libmemcached()
{
  static Libmemcached local_instance;
}

} // namespace queue
} // namespace plugins
} // namespace gearmand

/* Queue callback functions. */

namespace gearmand {
namespace queue {

gearmand_error_t LibmemcachedQueue::flush(gearman_server_st *)
{
  gearmand_debug("libmemcached flush");

  return GEARMAN_SUCCESS;
}

gearmand_error_t LibmemcachedQueue::done(gearman_server_st*,
                                         const char *unique, size_t unique_size,
                                         const char *function_name, size_t function_name_size)
{
  char key[MEMCACHED_MAX_KEY];

  gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached done: %.*s", (uint32_t)unique_size, (char *)unique);

  size_t key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s",
                                      GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX,
                                      (int)function_name_size,
                                      (const char *)function_name, (int)unique_size,
                                      (const char *)unique);

  /* For the moment we will assume it happened */
  memcached_return rc= memcached_delete(__queue->memc, (const char *)key, key_length, 0);
  if (rc != MEMCACHED_SUCCESS)
  {
    return GEARMAN_QUEUE_ERROR;
  }

  return GEARMAN_SUCCESS;
}

struct replay_context
{
  memcached_st clone;
  gearman_server_st *server;
  gearman_queue_add_fn *add_fn;
  void *add_context;
};

static memcached_return callback_loader(const memcached_st*,
                                        memcached_result_st*,
                                        void *context)
{
  struct replay_context *container= (struct replay_context *)context;
  const char *key;
  const char *unique;
  const char *function;
  size_t function_len;
  char *data;
  size_t data_size;

  key= memcached_result_key_value(result);
  if (strncmp(key, GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, strlen(GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX)))
    return MEMCACHED_SUCCESS;

  function= key + strlen(GEARMAN_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX);

  unique= index(function, '-');

  if (! unique)
    return MEMCACHED_SUCCESS;

  function_len = (size_t) (unique-function);
  unique++;

  assert(unique);
  assert(strlen(unique));
  assert(function);
  assert(function_len);

  data_size= (size_t) memcached_result_length(result);
  /* need to make a copy here ... gearman_server_job_free will free it later */
  data= (char *)malloc(data_size);
  if (data == NULL)
  {
    gearmand_perror("malloc");
    return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
  }
  memcpy(data, memcached_result_value(result), data_size);

  /* Currently not looking at failure cases */
  (void)add(container->server,
            unique, strlen(unique),
            function, function_len,
            data, data_size,
            static_cast<gearmand_job_priority_t>(memcached_result_flags(result)), 0);

  return MEMCACHED_SUCCESS;
}

/* Grab the object and load it into the loader */
static memcached_return callback_for_key(const memcached_st*,
                                         const char *key, size_t key_length,
                                         void *context)
{
  struct replay_context *container= (struct replay_context *)context;
  memcached_execute_function callbacks[1];
  char *passable[1];

  callbacks[0]= (memcached_execute_fn)&callback_loader;

  passable[0]= (char *)key;
  memcached_return_t rc= memcached_mget(&container->clone, passable, &key_length, 1);
  (void)rc;

  /* Just void errors for the moment, since other treads might have picked up the object. */
  (void)memcached_fetch_execute(&container->clone, callbacks, context, 1);

  return MEMCACHED_SUCCESS;
}

/*
  If we have any failures for loading values back into replay we just ignore them.
*/
gearmand_error_t LibmemcachedQueue::replay(gearman_server_st *server)
{
  struct replay_context container;
  memcached_st *check_for_failure;
  memcached_dump_func callbacks[1];

  callbacks[0]= (memcached_dump_fn)&callback_for_key;

  gearmand_info("libmemcached replay start");

  memset(&container, 0, sizeof(struct replay_context));
  check_for_failure= memcached_clone(&container.clone, __queue->memc);
  container.server= server;
  container.add_fn= add_fn;
  container.add_context= add_context;

  assert(check_for_failure);

  (void)memcached_dump(__queue->memc, callbacks, (void *)&container, 1);

  memcached_free(&container.clone);

  return GEARMAN_SUCCESS;
}

} // queue
} // gearmand

<|endoftext|>