<commit_before>// db-test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <nark/db/db_table.hpp>
#include <nark/io/MemStream.hpp>
#include <nark/io/DataIO.hpp>
#include <nark/io/RangeStream.hpp>
#include <nark/lcast.hpp>

struct TestRow {
	uint64_t id;
	nark::db::Schema::Fixed<9> fix;
	std::string str0;
	std::string str1;
	std::string str2;
	DATA_IO_LOAD_SAVE(TestRow,
		&id
		&fix

		// StrZero would never be serialized as LastColumn/RestAll
		&nark::db::Schema::StrZero(str0)

		&str1
		&nark::RestAll(str2)
		)
};

using namespace nark::db;

void doTest(nark::fstring tableClass, PathRef tableDir, size_t maxRowNum) {
	using namespace nark;
	CompositeTablePtr tab = CompositeTable::createTable(tableClass);
	tab->load(tableDir);
	DbContextPtr ctx(tab->createDbContext());

	valvec<byte> recBuf;
	NativeDataOutput<AutoGrownMemIO> rowBuilder;
	TestRow recRow;

	size_t insertedRows = 0;
	size_t deletedRows = 0;
	febitvec bits(maxRowNum + 1);
	for (size_t i = 0; i < maxRowNum; ++i) {
		TestRow recRow;
		recRow.id = rand() % maxRowNum + 1;
		sprintf(recRow.fix.data, "%06lld", recRow.id);
		recRow.str0 = std::string("s0:") + recRow.fix.data;
		recRow.str1 = std::string("s1:") + recRow.fix.data;
		recRow.str2 = std::string("s2:") + recRow.fix.data;
		rowBuilder.rewind();
		rowBuilder << recRow;
		fstring binRow(rowBuilder.begin(), rowBuilder.tell());
		if (bits[recRow.id]) {
			printf("dupkey: %s\n", tab->rowSchema().toJsonStr(binRow).c_str());
		}
		if (1067 == i)
			i = i;
		llong recId = ctx->insertRow(binRow);
		if (recId < 0) {
		//	assert(bits.is1(recRow.id));
			printf("Insert failed: %s\n", ctx->errMsg.c_str());
		} else {
			printf("Insert recId = %lld: %s\n", recId, tab->toJsonStr(binRow).c_str());
			insertedRows++;
		//	assert(bits.is0(recRow.id));
		}
		bits.set1(recRow.id);

		if (rand() < RAND_MAX*0.3) {
			llong randomRecordId = rand() % tab->numDataRows();
			uint64_t keyId = 0;
			recBuf.erase_all();
			std::string jstr;
			if (tab->exists(randomRecordId)) {
				size_t indexId = tab->getIndexId("id");
				assert(indexId < tab->getIndexNum());
				tab->selectOneColumn(randomRecordId, indexId, &recBuf, &*ctx);
				keyId = unaligned_load<uint64_t>(recBuf.data());
				ctx->getValue(randomRecordId, &recBuf);
				jstr = tab->toJsonStr(recBuf);
				assert(keyId > 0);
			//	assert(bits.is1(keyId));
			}
			bool isDeleted = false;
			if (rand() < RAND_MAX*0.3) {
				// may remove deleted record
				ctx->removeRow(randomRecordId);
				isDeleted = true;
			}
			else if (tab->exists(randomRecordId)) {
				ctx->removeRow(randomRecordId);
				isDeleted = true;
			}
			if (isDeleted && keyId > 0) {
				printf("delete success: recId = %lld: %s\n"
					, randomRecordId, jstr.c_str());
				bits.set0(keyId);
				deletedRows++;
			}
		}
	}

//	NativeDataInput<RangeStream<MemIO> > decoder;
//	NativeDataInput<MemIO> decoder;
//	decoder.set(rowBuilder.head());
//	decoder.setRangeLen(decoder.remain());
//	decoder >> recRow;

	{
		valvec<byte> keyHit, val;
		valvec<llong> idvec;
		for (size_t indexId = 0; indexId < tab->getIndexNum(); ++indexId) {
			IndexIteratorPtr indexIter = tab->createIndexIterForward(indexId);
			const Schema& indexSchema = tab->getIndexSchema(indexId);
			std::string keyData;
			for (size_t i = 0; i < maxRowNum/5; ++i) {
				llong keyInt = rand() % (maxRowNum * 11 / 10);
				char keyBuf[64];
				switch (indexId) {
				default:
					assert(0);
					break;
				case 0:
					keyData.assign((char*)&keyInt, 8);
					break;
				case 1: // str0
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 2: // str1
					sprintf(keyBuf, "s1:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 3: // str2
					sprintf(keyBuf, "s2:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 4: // fix
					assert(indexSchema.getFixedRowLen() > 0);
					keyData.resize(0);
					keyData.resize(indexSchema.getFixedRowLen());
					sprintf(&keyData[0], "%06lld", keyInt);
					break;
				case 5: // str0,str1
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData = keyBuf;
					keyData.push_back('\0');
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData.append(keyBuf);
					break;
				}
				idvec.resize(0);
				std::string keyJson = indexSchema.toJsonStr(keyData);
				printf("find index key = %s", keyJson.c_str());
				fflush(stdout);
				llong recId;
				if (i == 0x002d && indexId == 1)
					i = i;
				int ret = indexIter->seekLowerBound(keyData, &recId, &keyHit);
				if (ret > 0) {
					printf(", found upper_bound key=%s, recId=%lld\n",
						indexSchema.toJsonStr(keyHit).c_str(), recId);
				//	printf(", found hitkey > key, show first upper_bound:\n");
				//	idvec.push_back(recId);
				}
				else if (ret < 0) { // all keys are less than search key
					printf(", all keys are less than search key\n");
				}
				else if (ret == 0) { // found exact key
					idvec.push_back(recId);
					int hasNext; // int as bool
					while ((hasNext = indexIter->increment(&recId, &keyHit))
							&& fstring(keyHit) == keyData) {
						assert(recId < tab->numDataRows());
						idvec.push_back(recId);
					}
					if (hasNext)
						idvec.push_back(recId);
					printf(", found %zd exact and %d upper_bound\n",
						idvec.size()-hasNext, hasNext);
				}
				for (size_t i = 0; i < idvec.size(); ++i) {
					recId = idvec[i];
					ctx->getValue(recId, &val);
					printf("%8lld  | %s\n", recId, tab->toJsonStr(val).c_str());
				}
			}
		}
	}

	{
		printf("test iterate table, numDataRows=%lld ...\n", tab->numDataRows());
		StoreIteratorPtr storeIter = ctx->createTableIter();
		llong recId;
		valvec<byte> val;
		llong iterRows = 0;
		while (storeIter->increment(&recId, &val)) {
			printf("%8lld  | %s\n", recId, tab->toJsonStr(val).c_str());
			++iterRows;
		}
		printf("test iterate table passed, iterRows=%lld, insertedRows=%lld\n",
			iterRows, insertedRows);
	}

	// last writable segment will put to compressing queue
	tab->syncFinishWriting();
}

int main(int argc, char* argv[]) {
	if (argc < 2) {
		fprintf(stderr, "usage: %s maxRowNum\n", argv[0]);
		return 1;
	}
	size_t maxRowNum = (size_t)strtoull(argv[1], NULL, 10);
//	doTest("MockCompositeTable", "db1", maxRowNum);
	doTest("DfaDbTable", "dfadb", maxRowNum);
	CompositeTable::safeStopAndWaitForCompress();
    return 0;
}

<commit_msg>db-test: update<commit_after>// db-test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <nark/db/db_table.hpp>
#include <nark/io/MemStream.hpp>
#include <nark/io/DataIO.hpp>
#include <nark/io/RangeStream.hpp>
#include <nark/lcast.hpp>

struct TestRow {
	uint64_t id;
	nark::db::Schema::Fixed<9> fix;
	std::string str0;
	std::string str1;
	std::string str2;
	DATA_IO_LOAD_SAVE(TestRow,
		&id
		&fix

		// StrZero would never be serialized as LastColumn/RestAll
		&nark::db::Schema::StrZero(str0)

		&str1
		&nark::RestAll(str2)
		)
};

using namespace nark::db;

void doTest(nark::fstring tableClass, PathRef tableDir, size_t maxRowNum) {
	using namespace nark;
	CompositeTablePtr tab = CompositeTable::createTable(tableClass);
	tab->load(tableDir);
	DbContextPtr ctx(tab->createDbContext());

	valvec<byte> recBuf;
	NativeDataOutput<AutoGrownMemIO> rowBuilder;
	TestRow recRow;

	size_t insertedRows = 0;
	size_t deletedRows = 0;
	febitvec bits(maxRowNum + 1);
	for (size_t i = 0; i < maxRowNum; ++i) {
		TestRow recRow;
		recRow.id = rand() % maxRowNum + 1;
		sprintf(recRow.fix.data, "%06lld", recRow.id);
		recRow.str0 = std::string("s0:") + recRow.fix.data;
		recRow.str1 = std::string("s1:") + recRow.fix.data;
		recRow.str2 = std::string("s2:") + recRow.fix.data;
		rowBuilder.rewind();
		rowBuilder << recRow;
		fstring binRow(rowBuilder.begin(), rowBuilder.tell());
		if (bits[recRow.id]) {
			if (!tab->indexKeyExists(0, fstring((char*)&recRow.id, 8), &*ctx)) {
				i = i;
			}
			printf("dupkey: %s\n", tab->rowSchema().toJsonStr(binRow).c_str());
		}
		if (600 == i)
			i = i;
		llong recId = ctx->insertRow(binRow);
		if (recId < 0) {
			assert(bits.is1(recRow.id));
			printf("Insert failed: %s\n", ctx->errMsg.c_str());
		} else {
			printf("Insert recId = %lld: %s\n", recId, tab->toJsonStr(binRow).c_str());
			insertedRows++;
			if (bits.is1(recRow.id)) {
				ctx->removeRow(recId);
				llong recId2 = ctx->insertRow(binRow);
			}
			assert(tab->exists(recId));
			assert(bits.is0(recRow.id));
		}
		bits.set1(recRow.id);
#if 1
		if (rand() < RAND_MAX*0.3) {
			llong randomRecordId = rand() % tab->numDataRows();
			uint64_t keyId = 0;
			recBuf.erase_all();
			std::string jstr;
			if (tab->exists(randomRecordId)) {
				size_t indexId = tab->getIndexId("id");
				assert(indexId < tab->getIndexNum());
				tab->selectOneColumn(randomRecordId, indexId, &recBuf, &*ctx);
				keyId = unaligned_load<uint64_t>(recBuf.data());
				if (keyId == 27754)
					keyId = keyId;
				ctx->getValue(randomRecordId, &recBuf);
				jstr = tab->toJsonStr(recBuf);
				assert(keyId > 0);
			//	assert(bits.is1(keyId));
			}
			bool isDeleted = false;
			if (rand() < RAND_MAX*0.3) {
				// may remove deleted record
				ctx->removeRow(randomRecordId);
				isDeleted = true;
			}
			else if (tab->exists(randomRecordId)) {
				ctx->removeRow(randomRecordId);
				isDeleted = true;
			}
			if (isDeleted && keyId > 0) {
				printf("delete success: recId = %lld: %s\n"
					, randomRecordId, jstr.c_str());
				assert(!tab->exists(randomRecordId));
				bits.set0(keyId);
				deletedRows++;
			}
		}
#endif
	}

//	NativeDataInput<RangeStream<MemIO> > decoder;
//	NativeDataInput<MemIO> decoder;
//	decoder.set(rowBuilder.head());
//	decoder.setRangeLen(decoder.remain());
//	decoder >> recRow;

	{
		valvec<byte> keyHit, val;
		valvec<llong> idvec;
		for (size_t indexId = 0; indexId < tab->getIndexNum(); ++indexId) {
			IndexIteratorPtr indexIter = tab->createIndexIterForward(indexId);
			const Schema& indexSchema = tab->getIndexSchema(indexId);
			std::string keyData;
			for (size_t i = 0; i < maxRowNum/5; ++i) {
				llong keyInt = rand() % (maxRowNum * 11 / 10);
				char keyBuf[64];
				switch (indexId) {
				default:
					assert(0);
					break;
				case 0:
					keyData.assign((char*)&keyInt, 8);
					break;
				case 1: // str0
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 2: // str1
					sprintf(keyBuf, "s1:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 3: // str2
					sprintf(keyBuf, "s2:%06lld", keyInt);
					keyData = keyBuf;
					break;
				case 4: // fix
					assert(indexSchema.getFixedRowLen() > 0);
					keyData.resize(0);
					keyData.resize(indexSchema.getFixedRowLen());
					sprintf(&keyData[0], "%06lld", keyInt);
					break;
				case 5: // str0,str1
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData = keyBuf;
					keyData.push_back('\0');
					sprintf(keyBuf, "s0:%06lld", keyInt);
					keyData.append(keyBuf);
					break;
				}
				idvec.resize(0);
				std::string keyJson = indexSchema.toJsonStr(keyData);
				printf("find index key = %s", keyJson.c_str());
				fflush(stdout);
				llong recId;
				if (i == 0x002d && indexId == 1)
					i = i;
				int ret = indexIter->seekLowerBound(keyData, &recId, &keyHit);
				if (ret > 0) {
					printf(", found upper_bound key=%s, recId=%lld\n",
						indexSchema.toJsonStr(keyHit).c_str(), recId);
				//	printf(", found hitkey > key, show first upper_bound:\n");
				//	idvec.push_back(recId);
				}
				else if (ret < 0) { // all keys are less than search key
					printf(", all keys are less than search key\n");
				}
				else if (ret == 0) { // found exact key
					idvec.push_back(recId);
					int hasNext; // int as bool
					while ((hasNext = indexIter->increment(&recId, &keyHit))
							&& fstring(keyHit) == keyData) {
						assert(recId < tab->numDataRows());
						idvec.push_back(recId);
					}
					if (hasNext)
						idvec.push_back(recId);
					printf(", found %zd exact and %d upper_bound\n",
						idvec.size()-hasNext, hasNext);
				}
				for (size_t i = 0; i < idvec.size(); ++i) {
					recId = idvec[i];
					ctx->getValue(recId, &val);
					printf("%8lld  | %s\n", recId, tab->toJsonStr(val).c_str());
				}
			}
		}
	}

	{
		printf("test iterate table, numDataRows=%lld ...\n", tab->numDataRows());
		StoreIteratorPtr storeIter = ctx->createTableIter();
		llong recId;
		valvec<byte> val;
		llong iterRows = 0;
		while (storeIter->increment(&recId, &val)) {
			printf("%8lld  | %s\n", recId, tab->toJsonStr(val).c_str());
			++iterRows;
		}
		printf("test iterate table passed, iterRows=%lld, insertedRows=%lld\n",
			iterRows, insertedRows);
	}

	// last writable segment will put to compressing queue
	tab->syncFinishWriting();
}

int main(int argc, char* argv[]) {
	if (argc < 2) {
		fprintf(stderr, "usage: %s maxRowNum\n", argv[0]);
		return 1;
	}
	size_t maxRowNum = (size_t)strtoull(argv[1], NULL, 10);
//	doTest("MockCompositeTable", "db1", maxRowNum);
	doTest("DfaDbTable", "dfadb", maxRowNum);
	CompositeTable::safeStopAndWaitForCompress();
    return 0;
}

<|endoftext|>


<commit_before>// $Id: kelly_error_estimator.C,v 1.22 2006-10-26 17:15:59 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// 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

// C++ includes
#include <algorithm> // for std::fill
#include <cmath>    // for sqrt

// Local Includes
#include "libmesh_common.h"
#include "kelly_error_estimator.h"
#include "dof_map.h"
#include "error_vector.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "mesh.h"
#include "system.h"

#include "dense_vector.h"

void
KellyErrorEstimator::initialize(const System& system,
                                ErrorVector&,
                                bool)
{
  // Hang onto the system - we may need it for variable names later.
  my_system = &system;

  // We'll need gradients and normal vectors for flux jump computation
  fe_fine->get_dphi();
  fe_fine->get_normals();
  fe_coarse->get_dphi();
}

void
KellyErrorEstimator::internal_side_integration ()
{
  Real error = 1.e-30;
  unsigned int n_qp = fe_fine->n_quadrature_points();
  unsigned int n_fine_dofs = Ufine.size();
  unsigned int n_coarse_dofs = Ucoarse.size();

  std::vector<std::vector<RealGradient> > dphi_coarse = fe_coarse->get_dphi();
  std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();

  for (unsigned int qp=0; qp != n_qp; ++qp)
    {
      // Calculate solution gradients on fine and coarse elements
      // at this quadrature point
      Gradient grad_fine, grad_coarse;
      for (unsigned int i=0; i != n_coarse_dofs; ++i)
        grad_coarse.add_scaled (dphi_coarse[i][qp], Ucoarse(i));

      for (unsigned int i=0; i != n_fine_dofs; ++i)
        grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));

      // Find the jump in the normal derivative
      // at this quadrature point
      const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
#ifndef USE_COMPLEX_NUMBERS
      const Real jump2 = jump*jump;
#else
      const Real jump2 = std::norm(jump);
#endif
      // Accumulate the jump integral
      error += JxW_face[qp] * jump2;
    }

  // Add the h-weighted jump integral to each error term
  fine_error =
    error * fine_elem->hmax() * component_scale[var];
  coarse_error =
    error * coarse_elem->hmax() * component_scale[var];
}

bool
KellyErrorEstimator::boundary_side_integration ()
{
  const std::string &var_name = my_system->variable_name(var);

  std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();
  std::vector<Point> qface_point = fe_fine->get_xyz();

  // The reinitialization also recomputes the locations of
  // the quadrature points on the side.  By checking if the
  // first quadrature point on the side is on a flux boundary
  // for a particular variable, we will determine if the whole
  // element is on a flux boundary (assuming quadrature points
  // are strictly contained in the side).
  if (this->_bc_function(*my_system, qface_point[0], var_name).first)
    {
      const Real h = fine_elem->hmax();

      // The number of quadrature points
      const unsigned int n_qp = fe_fine->n_quadrature_points();

      // The error contribution from this face
      Real error = 1.e-30;

      // loop over the integration points on the face.
      for (unsigned int qp=0; qp<n_qp; qp++)
        {
          // Value of the imposed flux BC at this quadrature point.
          const std::pair<bool,Real> flux_bc =
            this->_bc_function(*my_system, qface_point[qp], var_name);

          // Be sure the BC function still thinks we're on the
          // flux boundary.
          assert (flux_bc.first == true);

          // The solution gradient from each element
          Gradient grad_fine;

          // Compute the solution gradient on element e
          for (unsigned int i=0; i != Ufine.size(); i++)
            grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));

          // The difference between the desired BC and the approximate solution.
          const Number jump = flux_bc.second - grad_fine*face_normals[qp];

          // The flux jump squared.  If using complex numbers,
          // std::norm(z) returns |z|^2, where |z| is the modulus of z.
#ifndef USE_COMPLEX_NUMBERS
          const Real jump2 = jump*jump;
#else
          const Real jump2 = std::norm(jump);
#endif

          // Integrate the error on the face.  The error is
          // scaled by an additional power of h, where h is
          // the maximum side length for the element.  This
          // arises in the definition of the indicator.
          error += JxW_face[qp]*jump2;

        } // End quadrature point loop

      fine_error = error*h*component_scale[var];

      return true;
    } // end if side on flux boundary
  return false;
}

void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system,
									const Point& p,
									const std::string& var_name))
{
  _bc_function = fptr;

// We may be turning boundary side integration on or off
  if (fptr)
    integrate_boundary_sides = true;
  else
    integrate_boundary_sides = false;
}
<commit_msg>Removed unnecessary headers<commit_after>// $Id: kelly_error_estimator.C,v 1.23 2007-10-05 20:51:40 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// 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

// C++ includes
#include <algorithm> // for std::fill
#include <cmath>    // for sqrt

// Local Includes
#include "libmesh_common.h"
#include "kelly_error_estimator.h"
#include "error_vector.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "system.h"

#include "dense_vector.h"

void
KellyErrorEstimator::initialize(const System& system,
                                ErrorVector&,
                                bool)
{
  // Hang onto the system - we may need it for variable names later.
  my_system = &system;

  // We'll need gradients and normal vectors for flux jump computation
  fe_fine->get_dphi();
  fe_fine->get_normals();
  fe_coarse->get_dphi();
}

void
KellyErrorEstimator::internal_side_integration ()
{
  Real error = 1.e-30;
  unsigned int n_qp = fe_fine->n_quadrature_points();
  unsigned int n_fine_dofs = Ufine.size();
  unsigned int n_coarse_dofs = Ucoarse.size();

  std::vector<std::vector<RealGradient> > dphi_coarse = fe_coarse->get_dphi();
  std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();

  for (unsigned int qp=0; qp != n_qp; ++qp)
    {
      // Calculate solution gradients on fine and coarse elements
      // at this quadrature point
      Gradient grad_fine, grad_coarse;
      for (unsigned int i=0; i != n_coarse_dofs; ++i)
        grad_coarse.add_scaled (dphi_coarse[i][qp], Ucoarse(i));

      for (unsigned int i=0; i != n_fine_dofs; ++i)
        grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));

      // Find the jump in the normal derivative
      // at this quadrature point
      const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
#ifndef USE_COMPLEX_NUMBERS
      const Real jump2 = jump*jump;
#else
      const Real jump2 = std::norm(jump);
#endif
      // Accumulate the jump integral
      error += JxW_face[qp] * jump2;
    }

  // Add the h-weighted jump integral to each error term
  fine_error =
    error * fine_elem->hmax() * component_scale[var];
  coarse_error =
    error * coarse_elem->hmax() * component_scale[var];
}

bool
KellyErrorEstimator::boundary_side_integration ()
{
  const std::string &var_name = my_system->variable_name(var);

  std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();
  std::vector<Point> qface_point = fe_fine->get_xyz();

  // The reinitialization also recomputes the locations of
  // the quadrature points on the side.  By checking if the
  // first quadrature point on the side is on a flux boundary
  // for a particular variable, we will determine if the whole
  // element is on a flux boundary (assuming quadrature points
  // are strictly contained in the side).
  if (this->_bc_function(*my_system, qface_point[0], var_name).first)
    {
      const Real h = fine_elem->hmax();

      // The number of quadrature points
      const unsigned int n_qp = fe_fine->n_quadrature_points();

      // The error contribution from this face
      Real error = 1.e-30;

      // loop over the integration points on the face.
      for (unsigned int qp=0; qp<n_qp; qp++)
        {
          // Value of the imposed flux BC at this quadrature point.
          const std::pair<bool,Real> flux_bc =
            this->_bc_function(*my_system, qface_point[qp], var_name);

          // Be sure the BC function still thinks we're on the
          // flux boundary.
          assert (flux_bc.first == true);

          // The solution gradient from each element
          Gradient grad_fine;

          // Compute the solution gradient on element e
          for (unsigned int i=0; i != Ufine.size(); i++)
            grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));

          // The difference between the desired BC and the approximate solution.
          const Number jump = flux_bc.second - grad_fine*face_normals[qp];

          // The flux jump squared.  If using complex numbers,
          // std::norm(z) returns |z|^2, where |z| is the modulus of z.
#ifndef USE_COMPLEX_NUMBERS
          const Real jump2 = jump*jump;
#else
          const Real jump2 = std::norm(jump);
#endif

          // Integrate the error on the face.  The error is
          // scaled by an additional power of h, where h is
          // the maximum side length for the element.  This
          // arises in the definition of the indicator.
          error += JxW_face[qp]*jump2;

        } // End quadrature point loop

      fine_error = error*h*component_scale[var];

      return true;
    } // end if side on flux boundary
  return false;
}

void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system,
									const Point& p,
									const std::string& var_name))
{
  _bc_function = fptr;

// We may be turning boundary side integration on or off
  if (fptr)
    integrate_boundary_sides = true;
  else
    integrate_boundary_sides = false;
}
<|endoftext|>


<commit_before>#ifndef __STAN__IO__VAR_CONTEXT_HPP__
#define __STAN__IO__VAR_CONTEXT_HPP__

#include <vector>

namespace stan {

  namespace io {

    /**
     * A var_reader reads array variables of integer and
     * floating point type by name and dimension.
     *
     *
An array's dimensionality is described by a sequence of
     * (unsigned) integers.  For instance, (7, 2, 3) picks
     * out a 7 by 2 by 3 array.  The empty dimensionality sequence
     * () is used for scalars.
     *
     *
Multidimensional arrays are stored in column-major order,
     * meaning the first index changes the most quickly.
     *
     *
If a variable has integer variables, it should return
     * those integer values cast to floating point values when
     * accessed through the floating-point methods.
     */
    class var_context {
    public:

      /**
       * Return true if the specified variable name is
       * defined.  This method should return true even
       * if the values are all integers.
       *
       * @param name Name of variable.
       * @return true if the variable exists with real
       * values.
       */
      virtual bool contains_r(const std::string& name) = 0;

      /**
       * Return the floating point values for the variable of the specified
       * variable name.  This method should cast integers to floating
       * point values if the values of the named variable are all integers.
       *
       *
If there is no variable of the specified name, the empty
       * vector is returned.
       *
       * @param name Name of variable.
       * @return Sequence of values for the named variable.
       */
      virtual std::vector<double> vals_r(const std::string& name) = 0;

      /**
       * Return the dimensions for the specified floating point variable.
       * If the variable doesn't exist or if it is a scalar, the
       * return result should be the empty vector.
       *
       * @param name Name of variable.
       * @return Sequence of dimensions for the variable.
       */
      virtual std::vector<unsigned int> dims_r(const std::string& name) = 0;

      /**
       * Return true if the specified variable name has
       * integer values.
       *
       * @param name Name of variable.
       * @return true if an integer variable of the specified
       * name is defined.
       */
      virtual bool contains_i(const std::string& name) = 0;

      /**
       * Return the integer values for the variable of the specified name
       * or the empty sequence if the variable is not defined.
       *
       * @param name Name of variable.
       * @return Sequence of integer values.
       */
      virtual std::vector<int> vals_i(const std::string& name) = 0;

      /**
       * Return the dimensions of the specified floating point variable.
       * If the variable doesn't exist (or if it is a scalar), the
       * return result should be the empty vector.
       *
       * @param name Name of variable.
       * @return Sequence of dimensions for the variable.
       */
      virtual std::vector<unsigned int> dims_i(const std::string& name) = 0;

      /**
       * Return a list of the names of the floating point variables in
       * the context.
       *
       * @param names Vector to store the list of names in.
       */
      virtual void names_r(std::vector<std::string>& names) = 0;

      /**
       * Return a list of the names of the integer variables in
       * the context.
       *
       * @param Vector to store the list of names in.
       */
      virtual void names_i(std::vector<std::string>& names) = 0;
    };

  }

}

#endif
<commit_msg>updated documentation<commit_after>#ifndef __STAN__IO__VAR_CONTEXT_HPP__
#define __STAN__IO__VAR_CONTEXT_HPP__

#include <vector>

namespace stan {

  namespace io {

    /**
     * A var_reader reads array variables of integer and
     * floating point type by name and dimension.
     *
     *
An array's dimensionality is described by a sequence of
     * (unsigned) integers.  For instance, (7, 2, 3) picks
     * out a 7 by 2 by 3 array.  The empty dimensionality sequence
     * () is used for scalars.
     *
     *
Multidimensional arrays are stored in column-major order,
     * meaning the first index changes the most quickly.
     *
     *
If a variable has integer variables, it should return
     * those integer values cast to floating point values when
     * accessed through the floating-point methods.
     */
    class var_context {
    public:

      /**
       * Return true if the specified variable name is
       * defined.  This method should return true even
       * if the values are all integers.
       *
       * @param name Name of variable.
       * @return true if the variable exists with real
       * values.
       */
      virtual bool contains_r(const std::string& name) = 0;

      /**
       * Return the floating point values for the variable of the specified
       * variable name.  This method should cast integers to floating
       * point values if the values of the named variable are all integers.
       *
       *
If there is no variable of the specified name, the empty
       * vector is returned.
       *
       * @param name Name of variable.
       * @return Sequence of values for the named variable.
       */
      virtual std::vector<double> vals_r(const std::string& name) = 0;

      /**
       * Return the dimensions for the specified floating point variable.
       * If the variable doesn't exist or if it is a scalar, the
       * return result should be the empty vector.
       *
       * @param name Name of variable.
       * @return Sequence of dimensions for the variable.
       */
      virtual std::vector<unsigned int> dims_r(const std::string& name) = 0;

      /**
       * Return true if the specified variable name has
       * integer values.
       *
       * @param name Name of variable.
       * @return true if an integer variable of the specified
       * name is defined.
       */
      virtual bool contains_i(const std::string& name) = 0;

      /**
       * Return the integer values for the variable of the specified name
       * or the empty sequence if the variable is not defined.
       *
       * @param name Name of variable.
       * @return Sequence of integer values.
       */
      virtual std::vector<int> vals_i(const std::string& name) = 0;

      /**
       * Return the dimensions of the specified floating point variable.
       * If the variable doesn't exist (or if it is a scalar), the
       * return result should be the empty vector.
       *
       * @param name Name of variable.
       * @return Sequence of dimensions for the variable.
       */
      virtual std::vector<unsigned int> dims_i(const std::string& name) = 0;

      /**
       * Return a list of the names of the floating point variables in
       * the context.
       *
       * @param names Vector to store the list of names in.
       */
      virtual void names_r(std::vector<std::string>& names) = 0;

      /**
       * Return a list of the names of the integer variables in
       * the context.
       *
       * @param names Vector to store the list of names in.
       */
      virtual void names_i(std::vector<std::string>& names) = 0;
    };

  }

}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "demoloop.h"
#include "helpers.h"
#include "hsl.h"
using namespace std;

float t = 0;
const float PI = 3.1459;
const float CYCLE_LENGTH = 10;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {}

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const int num_vertices = 5;
    const float interval = (PI * 2) / num_vertices;
    int16_t xCoords[num_vertices];
    int16_t yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    filledPolygonColor(renderer, xCoords, yCoords, num_vertices, rgb2uint32(color));

    const int dot_count = 20;
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (float i = 0; i < dot_count; ++i) {
        float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

        float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255 * interval_cycle_ratio);
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;
      float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;

      filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255);
    }
  }

private:
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<commit_msg>update loop5<commit_after>#include <iostream>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "demoloop.h"
#include "helpers.h"
#include "hsl.h"
using namespace std;

float t = 0;
const float PI = 3.1459;
const float CYCLE_LENGTH = 10;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {}

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const int num_vertices = 5;
    const float interval = (PI * 2) / num_vertices;
    int16_t xCoords[num_vertices];
    int16_t yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    filledPolygonColor(renderer, xCoords, yCoords, num_vertices, rgb2uint32(color));
    const int dot_count = 20;
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (float i = 0; i < dot_count; ++i) {
        const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

        const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255 * interval_cycle_ratio);

        if (i == 0) {
          const float x2 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float y2 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          lineRGBA(renderer, x2 + ox, y2 + oy, xCoords[v], yCoords[v], 0, 0, 0, 255);
        }
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;
      const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;

      filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255);
    }
  }

private:
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<|endoftext|>


<commit_before>#include "../Optimiser/Optimiser.h"

#include "../Simulator/Simulator.h"
#include "../Models/FourLayerVisionSpikingModel.h"

#include "../SpikeAnalyser/SpikeAnalyser.h"
#include "../Helpers/TimerWithMessages.h"
#include "../Helpers/TerminalHelpers.h"
#include "../Helpers/MemoryUsage.h"

#include "cuda_profiler_api.h"

// Use the following line to compile the binary
// make FILE='OptimiseFourLayerVisionSpikingModelFiringRates' EXPERIMENT_DIRECTORY='Experiments'  model -j22

// The function which will autorun when the executable is created
int main (int argc, char *argv[]){

	TimerWithMessages * experiment_timer = new TimerWithMessages("\n");

	// // Parameters for OPTIMISATION + Information Analysis
	// const float optimal_max_firing_rate = 100.0f;//set if optimizing based on maxfr //Maximum rate (spikes/sec) 87 +- 46  (*1)
	// //*1 Bair, W., & Movshon, J. A. (2004).  Adaptive Temporal Integration of Motion in Direction-Selective Neurons in Macaque Visual Cortex. The Journal of Neuroscience, 24(33), 7305遯ｶ�ｿｽ7323.
	// int number_of_bins = 5;
	// bool useThresholdForMaxFR = true;
	// float max_firing_rate = optimal_max_firing_rate*presentation_time_per_stimulus_per_epoch_test;

	const float presentation_time_per_stimulus_per_epoch = 0.3;

	// SIMULATOR OPTIONS
	Simulator_Options * simulator_options = new Simulator_Options();

	simulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch = presentation_time_per_stimulus_per_epoch;
	simulator_options->run_simulation_general_options->number_of_epochs = 1;
	simulator_options->run_simulation_general_options->apply_stdp_to_relevant_synapses = false;
	simulator_options->run_simulation_general_options->stimulus_presentation_order_seed = 1;

	simulator_options->recording_electrodes_options->count_neuron_spikes_recording_electrodes_bool = true;

	simulator_options->stimuli_presentation_options->presentation_format = PRESENTATION_FORMAT_OBJECT_BY_OBJECT_RESET_BETWEEN_STIMULI;
	simulator_options->stimuli_presentation_options->object_order = OBJECT_ORDER_ORIGINAL;
	simulator_options->stimuli_presentation_options->transform_order = TRANSFORM_ORDER_ORIGINAL;

	// MODEL
	FourLayerVisionSpikingModel * four_layer_vision_spiking_model = new FourLayerVisionSpikingModel();
	four_layer_vision_spiking_model->SetTimestep(0.00002);
	four_layer_vision_spiking_model->high_fidelity_spike_storage = true;
	four_layer_vision_spiking_model->inputs_directory = "MatlabGaborFilter/Inputs_1T_FR_OPT/";

	// OPTIMISATION
	float upper = 150.0;
	float lower = 100.0;
	int number_of_optimisation_stages = 7;

	Optimiser* optimiser = new Optimiser(four_layer_vision_spiking_model);

	if (number_of_optimisation_stages > 0) {

		Optimiser_Options * optimisation_stage_0_options = new Optimiser_Options();
		optimisation_stage_0_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0];
		optimisation_stage_0_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
		optimisation_stage_0_options->ideal_output_score = upper;
		optimisation_stage_0_options->score_to_use = SCORE_TO_USE_average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons;

		optimiser->AddOptimisationStage(optimisation_stage_0_options, simulator_options);

	}

	// printf("optimiser->spike_analyser_from_last_optimisation_stage->average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons[index_of_neuron_group_of_interest_for_each_optimisation_stage[optimisation_stage]]\n");

	optimiser->RunOptimisation();

	// float temp = (int)optimiser->spike_analyser_from_last_optimisation_stage->running_count_of_non_silent_neurons_per_neuron_group[0];
	// printf("optimiser->spike_analyser_from_last_optimisation_stage->running_count_of_non_silent_neurons_per_neuron_group[0]: %f\n", temp);

	float temp = optimiser->spike_analyser_from_last_optimisation_stage->average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons[0];

	if (number_of_optimisation_stages > 1) {

		Optimiser_Options * optimisation_stage_1_options = new Optimiser_Options();
		optimisation_stage_1_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0];
		optimisation_stage_1_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2I_L_SYNAPSES_ON;
		optimisation_stage_1_options->use_inhibitory_neurons = true;
		optimisation_stage_1_options->index_of_neuron_group_of_interest = 1;
		optimisation_stage_1_options->ideal_output_score = upper;
		optimisation_stage_1_options->score_to_use = SCORE_TO_USE_average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons;

		optimiser->AddOptimisationStage(optimisation_stage_1_options, simulator_options);

	}

	if (number_of_optimisation_stages > 2) {

		Optimiser_Options * optimisation_stage_2_options = new Optimiser_Options();
		optimisation_stage_2_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0];
		optimisation_stage_2_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->I2E_L_SYNAPSES_ON;
		optimisation_stage_2_options->use_inhibitory_neurons = true;
		optimisation_stage_2_options->index_of_neuron_group_of_interest = 0;
		optimisation_stage_2_options->ideal_output_score = 0.8*temp;
		optimisation_stage_2_options->positive_effect_of_postive_change_in_parameter = true;
		// optimisation_stage_2_options->score_to_use = SCORE_TO_USE_running_count_of_non_silent_neurons_per_neuron_group;
		// optimisation_stage_2_options->optimisation_minimum_error = 10.0;

		optimiser->AddOptimisationStage(optimisation_stage_2_options, simulator_options);

	}

	optimiser->RunOptimisation(1);

	// if (number_of_optimisation_stages > 3) {

	// 	Optimiser_Options * optimisation_stage_3_options = new Optimiser_Options();
	// 	optimisation_stage_3_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0];
	// 	optimisation_stage_3_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_L_SYNAPSES_ON;
	// 	optimisation_stage_3_options->use_inhibitory_neurons = true;
	// 	optimisation_stage_3_options->index_of_neuron_group_of_interest = 0;
	// 	optimisation_stage_3_options->ideal_output_score = upper;

	// 	optimiser->AddOptimisationStage(optimisation_stage_3_options, simulator_options);

	// }

	// optimiser->RunOptimisation();

	// four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L, 1, 3);
	// four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L, 1, 3);
	// four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L, 1, 3);

	// if (number_of_optimisation_stages > 4) {

	// 	Optimiser_Options * optimisation_stage_4_options = new Optimiser_Options();
	// 	optimisation_stage_4_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1];
	// 	optimisation_stage_4_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
	// 	optimisation_stage_4_options->use_inhibitory_neurons = true;
	// 	optimisation_stage_4_options->number_of_non_input_layers_to_simulate = 2;
	// 	optimisation_stage_4_options->index_of_neuron_group_of_interest = 2;
	// 	optimisation_stage_4_options->ideal_output_score = upper;

	// 	optimiser->AddOptimisationStage(optimisation_stage_4_options, simulator_options);

	// }

	// if (number_of_optimisation_stages > 5) {

	// 	Optimiser_Options * optimisation_stage_5_options = new Optimiser_Options();
	// 	optimisation_stage_5_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[2];
	// 	optimisation_stage_5_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
	// 	optimisation_stage_5_options->use_inhibitory_neurons = true;
	// 	optimisation_stage_5_options->number_of_non_input_layers_to_simulate = 3;
	// 	optimisation_stage_5_options->index_of_neuron_group_of_interest = 4;
	// 	optimisation_stage_5_options->ideal_output_score = upper;

	// 	optimiser->AddOptimisationStage(optimisation_stage_5_options, simulator_options);

	// }

	// if (number_of_optimisation_stages > 6) {

	// 	Optimiser_Options * optimisation_stage_6_options = new Optimiser_Options();
	// 	optimisation_stage_6_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[3];
	// 	optimisation_stage_6_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
	// 	optimisation_stage_6_options->use_inhibitory_neurons = true;
	// 	optimisation_stage_6_options->number_of_non_input_layers_to_simulate = 4;
	// 	optimisation_stage_6_options->index_of_neuron_group_of_interest = 6;
	// 	optimisation_stage_6_options->ideal_output_score = upper;

	// 	optimiser->AddOptimisationStage(optimisation_stage_6_options, simulator_options);

	// }

	// // four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF, 2, 3);

	// optimiser->RunOptimisation(4);

	// print_line_of_dashes_with_blank_lines_either_side();

	// // FINALISE MODEL + COPY TO DEVICE
	// four_layer_vision_spiking_model->number_of_non_input_layers_to_simulate = 4;
	// four_layer_vision_spiking_model->finalise_model();
	// four_layer_vision_spiking_model->copy_model_to_device();

	// // CREATE SIMULATOR
	// Simulator * simulator = new Simulator(four_layer_vision_spiking_model, simulator_options);

	// // RUN SIMULATION
	// SpikeAnalyser * spike_analyser = new SpikeAnalyser(four_layer_vision_spiking_model->spiking_neurons, four_layer_vision_spiking_model->input_spiking_neurons);
	// simulator->RunSimulation(spike_analyser);

	// // CALCULATE AVERAGES + OPTIMISATION OUTPUT SCORE
	// spike_analyser->calculate_various_neuron_spike_totals_and_averages(simulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch);

	/////////// END OF EXPERIMENT ///////////
	experiment_timer->stop_timer_and_log_time_and_message("Experiment Completed.", true);

	cudaProfilerStop();

	return 0;
}<commit_msg>Missed from last<commit_after>#include "../Optimiser/Optimiser.h"

#include "../Simulator/Simulator.h"
#include "../Models/FourLayerVisionSpikingModel.h"

#include "../SpikeAnalyser/SpikeAnalyser.h"
#include "../Helpers/TimerWithMessages.h"
#include "../Helpers/TerminalHelpers.h"
#include "../Helpers/MemoryUsage.h"

#include "cuda_profiler_api.h"

// Use the following line to compile the binary
// make FILE='OptimiseFourLayerVisionSpikingModelFiringRates' EXPERIMENT_DIRECTORY='Experiments'  model -j22

// The function which will autorun when the executable is created
int main (int argc, char *argv[]){

	TimerWithMessages * experiment_timer = new TimerWithMessages("\n");

	// // Parameters for OPTIMISATION + Information Analysis
	// const float optimal_max_firing_rate = 100.0f;//set if optimizing based on maxfr //Maximum rate (spikes/sec) 87 +- 46  (*1)
	// //*1 Bair, W., & Movshon, J. A. (2004).  Adaptive Temporal Integration of Motion in Direction-Selective Neurons in Macaque Visual Cortex. The Journal of Neuroscience, 24(33), 7305遯ｶ�ｿｽ7323.
	// int number_of_bins = 5;
	// bool useThresholdForMaxFR = true;
	// float max_firing_rate = optimal_max_firing_rate*presentation_time_per_stimulus_per_epoch_test;

	const float presentation_time_per_stimulus_per_epoch = 0.3;

	// SIMULATOR OPTIONS
	Simulator_Options * simulator_options = new Simulator_Options();

	simulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch = presentation_time_per_stimulus_per_epoch;
	simulator_options->run_simulation_general_options->number_of_epochs = 1;
	simulator_options->run_simulation_general_options->apply_stdp_to_relevant_synapses = false;
	simulator_options->run_simulation_general_options->stimulus_presentation_order_seed = 1;

	simulator_options->recording_electrodes_options->count_neuron_spikes_recording_electrodes_bool = true;

	simulator_options->stimuli_presentation_options->presentation_format = PRESENTATION_FORMAT_OBJECT_BY_OBJECT_RESET_BETWEEN_STIMULI;
	simulator_options->stimuli_presentation_options->object_order = OBJECT_ORDER_ORIGINAL;
	simulator_options->stimuli_presentation_options->transform_order = TRANSFORM_ORDER_ORIGINAL;

	// MODEL
	FourLayerVisionSpikingModel * four_layer_vision_spiking_model = new FourLayerVisionSpikingModel();
	four_layer_vision_spiking_model->SetTimestep(0.00002);
	four_layer_vision_spiking_model->high_fidelity_spike_storage = true;
	four_layer_vision_spiking_model->inputs_directory = "MatlabGaborFilter/Inputs_1T_FR_OPT/";

	// OPTIMISATION
	float upper = 150.0;
	float lower = 100.0;
	int number_of_optimisation_stages = 7;

	Optimiser* optimiser = new Optimiser(four_layer_vision_spiking_model);

	if (number_of_optimisation_stages > 0) {

		Optimiser_Options * optimisation_stage_0_options = new Optimiser_Options();
		optimisation_stage_0_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0];
		optimisation_stage_0_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
		optimisation_stage_0_options->ideal_output_score = upper;
		optimisation_stage_0_options->score_to_use = SCORE_TO_USE_average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons;

		optimiser->AddOptimisationStage(optimisation_stage_0_options, simulator_options);

	}

	// printf("optimiser->spike_analyser_from_last_optimisation_stage->average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons[index_of_neuron_group_of_interest_for_each_optimisation_stage[optimisation_stage]]\n");

	optimiser->RunOptimisation();

	// float temp = (int)optimiser->spike_analyser_from_last_optimisation_stage->running_count_of_non_silent_neurons_per_neuron_group[0];
	// printf("optimiser->spike_analyser_from_last_optimisation_stage->running_count_of_non_silent_neurons_per_neuron_group[0]: %f\n", temp);

	float temp = optimiser->spike_analyser_from_last_optimisation_stage->average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons[0];

	if (number_of_optimisation_stages > 1) {

		Optimiser_Options * optimisation_stage_1_options = new Optimiser_Options();
		optimisation_stage_1_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0];
		optimisation_stage_1_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2I_L_SYNAPSES_ON;
		optimisation_stage_1_options->use_inhibitory_neurons = true;
		optimisation_stage_1_options->index_of_neuron_group_of_interest = 1;
		optimisation_stage_1_options->ideal_output_score = upper;
		optimisation_stage_1_options->score_to_use = SCORE_TO_USE_average_number_of_spikes_per_neuron_group_per_second_excluding_silent_neurons;

		optimiser->AddOptimisationStage(optimisation_stage_1_options, simulator_options);

	}

	if (number_of_optimisation_stages > 2) {

		Optimiser_Options * optimisation_stage_2_options = new Optimiser_Options();
		optimisation_stage_2_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0];
		optimisation_stage_2_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->I2E_L_SYNAPSES_ON;
		optimisation_stage_2_options->use_inhibitory_neurons = true;
		optimisation_stage_2_options->index_of_neuron_group_of_interest = 0;
		optimisation_stage_2_options->ideal_output_score = 0.8*temp;
		optimisation_stage_2_options->positive_effect_of_postive_change_in_parameter = true;
		// optimisation_stage_2_options->score_to_use = SCORE_TO_USE_running_count_of_non_silent_neurons_per_neuron_group;
		// optimisation_stage_2_options->optimisation_minimum_error = 10.0;

		optimiser->AddOptimisationStage(optimisation_stage_2_options, simulator_options);

	}

	optimiser->RunOptimisation(1);

	if (number_of_optimisation_stages > 3) {

		Optimiser_Options * optimisation_stage_3_options = new Optimiser_Options();
		optimisation_stage_3_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0];
		optimisation_stage_3_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_L_SYNAPSES_ON;
		optimisation_stage_3_options->use_inhibitory_neurons = true;
		optimisation_stage_3_options->index_of_neuron_group_of_interest = 0;
		optimisation_stage_3_options->ideal_output_score = upper;

		optimiser->AddOptimisationStage(optimisation_stage_3_options, simulator_options);

	}

	optimiser->RunOptimisation();

	four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L, 1, 3);
	four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L, 1, 3);
	four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L, 1, 3);

	if (number_of_optimisation_stages > 4) {

		Optimiser_Options * optimisation_stage_4_options = new Optimiser_Options();
		optimisation_stage_4_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1];
		optimisation_stage_4_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
		optimisation_stage_4_options->use_inhibitory_neurons = true;
		optimisation_stage_4_options->number_of_non_input_layers_to_simulate = 2;
		optimisation_stage_4_options->index_of_neuron_group_of_interest = 2;
		optimisation_stage_4_options->ideal_output_score = upper;

		optimiser->AddOptimisationStage(optimisation_stage_4_options, simulator_options);

	}

	if (number_of_optimisation_stages > 5) {

		Optimiser_Options * optimisation_stage_5_options = new Optimiser_Options();
		optimisation_stage_5_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[2];
		optimisation_stage_5_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
		optimisation_stage_5_options->use_inhibitory_neurons = true;
		optimisation_stage_5_options->number_of_non_input_layers_to_simulate = 3;
		optimisation_stage_5_options->index_of_neuron_group_of_interest = 4;
		optimisation_stage_5_options->ideal_output_score = upper;

		optimiser->AddOptimisationStage(optimisation_stage_5_options, simulator_options);

	}

	if (number_of_optimisation_stages > 6) {

		Optimiser_Options * optimisation_stage_6_options = new Optimiser_Options();
		optimisation_stage_6_options->model_pointer_to_be_optimised = &four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[3];
		optimisation_stage_6_options->synapse_bool_pointer_to_turn_on = &four_layer_vision_spiking_model->E2E_FF_SYNAPSES_ON;
		optimisation_stage_6_options->use_inhibitory_neurons = true;
		optimisation_stage_6_options->number_of_non_input_layers_to_simulate = 4;
		optimisation_stage_6_options->index_of_neuron_group_of_interest = 6;
		optimisation_stage_6_options->ideal_output_score = upper;

		optimiser->AddOptimisationStage(optimisation_stage_6_options, simulator_options);

	}

	// four_layer_vision_spiking_model->set_LBL_values_for_pointer_from_layer_to_layer(four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1], four_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF, 2, 3);

	optimiser->RunOptimisation(4);

	print_line_of_dashes_with_blank_lines_either_side();

	// FINALISE MODEL + COPY TO DEVICE
	four_layer_vision_spiking_model->number_of_non_input_layers_to_simulate = 4;
	four_layer_vision_spiking_model->finalise_model();
	four_layer_vision_spiking_model->copy_model_to_device();

	// CREATE SIMULATOR
	Simulator * simulator = new Simulator(four_layer_vision_spiking_model, simulator_options);

	// RUN SIMULATION
	SpikeAnalyser * spike_analyser = new SpikeAnalyser(four_layer_vision_spiking_model->spiking_neurons, four_layer_vision_spiking_model->input_spiking_neurons);
	simulator->RunSimulation(spike_analyser);

	// CALCULATE AVERAGES + OPTIMISATION OUTPUT SCORE
	spike_analyser->calculate_various_neuron_spike_totals_and_averages(simulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch);

	/////////// END OF EXPERIMENT ///////////
	experiment_timer->stop_timer_and_log_time_and_message("Experiment Completed.", true);

	cudaProfilerStop();

	return 0;
}<|endoftext|>


<commit_before>28ea7e6e-2748-11e6-8090-e0f84713e7b8<commit_msg>ashley broke it<commit_after>28f4e5dc-2748-11e6-83d6-e0f84713e7b8<|endoftext|>


<commit_before><commit_msg> ChangeLabel was not fully implemented on alphanumeric labels. (#7294)<commit_after><|endoftext|>


<commit_before>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the Campcaster project.
    http://campcaster.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

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

    Campcaster is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Campcaster; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Author   : $Author$
    Version  : $Revision$
    Location : $URL$

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#if HAVE_UNISTD_H
#include <unistd.h>
#else
#error "Need unistd.h"
#endif

#include <string>
#include <iostream>

#include "LiveSupport/Core/TimeConversion.h"

#include "GstreamerPlayer.h"
#include "TestEventListener.h"
#include "TwoGstreamerPlayersTest.h"

using namespace LiveSupport::PlaylistExecutor;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

CPPUNIT_TEST_SUITE_REGISTRATION(TwoGstreamerPlayersTest);

/**
 *  The name of the configuration file for the audio player.
 */
static const std::string configFileName = "etc/twoGstreamerPlayers.xml";

/**
 *  The name of the root XML element in the configuration file.
 */
static const std::string rootElementName = "twoGstreamerPlayers";

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Set up the test environment
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: setUp(void)                         throw ()
{
    try {
        Ptr<xmlpp::DomParser>::Ref  parser(
                                    new xmlpp::DomParser(configFileName, true));
        const xmlpp::Document * document = parser->get_document();
        const xmlpp::Element  * root     = document->get_root_node();

        xmlpp::Node::NodeList       children;
        const xmlpp::Element      * element;

        children = root->get_children(GstreamerPlayer::getConfigElementName());

        element = dynamic_cast<const xmlpp::Element*> (*(children.begin()));
        player1.reset(new GstreamerPlayer());
        player1->configure(*element);

        children.pop_front();
        element = dynamic_cast<const xmlpp::Element*> (*(children.begin()));
        player2.reset(new GstreamerPlayer());
        player2->configure(*element);

    } catch (std::invalid_argument &e) {
        std::cerr << "semantic error in configuration file" << std::endl;
    } catch (xmlpp::exception &e) {
        std::cerr << e.what() << std::endl;
    }
}

/*------------------------------------------------------------------------------
 *  Clean up the test environment
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: tearDown(void)                      throw ()
{
    player2.reset();
    player1.reset();
}

/*------------------------------------------------------------------------------
 *  Test to see if the GstreamerPlayer engine can be started and stopped
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: firstTest(void)
                                                throw (CPPUNIT_NS::Exception)
{
    try {
        player1->initialize();
        player2->initialize();
        CPPUNIT_ASSERT(!player1->isPlaying());
        CPPUNIT_ASSERT(!player2->isPlaying());
        player2->deInitialize();
        player1->deInitialize();
    } catch (std::exception &e) {
        CPPUNIT_FAIL("failed to initialize or de-initialize GstreamerPlayer");
    }
}

/*------------------------------------------------------------------------------
 *  Play something simple on player #1
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: simplePlay1Test(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player1->initialize();
    try {
        player1->open("file:var/test10001.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->start();
    CPPUNIT_ASSERT(player1->isPlaying());
    while (player1->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->close();
    player1->deInitialize();
}

/*------------------------------------------------------------------------------
 *  Play something simple on player #2
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: simplePlay2Test(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player2->initialize();
    try {
        player2->open("file:var/test.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->start();
    CPPUNIT_ASSERT(player2->isPlaying());
    while (player2->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->close();
    player2->deInitialize();
}

/*------------------------------------------------------------------------------
 *  Play something simple on both players
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: playBothTest(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player1->initialize();
    player2->initialize();

    // start playing on player1
    try {
        player1->open("file:var/test10001.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->start();
    CPPUNIT_ASSERT(player1->isPlaying());

    // sleep some time
    for (unsigned i = 0; i < 100; ++i) {
        TimeConversion::sleep(sleepT);
    }

    // start playing on player2
    try {
        player2->open("file:var/test.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->start();
    CPPUNIT_ASSERT(player2->isPlaying());

    // wait for both players to finish
    while (player1->isPlaying() || player2->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    CPPUNIT_ASSERT(!player2->isPlaying());

    player2->close();
    player1->close();
    player2->deInitialize();
    player1->deInitialize();
}

<commit_msg>Fixing ticket #2291 - part 5, playlistExcutor unit test back in business<commit_after>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the Campcaster project.
    http://campcaster.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

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

    Campcaster is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Campcaster; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Author   : $Author$
    Version  : $Revision$
    Location : $URL$

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#if HAVE_UNISTD_H
#include <unistd.h>
#else
#error "Need unistd.h"
#endif

#include <string>
#include <iostream>

#include "LiveSupport/Core/TimeConversion.h"

#include "GstreamerPlayer.h"
#include "TestEventListener.h"
#include "TwoGstreamerPlayersTest.h"

using namespace LiveSupport::PlaylistExecutor;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

CPPUNIT_TEST_SUITE_REGISTRATION(TwoGstreamerPlayersTest);

/**
 *  The name of the configuration file for the audio player.
 */
static const std::string configFileName = "etc/twoGstreamerPlayers.xml";

/**
 *  The name of the root XML element in the configuration file.
 */
static const std::string rootElementName = "twoGstreamerPlayers";

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Set up the test environment
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: setUp(void)                         throw ()
{
    try {
        Ptr<xmlpp::DomParser>::Ref  parser(
                                    new xmlpp::DomParser(configFileName, true));
        const xmlpp::Document * document = parser->get_document();
        const xmlpp::Element  * root     = document->get_root_node();

        xmlpp::Node::NodeList       children;
        const xmlpp::Element      * element;

        children = root->get_children(GstreamerPlayer::getConfigElementName());

        element = dynamic_cast<const xmlpp::Element*> (*(children.begin()));
        player1.reset(new GstreamerPlayer());
        player1->configure(*element);

        children.pop_front();
        element = dynamic_cast<const xmlpp::Element*> (*(children.begin()));
        player2.reset(new GstreamerPlayer());
        player2->configure(*element);

    } catch (std::invalid_argument &e) {
        std::cerr << "semantic error in configuration file" << std::endl;
    } catch (xmlpp::exception &e) {
        std::cerr << e.what() << std::endl;
    }
}

/*------------------------------------------------------------------------------
 *  Clean up the test environment
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: tearDown(void)                      throw ()
{
    player2.reset();
    player1.reset();
}

/*------------------------------------------------------------------------------
 *  Test to see if the GstreamerPlayer engine can be started and stopped
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: firstTest(void)
                                                throw (CPPUNIT_NS::Exception)
{
    try {
        player1->initialize();
        player2->initialize();
        CPPUNIT_ASSERT(!player1->isPlaying());
        CPPUNIT_ASSERT(!player2->isPlaying());
        player2->deInitialize();
        player1->deInitialize();
    } catch (std::exception &e) {
        CPPUNIT_FAIL("failed to initialize or de-initialize GstreamerPlayer");
    }
}

/*------------------------------------------------------------------------------
 *  Play something simple on player #1
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: simplePlay1Test(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player1->initialize();
    try {
        player1->open("file:///tmp/campcaster/test10001.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->start();
    CPPUNIT_ASSERT(player1->isPlaying());
    while (player1->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->close();
    player1->deInitialize();
}

/*------------------------------------------------------------------------------
 *  Play something simple on player #2
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: simplePlay2Test(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player2->initialize();
    try {
        player2->open("file:///tmp/campcaster/test.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->start();
    CPPUNIT_ASSERT(player2->isPlaying());
    while (player2->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->close();
    player2->deInitialize();
}

/*------------------------------------------------------------------------------
 *  Play something simple on both players
 *----------------------------------------------------------------------------*/
void
TwoGstreamerPlayersTest :: playBothTest(void)
                                                throw (CPPUNIT_NS::Exception)
{
    Ptr<time_duration>::Ref     sleepT(new time_duration(microseconds(10)));

    player1->initialize();
    player2->initialize();

    // start playing on player1
    try {
        player1->open("file:///tmp/campcaster/test10001.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    player1->start();
    CPPUNIT_ASSERT(player1->isPlaying());

    // sleep some time
    for (unsigned i = 0; i < 100; ++i) {
        TimeConversion::sleep(sleepT);
    }

    // start playing on player2
    try {
        player2->open("file:///tmp/campcaster/test.mp3");
    } catch (std::invalid_argument &e) {
        CPPUNIT_FAIL(e.what());
    }
    CPPUNIT_ASSERT(!player2->isPlaying());
    player2->start();
    CPPUNIT_ASSERT(player2->isPlaying());

    // wait for both players to finish
    while (player1->isPlaying() || player2->isPlaying()) {
        TimeConversion::sleep(sleepT);
    }
    CPPUNIT_ASSERT(!player1->isPlaying());
    CPPUNIT_ASSERT(!player2->isPlaying());

    player2->close();
    player1->close();
    player2->deInitialize();
    player1->deInitialize();
}

<|endoftext|>


<commit_before>#include <iostream>

//proper sdl header inclusion as per documentation
#include <SDL.h>

using namespace std;

int main() {

    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "failed" << endl;
        return 1;
    }

    SDL_Window *window = SDL_CreateWindow("Cider Fire",
                                          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
                                          SDL_WINDOW_SHOWN);

    if (window == NULL) {
        cout << SDL_GetError() << endl;
        SDL_Quit();
        return 2;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
                                             SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

    if (renderer == NULL) {
        cout << "could not create rendered" << endl;
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 3;
    }

    if (texture == NULL) {
        cout << "could not create texture" << endl;
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 4;
    }

    //RGBA 8888 = 32

    Uint32 *buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

    memset(buffer, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));

    buffer[30000] = 0x0080FFFF;

    for (int i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i++) {
        buffer[i] = 0xFFFFFFFF;
    }

    SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    bool quit = false;

    SDL_Event event;

    while (!quit) {
//        Update particles
//        Draw particles
//        Check for messages or events

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }
    }

    delete[] buffer;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<commit_msg>Commented dual implementation of gradient switch<commit_after>#include <iostream>

//proper sdl header inclusion as per documentation
#include <SDL.h>

using namespace std;

int main() {

    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "failed" << endl;
        return 1;
    }

    SDL_Window *window = SDL_CreateWindow("Cider Fire",
                                          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
                                          SDL_WINDOW_SHOWN);

    if (window == NULL) {
        cout << SDL_GetError() << endl;
        SDL_Quit();
        return 2;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
                                             SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

    if (renderer == NULL) {
        cout << "could not create rendered" << endl;
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 3;
    }

    if (texture == NULL) {
        cout << "could not create texture" << endl;
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 4;
    }

    //RGBA 8888 = 32

    Uint32 *buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

    memset(buffer, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));

    buffer[30000] = 0x0080FFFF;

    // Same as memset

    for (int i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i++) {
        buffer[i] = 0xFFFFFFFF;
    }

    SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    bool quit = false;

    SDL_Event event;

    while (!quit) {
//        Update particles
//        Draw particles
//        Check for messages or events

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }
    }

    delete[] buffer;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<|endoftext|>


<commit_before>c6512dd7-4b02-11e5-8651-28cfe9171a43<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>c65f281e-4b02-11e5-b7a0-28cfe9171a43<|endoftext|>


<commit_before>8e6e3f38-ad59-11e7-85fe-ac87a332f658<commit_msg>Long commit messages are not required<commit_after>8faadbe1-ad59-11e7-bf80-ac87a332f658<|endoftext|>


<commit_before>#include "dlx.h"
#include "partial_cross.h"
#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

vector<int> try_placement(int idx, int x, int y, int r, int rr);
typedef vector<vector<int > > tile;

int main(void) {
  // Get initial grid
  int num_cols = num_pieces + board_x * board_y;
  auto grid_pair = initialize(num_cols);
  header * root = grid_pair.first;
  vector<header *> grid = grid_pair.second;

  // Build the grid
  // First, properly set tile flags
  for(int i = 0; i < num_pieces; ++i){
    grid[i]->tile = true;
  }

  // Next, add rows for placements
  for(int i = 0; i < num_pieces; ++i) {
    for(int x = 0; x < board_x; ++x) {
      for(int y = 0; y < board_y; ++y) {
        for (int rotate = 0; rotate < 4; ++rotate) {
          for (int reflect = 0; reflect < 2; ++reflect) {
            //cout << i << " " << x << " " << y << " " << rotate << " " << reflect << endl;
            vector<int> covered = try_placement(i, x, y, rotate, reflect);
           /* auto covered_iter = covered.cbegin();
            node * prev_node = nullptr;
            for(int j = 0; j < num_cols; ++j) {
              node * row_node = new node();
              row_node->used = (j == i || j == *covered_iter);
              if(j == *covered_iter) ++covered_iter;
              row_node->
              grid[j]->insert(row_node);
            }*/
            bool first = true;
            node * prev = nullptr;
            for(int j = 0; j < covered.size(); ++j) {
              node * row_node = new node();
              if(first) {
                first = false;
              }
              else {
                row_node->left = prev;
                row_node->right = prev->right;
                prev->right->left = row_node;
                prev->right = row_node;
              }

              grid[covered[j]]->insert(row_node);
              prev = row_node;
            }
          }
        }
      }
    }
  }
  cout << "passed for loops" << endl;

  // Get count
  int count = 0;
  count_sols(root, count);

  // Output count
  cout << "Found " << count << " solutions!\n";
  return 0;
}

int ** make_matrix(int dim_x, int dim_y) {
  int** matrix = new int*[dim_y];
  for (int i = 0; i < dim_y; ++i) {
    matrix[i] = new int[dim_x];
    for (int j = 0; j < dim_x; ++j) {
      matrix[i][j] = 0;
    }
  }
  return matrix;
}

int ** get_tile(int idx) {
  tile orig_tile = pieces[idx];
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];

  int ** tile = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      tile[i][j] = orig_tile[i][j];
    }
  }
  return tile;
}

void cleanup(int ** tile, int dim_x, int dim_y) {
  for (int i = 0; i < dim_y; ++i) {
      delete [] tile[i];
  }
  delete [] tile;
}

/* Reflect across the x-axis. */
int ** reflect(int ** tile, int dim_x, int dim_y) {
  int ** reflected = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      reflected[dim_y - 1 - i][j] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return reflected;
}

int ** rotate(int ** tile, int dim_x, int dim_y) {
  int ** rotated = make_matrix(dim_y, dim_x);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      rotated[j][dim_y - 1 - i] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return rotated;
}

tuple<int **,tuple<int, int> > transform_tile(int idx, int _rotate, int _reflect) {
  int ** tile = get_tile(idx);
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];
  if (_reflect == 1) {
    tile = reflect(tile, dim_x, dim_y);
  }

  for (int r = 0; r < _rotate; r++) {
    tile = rotate(tile, dim_x, dim_y);
    int temp = dim_x;
    dim_x = dim_y;
    dim_y = temp;
  }

  tuple<int, int> dims = make_tuple(dim_x, dim_y);

  return make_tuple(tile, dims);
}

vector<int> try_placement(int idx, int x, int y, int rotate, int reflect) {
  // Try placing tile idx at (x, y)
  // If it's valid, return a vector of the parts of the board covered
  // If it isn't valid, return an empty vector
  auto tuple = transform_tile(idx, rotate, reflect);
  int ** tile = get<0>(tuple);
  auto dims = get<1>(tuple);
  int dim_x = get<0>(dims);
  int dim_y = get<1>(dims);

  vector<int> indices;
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      int board_i = i + y;
      int board_j = j + x;
      /* Fell off board. */
      if (board_i >= board_y || board_j >= board_x) {
        return vector<int>();
      }

      /* Mismatch. */
      if (board[board_i][board_j] != tile[i][j]) {
        return vector<int>();
      }

      /* Otherwise, we add the index. */
      indices.push_back(board_i + board_j * board_x);
    }
  }

  cleanup(tile, dim_x, dim_y);

  return indices;
}
<commit_msg>setting value, not that it matters<commit_after>#include "dlx.h"
#include "partial_cross.h"
#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

vector<int> try_placement(int idx, int x, int y, int r, int rr);
typedef vector<vector<int > > tile;

int main(void) {
  // Get initial grid
  int num_cols = num_pieces + board_x * board_y;
  auto grid_pair = initialize(num_cols);
  header * root = grid_pair.first;
  vector<header *> grid = grid_pair.second;

  // Build the grid
  // First, properly set tile flags
  for(int i = 0; i < num_pieces; ++i){
    grid[i]->tile = true;
  }

  // Next, add rows for placements
  for(int i = 0; i < num_pieces; ++i) {
    for(int x = 0; x < board_x; ++x) {
      for(int y = 0; y < board_y; ++y) {
        for (int rotate = 0; rotate < 4; ++rotate) {
          for (int reflect = 0; reflect < 2; ++reflect) {
            //cout << i << " " << x << " " << y << " " << rotate << " " << reflect << endl;
            vector<int> covered = try_placement(i, x, y, rotate, reflect);
           /* auto covered_iter = covered.cbegin();
            node * prev_node = nullptr;
            for(int j = 0; j < num_cols; ++j) {
              node * row_node = new node();
              row_node->used = (j == i || j == *covered_iter);
              if(j == *covered_iter) ++covered_iter;
              row_node->
              grid[j]->insert(row_node);
            }*/
            bool first = true;
            node * prev = nullptr;
            for(int j = 0; j < covered.size(); ++j) {
              node * row_node = new node();
              row_node->used = true;
              if(first) {
                first = false;
              }
              else {
                row_node->left = prev;
                row_node->right = prev->right;
                prev->right->left = row_node;
                prev->right = row_node;
              }

              grid[covered[j]]->insert(row_node);
              prev = row_node;
            }
          }
        }
      }
    }
  }
  cout << "passed for loops" << endl;

  // Get count
  int count = 0;
  count_sols(root, count);

  // Output count
  cout << "Found " << count << " solutions!\n";
  return 0;
}

int ** make_matrix(int dim_x, int dim_y) {
  int** matrix = new int*[dim_y];
  for (int i = 0; i < dim_y; ++i) {
    matrix[i] = new int[dim_x];
    for (int j = 0; j < dim_x; ++j) {
      matrix[i][j] = 0;
    }
  }
  return matrix;
}

int ** get_tile(int idx) {
  tile orig_tile = pieces[idx];
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];

  int ** tile = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      tile[i][j] = orig_tile[i][j];
    }
  }
  return tile;
}

void cleanup(int ** tile, int dim_x, int dim_y) {
  for (int i = 0; i < dim_y; ++i) {
      delete [] tile[i];
  }
  delete [] tile;
}

/* Reflect across the x-axis. */
int ** reflect(int ** tile, int dim_x, int dim_y) {
  int ** reflected = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      reflected[dim_y - 1 - i][j] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return reflected;
}

int ** rotate(int ** tile, int dim_x, int dim_y) {
  int ** rotated = make_matrix(dim_y, dim_x);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      rotated[j][dim_y - 1 - i] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return rotated;
}

tuple<int **,tuple<int, int> > transform_tile(int idx, int _rotate, int _reflect) {
  int ** tile = get_tile(idx);
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];
  if (_reflect == 1) {
    tile = reflect(tile, dim_x, dim_y);
  }

  for (int r = 0; r < _rotate; r++) {
    tile = rotate(tile, dim_x, dim_y);
    int temp = dim_x;
    dim_x = dim_y;
    dim_y = temp;
  }

  tuple<int, int> dims = make_tuple(dim_x, dim_y);

  return make_tuple(tile, dims);
}

vector<int> try_placement(int idx, int x, int y, int rotate, int reflect) {
  // Try placing tile idx at (x, y)
  // If it's valid, return a vector of the parts of the board covered
  // If it isn't valid, return an empty vector
  auto tuple = transform_tile(idx, rotate, reflect);
  int ** tile = get<0>(tuple);
  auto dims = get<1>(tuple);
  int dim_x = get<0>(dims);
  int dim_y = get<1>(dims);

  vector<int> indices;
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      int board_i = i + y;
      int board_j = j + x;
      /* Fell off board. */
      if (board_i >= board_y || board_j >= board_x) {
        return vector<int>();
      }

      /* Mismatch. */
      if (board[board_i][board_j] != tile[i][j]) {
        return vector<int>();
      }

      /* Otherwise, we add the index. */
      indices.push_back(board_i + board_j * board_x);
    }
  }

  cleanup(tile, dim_x, dim_y);

  return indices;
}
<|endoftext|>


<commit_before>0c25cf54-ad5d-11e7-a8e1-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>0caf2507-ad5d-11e7-8d06-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

static void showLogo() {
  cout << "\n"
          "---------------------------\n"
          "   /\\                      \n"
          "   \\/  Draupnir v0.0.1     \n"
          "   /\\                      \n"
          "---------------------------\n"
          "\n";
}

int main(int argc, char *argv[]) {
  showLogo();

  cout << "Arguments:" << endl;
  for (int i = 0; i < argc; i++) {
    cout << "  " << i << ": " << argv[i] << endl;
  }

  return 0;
}
<commit_msg>Add newline after arguments<commit_after>#include <iostream>

using namespace std;

static void showLogo() {
  cout << "\n"
          "---------------------------\n"
          "   /\\                      \n"
          "   \\/  Draupnir v0.0.1     \n"
          "   /\\                      \n"
          "---------------------------\n"
          "\n";
}

int main(int argc, char *argv[]) {
  showLogo();

  cout << "Arguments:" << endl;
  for (int i = 0; i < argc; i++) {
    cout << "  " << i << ": " << argv[i] << endl;
  }
  cout << endl;

  return 0;
}
<|endoftext|>


<commit_before>//
// Created by volundr on 7/19/16.
//

#include <iostream>
#include <iomanip>
#include "Bno055Interface.h"
#include "bno055DataSheet.h"

#define BNO055_DEVICE_FILE "/dev/ttyS0"

using namespace bno055;

int main() {
    Bno055Interface bno055;
    bno055.init(BNO055_DEVICE_FILE);
    if (bno055.isLive()) {
        std::cout << "BNO055 is live.\n";
    } else {
        std::cout << "Could not contact BNO055!\n";
        return 1;
    }

    Vec3_16 orient;
    Vec3_f orientDeg;
    while(bno055.queryVec3(&orient, EULER_ORIENT)) {
        orientDeg = orient.toFusionEulerOrientation();
        std::cout << "-> ";
        std::cout << std::setiosflags(std::ios::right);
        std::cout << std::setiosflags(std::ios::fixed);
        std::cout << std::setw(10) << std::setprecision(4) << orientDeg.heading
                  << std::setw(10) << std::setprecision(4) << orientDeg.roll
                  << std::setw(10) << std::setprecision(4) << orientDeg.pitch;
        std::cout << std::endl;
    }

    std::cout << "Data gathering halted, exiting!\n";

    return 0;
}

<commit_msg>added delay of 10 useconds to fix buffer over run<commit_after>//
// Created by volundr on 7/19/16.
//

#include <iostream>
#include <iomanip>
#include "Bno055Interface.h"
#include "bno055DataSheet.h"

#define BNO055_DEVICE_FILE "/dev/ttyS0"

using namespace bno055;

int main() {
    Bno055Interface bno055;
    bno055.init(BNO055_DEVICE_FILE);
    if (bno055.isLive()) {
        std::cout << "BNO055 is live.\n";
    } else {
        std::cout << "Could not contact BNO055!\n";
        return 1;
    }

    Vec3_16 orient;
    Vec3_f orientDeg;
    while(bno055.queryVec3(&orient, EULER_ORIENT)) {
        orientDeg = orient.toFusionEulerOrientation();
        std::cout << "-> ";
        std::cout << std::setiosflags(std::ios::right);
        std::cout << std::setiosflags(std::ios::fixed);
        std::cout << std::setw(10) << std::setprecision(4) << orientDeg.heading
                  << std::setw(10) << std::setprecision(4) << orientDeg.roll
                  << std::setw(10) << std::setprecision(4) << orientDeg.pitch;
        std::cout << std::endl;
        usleep(10);
    }

    std::cout << "Data gathering halted, exiting!\n";

    return 0;
}

<|endoftext|>