<commit_before>/*
 * Copyright (C) 2011
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
using std::string;
using std::ofstream;

#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;

#ifndef CL_DATA_HPP
#define CL_DATA_HPP

namespace isa {

namespace OpenCL {

template< typename T > class CLData {
public:
	CLData(string name, bool deletePolicy = false);
	~CLData();

	inline string getName() const;

	// Allocation of host data
	void allocateHostData(T * data, size_t size);
	void allocateHostData(long long unsigned int nrElements);
	void deleteHostData();

	// Allocation of device data
	void allocateDeviceData(cl::Buffer * data, size_t size);
	void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
	void allocateDeviceData() throw (OpenCLError);
	void deleteDeviceData();
	inline void setDeviceReadOnly();
	inline void setDeviceWriteOnly();

	// Memory transfers
	void copyHostToDevice(bool async = false) throw (OpenCLError);
	void copyDeviceToHost(bool async = false) throw (OpenCLError);
	void dumpDeviceToDisk() throw (OpenCLError);

	// OpenCL
	inline void setCLContext(cl::Context * context);
	inline void setCLQueue(cl::CommandQueue * queue);

	// Access host data
	inline T * getHostData();
	inline T * getHostDataAt(long long unsigned int startingPoint);
	inline void * getRawHostData();
	inline void * getRawHostDataAt(long long unsigned int startingPoint);
	inline size_t getHostDataSize() const;
	inline T operator[](long long unsigned int item);

	// Access device data
	inline cl::Buffer * getDeviceData();
	inline size_t getDeviceDataSize() const;

	// Timers
	inline Timer & getH2DTimer();
	inline Timer & getD2HTimer();

private:
	cl::Context * clContext;
	cl::CommandQueue * clQueue;
	Timer timerH2D;
	Timer timerD2H;

	bool deleteHost;
	bool deviceReadOnly;
	bool deviceWriteOnly;
	T * hostData;
	size_t hostDataSize;
	cl::Buffer * deviceData;
	size_t deviceDataSize;

	string name;
};

// Implementations

template< typename T > CLData< T >::CLData(string name, bool deletePolicy, bool devRO) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(0), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}

template< typename T > CLData< T >::~CLData() {
	deleteHostData();
	deleteDeviceData();
}

template< typename T > void CLData< T >::allocateHostData(T * data, size_t size) {
	deleteHostData();

	hostData = data;
	hostDataSize = size;
}

template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
	size_t newSize = nrElements * sizeof(T);

	if ( newSize != hostDataSize ) {
		deleteHostData();

		hostData = new T [nrElements];
		hostDataSize = newSize;
	}
	memset(getRawHostData(), 0, newSize);
}

template< typename T > void CLData< T >::deleteHostData() {
	if ( deleteHost && hostDataSize != 0 ) {
		delete [] hostData;
		hostData = 0;
		hostDataSize = 0;
	}
}

template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
	deleteDeviceData();

	deviceData = data;
	deviceDataSize = size;
}

template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
	size_t newSize = nrElements * sizeof(T);
	if ( newSize != deviceDataSize ) {
		deleteDeviceData();

		try {
			if ( deviceReadOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
			} else if ( deviceWriteOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
			} else {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
			}
		} catch ( cl::Error err ) {
			deviceDataSize = 0;
			throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
		}
		deviceDataSize = newSize;
	}
}

template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::deleteDeviceData() {
	if ( deviceDataSize != 0 ) {
		delete deviceData;
		deviceData = 0;
		deviceDataSize = 0;
	}
}

template< typename T > inline void CLData< T >::setDeviceReadOnly() {
	deviceReadOnly = true;
	deviceWriteOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
	deviceWriteOnly = true;
	deviceReadOnly = false;
}

template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerH2D.start();
			clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerH2D.stop();
		} catch ( cl::Error err ) {
			timerH2D.reset();
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
}

template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerD2H.start();
			clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerD2H.stop();
		} catch ( cl::Error err ) {
			timerD2H.reset();
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}

}

template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
	CLData< T > temp = CLData< T >("temp", true);

	temp.setCLContext(clContext);
	temp.setCLQueue(clQueue);
	temp.allocateHostData(hostDataSize / sizeof(T));
	temp.allocateDeviceData(deviceData, deviceDataSize);
	temp.copyDeviceToHost();

	ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
	oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
	oFile.close();
}

template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
	clContext = context;
}

template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
	clQueue = queue;
}

template< typename T > inline T * CLData< T >::getHostData() {
	return hostData;
}

template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
	return &(hostData[startingPoint]);
}

template< typename T > inline void * CLData< T >::getRawHostData() {
	return reinterpret_cast< void * >(hostData);
}

template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
	return reinterpret_cast< void * >(&(hostData[startingPoint]));
}

template< typename T > inline size_t CLData< T >::getHostDataSize() const {
	return hostDataSize;
}

template< typename T > inline T CLData< T >::operator[](long long unsigned int item) {
	return hostData[item];
}

template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
	return deviceData;
}

template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
	return deviceDataSize;
}

template< typename T > inline string CLData< T >::getName() const {
	return name;
}

template< typename T > inline Timer & CLData< T >::getH2DTimer() {
	return timerH2D;
}

template< typename T > inline Timer & CLData< T >::getD2HTimer() {
	return timerD2H;
}

} // OpenCL
} // isa

#endif // CL_DATA_HPP
<commit_msg>Added an allocateSharedDeviceData() to avoid memory copying. Not tested it yet.<commit_after>/*
 * Copyright (C) 2011
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
using std::string;
using std::ofstream;

#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;

#ifndef CL_DATA_HPP
#define CL_DATA_HPP

namespace isa {

namespace OpenCL {

template< typename T > class CLData {
public:
	CLData(string name, bool deletePolicy = false);
	~CLData();

	inline string getName() const;

	// Allocation of host data
	void allocateHostData(T * data, size_t size);
	void allocateHostData(long long unsigned int nrElements);
	void deleteHostData();

	// Allocation of device data
	void allocateDeviceData(cl::Buffer * data, size_t size);
	void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
	void allocateDeviceData() throw (OpenCLError);
	void allocateSharedeDeviceData() throw (OpenCLError);
	void deleteDeviceData();
	inline void setDeviceReadOnly();
	inline void setDeviceWriteOnly();

	// Memory transfers
	void copyHostToDevice(bool async = false) throw (OpenCLError);
	void copyDeviceToHost(bool async = false) throw (OpenCLError);
	void dumpDeviceToDisk() throw (OpenCLError);

	// OpenCL
	inline void setCLContext(cl::Context * context);
	inline void setCLQueue(cl::CommandQueue * queue);

	// Access host data
	inline T * getHostData();
	inline T * getHostDataAt(long long unsigned int startingPoint);
	inline void * getRawHostData();
	inline void * getRawHostDataAt(long long unsigned int startingPoint);
	inline size_t getHostDataSize() const;
	inline T operator[](long long unsigned int item);

	// Access device data
	inline cl::Buffer * getDeviceData();
	inline size_t getDeviceDataSize() const;

	// Timers
	inline Timer & getH2DTimer();
	inline Timer & getD2HTimer();

private:
	cl::Context * clContext;
	cl::CommandQueue * clQueue;
	Timer timerH2D;
	Timer timerD2H;

	bool deleteHost;
	bool deviceReadOnly;
	bool deviceWriteOnly;
	T * hostData;
	size_t hostDataSize;
	cl::Buffer * deviceData;
	size_t deviceDataSize;

	string name;
};

// Implementations

template< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(0), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}

template< typename T > CLData< T >::~CLData() {
	deleteHostData();
	deleteDeviceData();
}

template< typename T > void CLData< T >::allocateHostData(T * data, size_t size) {
	deleteHostData();

	hostData = data;
	hostDataSize = size;
}

template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
	size_t newSize = nrElements * sizeof(T);

	if ( newSize != hostDataSize ) {
		deleteHostData();

		hostData = new T [nrElements];
		hostDataSize = newSize;
	}
	memset(getRawHostData(), 0, newSize);
}

template< typename T > void CLData< T >::deleteHostData() {
	if ( deleteHost && hostDataSize != 0 ) {
		delete [] hostData;
		hostData = 0;
		hostDataSize = 0;
	}
}

template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
	deleteDeviceData();

	deviceData = data;
	deviceDataSize = size;
}

template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
	size_t newSize = nrElements * sizeof(T);
	if ( newSize != deviceDataSize ) {
		deleteDeviceData();

		try {
			if ( deviceReadOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
			} else if ( deviceWriteOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
			} else {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
			}
		} catch ( cl::Error err ) {
			deviceDataSize = 0;
			throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
		}
		deviceDataSize = newSize;
	}
}

template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::deleteDeviceData() {
	if ( deviceDataSize != 0 ) {
		delete deviceData;
		deviceData = 0;
		deviceDataSize = 0;
	}
}

template< typename T > inline void CLData< T >::setDeviceReadOnly() {
	deviceReadOnly = true;
	deviceWriteOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
	deviceWriteOnly = true;
	deviceReadOnly = false;
}

template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerH2D.start();
			clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerH2D.stop();
		} catch ( cl::Error err ) {
			timerH2D.reset();
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
}

template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerD2H.start();
			clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerD2H.stop();
		} catch ( cl::Error err ) {
			timerD2H.reset();
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}

}

template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
	CLData< T > temp = CLData< T >("temp", true);

	temp.setCLContext(clContext);
	temp.setCLQueue(clQueue);
	temp.allocateHostData(hostDataSize / sizeof(T));
	temp.allocateDeviceData(deviceData, deviceDataSize);
	temp.copyDeviceToHost();

	ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
	oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
	oFile.close();
}

template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
	clContext = context;
}

template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
	clQueue = queue;
}

template< typename T > inline T * CLData< T >::getHostData() {
	return hostData;
}

template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
	return &(hostData[startingPoint]);
}

template< typename T > inline void * CLData< T >::getRawHostData() {
	return reinterpret_cast< void * >(hostData);
}

template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
	return reinterpret_cast< void * >(&(hostData[startingPoint]));
}

template< typename T > inline size_t CLData< T >::getHostDataSize() const {
	return hostDataSize;
}

template< typename T > inline T CLData< T >::operator[](long long unsigned int item) {
	return hostData[item];
}

template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
	return deviceData;
}

template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
	return deviceDataSize;
}

template< typename T > inline string CLData< T >::getName() const {
	return name;
}

template< typename T > inline Timer & CLData< T >::getH2DTimer() {
	return timerH2D;
}

template< typename T > inline Timer & CLData< T >::getD2HTimer() {
	return timerD2H;
}

} // OpenCL
} // isa

#endif // CL_DATA_HPP
<|endoftext|>


<commit_before>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#include "arrfunc_functions.hpp"
#include "array_functions.hpp"
#include "array_from_py.hpp"
#include "array_assign_from_py.hpp"
#include "type_functions.hpp"
#include "utility_functions.hpp"
#include "numpy_interop.hpp"
#include "arrfunc_from_pyfunc.hpp"

#include <dynd/types/string_type.hpp>
#include <dynd/types/base_dim_type.hpp>
#include <dynd/memblock/external_memory_block.hpp>
#include <dynd/array_range.hpp>
#include <dynd/type_promotion.hpp>
#include <dynd/types/base_struct_type.hpp>
#include <dynd/types/base_bytes_type.hpp>
#include <dynd/types/struct_type.hpp>
#include <dynd/func/rolling_arrfunc.hpp>
#include <dynd/view.hpp>
#include <dynd/func/callable.hpp>
#include <dynd/func/arrfunc_registry.hpp>

using namespace std;
using namespace dynd;
using namespace pydynd;

PyTypeObject *pydynd::WArrFunc_Type;

void pydynd::init_w_arrfunc_typeobject(PyObject *type)
{
  WArrFunc_Type = (PyTypeObject *)type;
}

PyObject *pydynd::arrfunc_call(PyObject *af_obj, PyObject *args_obj,
                               PyObject *ectx_obj)
{
  if (!WArrFunc_Check(af_obj)) {
    PyErr_SetString(PyExc_TypeError, "arrfunc_call expected an nd.arrfunc");
    return NULL;
  }
  const nd::arrfunc &af = ((WArrFunc *)af_obj)->v;
  if (af.is_null()) {
    PyErr_SetString(PyExc_ValueError, "cannot call a null nd.arrfunc");
    return NULL;
  }
  if (!PyTuple_Check(args_obj)) {
    PyErr_SetString(PyExc_ValueError,
                    "arrfunc_call requires a tuple of arguments");
    return NULL;
  }
  const eval::eval_context *ectx = eval_context_from_pyobj(ectx_obj);
  // Convert args into nd::arrays
  intptr_t args_size = PyTuple_Size(args_obj);
  std::vector<nd::array> args(args_size);
  for (intptr_t i = 0; i < args_size; ++i) {
    args[i] = array_from_py(PyTuple_GET_ITEM(args_obj, i), 0, false, ectx);
  }

  nd::array result = af.call(args_size, args_size ? &args[0] : NULL, ectx);
  return wrap_array(result);
}

PyObject *pydynd::arrfunc_rolling_apply(PyObject *func_obj, PyObject *arr_obj,
                                        PyObject *window_size_obj,
                                        PyObject *ectx_obj)
{
  const eval::eval_context *ectx = eval_context_from_pyobj(ectx_obj);
  nd::array arr = array_from_py(arr_obj, 0, false, ectx);
  intptr_t window_size = pyobject_as_index(window_size_obj);
  nd::arrfunc func;
  if (WArrFunc_Check(func_obj)) {
    func = ((WArrFunc *)func_obj)->v;
  }
  else {
    ndt::type el_tp = arr.get_type().get_type_at_dimension(NULL, 1);
    ndt::type proto = ndt::make_arrfunc(
        ndt::make_tuple(ndt::make_fixed_dimsym(el_tp)), el_tp);

    func = arrfunc_from_pyfunc(func_obj, proto);
  }
  nd::arrfunc roll = make_rolling_arrfunc(func, window_size);
  nd::array result = roll(arr, ectx);
  return wrap_array(result);
}

PyObject *pydynd::get_published_arrfuncs()
{
  pyobject_ownref res(PyDict_New());
  const map<nd::string, nd::arrfunc> &reg = func::get_regfunctions();
  for (map<nd::string, nd::arrfunc>::const_iterator it = reg.begin();
       it != reg.end(); ++it) {
    PyDict_SetItem(res.get(), pystring_from_string(it->first.str()),
                   wrap_array(it->second));
  }
  return res.release();
}
<commit_msg>Fix for changes to call<commit_after>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#include "arrfunc_functions.hpp"
#include "array_functions.hpp"
#include "array_from_py.hpp"
#include "array_assign_from_py.hpp"
#include "type_functions.hpp"
#include "utility_functions.hpp"
#include "numpy_interop.hpp"
#include "arrfunc_from_pyfunc.hpp"

#include <dynd/types/string_type.hpp>
#include <dynd/types/base_dim_type.hpp>
#include <dynd/memblock/external_memory_block.hpp>
#include <dynd/array_range.hpp>
#include <dynd/type_promotion.hpp>
#include <dynd/types/base_struct_type.hpp>
#include <dynd/types/base_bytes_type.hpp>
#include <dynd/types/struct_type.hpp>
#include <dynd/func/rolling_arrfunc.hpp>
#include <dynd/view.hpp>
#include <dynd/func/callable.hpp>
#include <dynd/func/arrfunc_registry.hpp>

using namespace std;
using namespace dynd;
using namespace pydynd;

PyTypeObject *pydynd::WArrFunc_Type;

void pydynd::init_w_arrfunc_typeobject(PyObject *type)
{
  WArrFunc_Type = (PyTypeObject *)type;
}

PyObject *pydynd::arrfunc_call(PyObject *af_obj, PyObject *args_obj,
                               PyObject *ectx_obj)
{
  if (!WArrFunc_Check(af_obj)) {
    PyErr_SetString(PyExc_TypeError, "arrfunc_call expected an nd.arrfunc");
    return NULL;
  }
  const nd::arrfunc &af = ((WArrFunc *)af_obj)->v;
  if (af.is_null()) {
    PyErr_SetString(PyExc_ValueError, "cannot call a null nd.arrfunc");
    return NULL;
  }
  if (!PyTuple_Check(args_obj)) {
    PyErr_SetString(PyExc_ValueError,
                    "arrfunc_call requires a tuple of arguments");
    return NULL;
  }
  const eval::eval_context *ectx = eval_context_from_pyobj(ectx_obj);
  // Convert args into nd::arrays
  intptr_t args_size = PyTuple_Size(args_obj);
  std::vector<nd::array> args(args_size);
  for (intptr_t i = 0; i < args_size; ++i) {
    args[i] = array_from_py(PyTuple_GET_ITEM(args_obj, i), 0, false, ectx);
  }

  nd::array result = af.call(args_size, args_size ? &args[0] : NULL, ectx);
  return wrap_array(result);
}

PyObject *pydynd::arrfunc_rolling_apply(PyObject *func_obj, PyObject *arr_obj,
                                        PyObject *window_size_obj,
                                        PyObject *ectx_obj)
{
  eval::eval_context *ectx = const_cast<eval::eval_context *>(eval_context_from_pyobj(ectx_obj));
  nd::array arr = array_from_py(arr_obj, 0, false, ectx);
  intptr_t window_size = pyobject_as_index(window_size_obj);
  nd::arrfunc func;
  if (WArrFunc_Check(func_obj)) {
    func = ((WArrFunc *)func_obj)->v;
  }
  else {
    ndt::type el_tp = arr.get_type().get_type_at_dimension(NULL, 1);
    ndt::type proto = ndt::make_arrfunc(
        ndt::make_tuple(ndt::make_fixed_dimsym(el_tp)), el_tp);

    func = arrfunc_from_pyfunc(func_obj, proto);
  }
  nd::arrfunc roll = make_rolling_arrfunc(func, window_size);
  nd::array result = roll(arr, kwds("ectx", ectx));
  return wrap_array(result);
}

PyObject *pydynd::get_published_arrfuncs()
{
  pyobject_ownref res(PyDict_New());
  const map<nd::string, nd::arrfunc> &reg = func::get_regfunctions();
  for (map<nd::string, nd::arrfunc>::const_iterator it = reg.begin();
       it != reg.end(); ++it) {
    PyDict_SetItem(res.get(), pystring_from_string(it->first.str()),
                   wrap_array(it->second));
  }
  return res.release();
}
<|endoftext|>


<commit_before>#include "artifact_subtract.h"
#include <cstring>

ArtifactSubtract::ArtifactSubtract(int _nsc, int _nrc, int _maxcurrent,
                                   int _buflen, float _alpha)
{
	nsc = _nsc;				// 16
	nrc = _nrc;				// 96
	maxcurrent = _maxcurrent;		// 100
	buflen = _buflen;			// 64
	alpha = _alpha;				// 0.99;

	sa = new float[maxcurrent*nsc*nrc*buflen];	// stim artifact buffer
	of = new long[maxcurrent*nsc];				// buffer read offset
	memset(of, -1, maxcurrent*nsc*sizeof(long));
}

ArtifactSubtract::~ArtifactSubtract()
{
	delete[] sa;
	delete[] of;
}

void ArtifactSubtract::filter(float *f, u16 *sc, u16 *current, int ns)
{
	// This function takes a pointer to a matrix of neural data of dimensionality
	// (number of recording chans) x (number of samples) and a pointer to a
	// vector of stimulation chans of length ns and a vector of stimulation
	// currents of length ns
	//
	// It then goes through this data, updating the SA template if
	// appropriate (ie only single channel is hot) and then subtracts using
	// the SA templates for any number of hot channels (assuming SAs add).
	//
	// Importantly, since the buffer offsets are only per current and stimchan
	// (ie we assume the SA affects all recording channels simultaneously)
	// we MUST process each recchan before advancing the buffer offset and
	// moving to the next time sample. That is, we must process the data by
	// looping over time samples first.
	//
	// Note also that this function operates on the data matrix, f, in place.
	// The stimchannel and current values are not changed.

	// this is a helper function
	auto check_bit = [](u16 var, int n) -> bool {
		if (n < 0 || n > 15)
		{
			return false;
		}
		return (var) & (1<<n);
	};

	for (int k=0; k<ns; k++) {	// loop over samples

		// first loop through and get how many stim chans are hot
		// and update the offset pointers

		int nstim = 0; // stim pulses "hot" on this sample
		for (int j=0; j<maxcurrent; j++) {	// loop over currents
			for (int i=0; i<nsc; i++) {	// loop over stimchans
				if (sc[k] > 0) {	// ie if there is stim this sample
					if (check_bit(sc[k], i) && current[k] == (j+1)) {
						if (of[j*nsc+i] != -1) {
							error("went hot while hot!");
						}
						of[j*nsc+i] = 0;
					}
				}
				if (of[j*nsc+i] != -1) {
					nstim++;
				}
			}
		}

		if (nstim == 0) {
			continue;
		}

		// now loop through again and update (if appropriate) and
		// apply (always) the artifact buffers to the data matrix

		for (int j=0; j<maxcurrent; j++) {	// loop over currents
			for (int i=0; i<nsc; i++) {	// loop over stimchans
				long *idx = &(of[j*nsc+i]);
				if (*idx != -1) { // if we are stimulating on this current&chan
					for (int m=0; m<nrc; m++) {	// loop over recchans
						// this is the pointer to a buffer for a particular
						// current, stimchan, and recchan
						float *x = &(sa[j*nsc*nrc*buflen + i*nrc*buflen + m*buflen]);
						if (nstim == 1) { //if 1 channel is hot, update templates
							x[*idx] *= alpha;
							x[*idx] += (1.0-alpha) * f[m*ns+k];
						}
						//f[m*ns+k] -= x[*idx]; // subtract templates

					}
					// advance buffer and reset if necessary
					(*idx)++;
					if (*idx >= buflen) {
						(*idx) = -1;
					}
				}
			}
		}
	}
}
<commit_msg>final debug code removed. subtr nominally works?<commit_after>#include "artifact_subtract.h"
#include <cstring>

ArtifactSubtract::ArtifactSubtract(int _nsc, int _nrc, int _maxcurrent,
                                   int _buflen, float _alpha)
{
	nsc = _nsc;				// 16
	nrc = _nrc;				// 96
	maxcurrent = _maxcurrent;		// 100
	buflen = _buflen;			// 64
	alpha = _alpha;				// 0.99;

	sa = new float[maxcurrent*nsc*nrc*buflen];	// stim artifact buffer
	of = new long[maxcurrent*nsc];				// buffer read offset
	memset(of, -1, maxcurrent*nsc*sizeof(long));
}

ArtifactSubtract::~ArtifactSubtract()
{
	delete[] sa;
	delete[] of;
}

void ArtifactSubtract::filter(float *f, u16 *sc, u16 *current, int ns)
{
	// This function takes a pointer to a matrix of neural data of dimensionality
	// (number of recording chans) x (number of samples) and a pointer to a
	// vector of stimulation chans of length ns and a vector of stimulation
	// currents of length ns
	//
	// It then goes through this data, updating the SA template if
	// appropriate (ie only single channel is hot) and then subtracts using
	// the SA templates for any number of hot channels (assuming SAs add).
	//
	// Importantly, since the buffer offsets are only per current and stimchan
	// (ie we assume the SA affects all recording channels simultaneously)
	// we MUST process each recchan before advancing the buffer offset and
	// moving to the next time sample. That is, we must process the data by
	// looping over time samples first.
	//
	// Note also that this function operates on the data matrix, f, in place.
	// The stimchannel and current values are not changed.

	// this is a helper function
	auto check_bit = [](u16 var, int n) -> bool {
		if (n < 0 || n > 15)
		{
			return false;
		}
		return (var) & (1<<n);
	};

	for (int k=0; k<ns; k++) {	// loop over samples

		// first loop through and get how many stim chans are hot
		// and update the offset pointers

		int nstim = 0; // stim pulses "hot" on this sample
		for (int j=0; j<maxcurrent; j++) {	// loop over currents
			for (int i=0; i<nsc; i++) {	// loop over stimchans
				if (sc[k] > 0) {	// ie if there is stim this sample
					if (check_bit(sc[k], i) && current[k] == (j+1)) {
						if (of[j*nsc+i] != -1) {
							error("went hot while hot!");
						}
						of[j*nsc+i] = 0;
					}
				}
				if (of[j*nsc+i] != -1) {
					nstim++;
				}
			}
		}

		if (nstim == 0) {
			continue;
		}

		// now loop through again and update (if appropriate) and
		// apply (always) the artifact buffers to the data matrix

		for (int j=0; j<maxcurrent; j++) {	// loop over currents
			for (int i=0; i<nsc; i++) {	// loop over stimchans
				long *idx = &(of[j*nsc+i]);
				if (*idx != -1) { // if we are stimulating on this current&chan
					for (int m=0; m<nrc; m++) {	// loop over recchans
						// this is the pointer to a buffer for a particular
						// current, stimchan, and recchan
						float *x = &(sa[j*nsc*nrc*buflen + i*nrc*buflen + m*buflen]);
						if (nstim == 1) { //if 1 channel is hot, update templates
							x[*idx] *= alpha;
							x[*idx] += (1.0-alpha) * f[m*ns+k];
						}
						f[m*ns+k] -= x[*idx]; // subtract templates

					}
					// advance buffer and reset if necessary
					(*idx)++;
					if (*idx >= buflen) {
						(*idx) = -1;
					}
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>/**
	\file cube.cpp
	\brief LightEngine 3D (examples): cube example
	\brief Windows implementation
	\author Frederic Meslin (fred@fredslab.net)
	\twitter @marzacdev
	\website http://fredslab.net
*/

#include "engine/le3d.h"
#include "tools/timing.h"

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>

/*****************************************************************************/
const int resoX = 640;
const int resoY = 480;

/*****************************************************************************/
int main()
{
/** Create application objects */
	LeWindow     window     = LeWindow("Le3d: cube example", resoX, resoY);
	LeDraw       draw       = LeDraw(window.getContext(), resoX, resoY);
	LeRenderer   renderer   = LeRenderer(resoX, resoY);
	LeRasterizer rasterizer = LeRasterizer(resoX, resoY);

/** Load the assets (textures then 3D models) */
	bmpCache.loadDirectory("assets");
	meshCache.loadDirectory("assets");

/** Retrieve the 3D model */
    int crateSlot = meshCache.getFromName("crate.obj");
    LeMesh * crate = meshCache.slots[crateSlot].mesh;

/** Create three lights */
	LeLight light1(LE_LIGHT_DIRECTIONAL, 0xFF4040);
	LeLight light2(LE_LIGHT_DIRECTIONAL, 0x4040FF);
	LeLight light3(LE_LIGHT_AMBIENT, 0x404040);

	light1.axis = LeAxis(LeVertex(), LeVertex(1.0f, 0.0f, -1.0f));
	light2.axis = LeAxis(LeVertex(), LeVertex(-1.0f, 0.0f, -1.0f));

/** Set the renderer properties */
    renderer.setViewPosition(LeVertex(0.0f, 0.0f, 3.0f));
    renderer.updateViewMatrix();
    rasterizer.background = 0xC0C0FF;

/** Initialize the timing */
    timing.setup(60);
	timing.firstFrame();

/** Program main loop */
    MSG msg;
	msg.message = 0;
	while(msg.message != WM_QUIT) {
    /** Process OS messages */
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

    /** Wait for next frame */
		timing.waitNextFrame();

    /** Copy render frame to window context */
        draw.setPixels(rasterizer.frame.data);

    /** Update model transforms */
        crate->angle += LeVertex(0.1f, 2.0f, 0.0f);
        crate->updateMatrix();

	/** Light model */
		LeLight::black(crate);
		light1.shine(crate);
		light2.shine(crate);
		light3.shine(crate);

    /** Render the 3D model */
        renderer.render(crate);

    /** Draw the triangles */
        rasterizer.flush();
        rasterizer.rasterList(renderer.getTriangleList());
        renderer.flush();
	}

    timing.lastFrame();
    return 0;
}
<commit_msg>Correcting indentation<commit_after>/**
	\file cube.cpp
	\brief LightEngine 3D (examples): cube example
	\brief Windows implementation
	\author Frederic Meslin (fred@fredslab.net)
	\twitter @marzacdev
	\website http://fredslab.net
*/

#include "engine/le3d.h"
#include "tools/timing.h"

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>

/*****************************************************************************/
const int resoX = 640;
const int resoY = 480;

/*****************************************************************************/
int main()
{
/** Create application objects */
	LeWindow	 window		= LeWindow("Le3d: cube example", resoX, resoY);
	LeDraw		 draw		= LeDraw(window.getContext(), resoX, resoY);
	LeRenderer	 renderer	= LeRenderer(resoX, resoY);
	LeRasterizer rasterizer = LeRasterizer(resoX, resoY);

/** Load the assets (textures then 3D models) */
	bmpCache.loadDirectory("assets");
	meshCache.loadDirectory("assets");

/** Retrieve the 3D model */
	int crateSlot = meshCache.getFromName("crate.obj");
	LeMesh * crate = meshCache.slots[crateSlot].mesh;

/** Create three lights */
	LeLight light1(LE_LIGHT_DIRECTIONAL, 0xFF4040);
	LeLight light2(LE_LIGHT_DIRECTIONAL, 0x4040FF);
	LeLight light3(LE_LIGHT_AMBIENT, 0x404040);

	light1.axis = LeAxis(LeVertex(), LeVertex(1.0f, 0.0f, -1.0f));
	light2.axis = LeAxis(LeVertex(), LeVertex(-1.0f, 0.0f, -1.0f));

/** Set the renderer properties */
	renderer.setViewPosition(LeVertex(0.0f, 0.0f, 3.0f));
	renderer.updateViewMatrix();
	rasterizer.background = 0xC0C0FF;

/** Initialize the timing */
	timing.setup(60);
	timing.firstFrame();

/** Program main loop */
	MSG msg;
	msg.message = 0;
	while(msg.message != WM_QUIT) {
	/** Process OS messages */
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

	/** Wait for next frame */
		timing.waitNextFrame();

	/** Copy render frame to window context */
		draw.setPixels(rasterizer.frame.data);

	/** Update model transforms */
		crate->angle += LeVertex(0.1f, 2.0f, 0.0f);
		crate->updateMatrix();

	/** Light model */
		LeLight::black(crate);
		light1.shine(crate);
		light2.shine(crate);
		light3.shine(crate);

	/** Render the 3D model */
		renderer.render(crate);

	/** Draw the triangles */
		rasterizer.flush();
		rasterizer.rasterList(renderer.getTriangleList());
		renderer.flush();
	}

	timing.lastFrame();
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main(int argc, char *argv[])
{
	boost::asio::io_service io;

	boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
	t.wait();

	std::cout << "Hello, world!" << std::endl;

	return 0;
}
<commit_msg>chat: start working on a parameter binding example from Asio<commit_after>#include <iostream>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(const boost::system::error_code &e, boost::asio::deadline_timer& t, int& count)
{
	std::cout << "A timer thing No. " << count++ << std::endl;
}

int main(int argc, char *argv[])
{
	boost::asio::io_service io;

	boost::asio::deadline_timer t1(io, boost::posix_time::seconds(1));
	boost::asio::deadline_timer t2(io, boost::posix_time::seconds(2));
	t1.async_wait(&print);
	std::cout << "Between" << std::endl;
	t2.async_wait(&print);

	io.run();

	std::cout << "Meantime stuff" << std::endl;

	return 0;
}
<|endoftext|>


<commit_before>#ifndef RTC_HH
#define RTC_HH

#include <stdint.h>

namespace hal {
    using rtc_time_su = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_time_st = lib::regbit<4, lib::u8, 3, 0>;
    using rtc_time_mnu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_time_mnt = lib::regbit<12, lib::u8, 3, 0>;
    using rtc_time_hu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_time_ht = lib::regbit<20, lib::u8, 2, 0>;
    using rtc_time_pm = lib::regbit<22>;

    using rtc_date_du = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_date_dt = lib::regbit<4, lib::u8, 2, 0>;
    using rtc_date_mu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_date_mt = lib::regbit<12, lib::u8, 1, 0>;
    enum struct rtc_date_wdu_t : lib::u8 {
        monday = 0b001,
        tuesday = 0b010,
        wednesday = 0b011,
        thursday = 0b100,
        friday = 0b101,
        saturday = 0b110,
        sunday = 0b111
    };
    using rtc_date_wdu =
        lib::regbit<13,
        rtc_date_wdu_t,
        3,
        rtc_date_wdu_t::monday>;
    using rtc_date_yu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_date_yt = lib::regbit<20, lib::u8, 4, 0>;

    enum struct rtc_control_wucksel_t : lib::u8 {
        rtc_by16 = 0b000,
        rtc_by8 = 0b001,
        rtc_by4 = 0b010,
        rtc_by2 = 0b011,
        ck_spre = 0b100,
        ck_spre_wut_add = 0b110
    };
    using rtc_control_wucksel =
        lib::regbit<0,
        rtc_control_wucksel_t,
        3,
        rtc_control_wucksel_t::rtc_by16>;
    using rtc_control_tsedge = lib::regbit<3>;
    using rtc_control_refckon = lib::regbit<4>;
    using rtc_control_bypshad = lib::regbit<5>;
    using rtc_control_fmt = lib::regbit<6>;
    using rtc_control_dce = lib::regbit<7>;
    using rtc_control_alrae = lib::regbit<8>;
    using rtc_control_alrbe = lib::regbit<9>;
    using rtc_control_wute = lib::regbit<10>;
    using rtc_control_tse = lib::regbit<11>;
    using rtc_control_alraie = lib::regbit<12>;
    using rtc_control_alrbie = lib::regbit<13>;
    using rtc_control_wutie = lib::regbit<14>;
    using rtc_control_tsie = lib::regbit<15>;
    using rtc_control_add1h = lib::regbit<16>;
    using rtc_control_sub1h = lib::regbit<17>;
    using rtc_control_bkp = lib::regbit<18>;
    using rtc_control_cosel = lib::regbit<19>;
    using rtc_control_pol = lib::regbit<20>;
    enum struct rtc_control_osel_t : lib::u8 {
        disabled = 0b00,
        alarm_a = 0b01,
        alarm_b = 0b10,
        wakeup = 0b11,
    };
    using rtc_control_osel =
        lib::regbit<21,
        rtc_control_osel_t,
        2,
        rtc_control_osel_t::disabled>;
    using rtc_control_coe = lib::regbit<23>;

    using rtc_init_status_alrawf = lib::regbit<0>;
    using rtc_init_status_alrbwf = lib::regbit<1>;
    using rtc_init_status_wutwf = lib::regbit<2>;
    using rtc_init_status_shpf = lib::regbit<3>;
    using rtc_init_status_inits = lib::regbit<4>;
    using rtc_init_status_rsf = lib::regbit<5>;
    using rtc_init_status_initf = lib::regbit<6>;
    using rtc_init_status_init = lib::regbit<7>;
    using rtc_init_status_alraf = lib::regbit<8>;
    using rtc_init_status_alrbf = lib::regbit<9>;
    using rtc_init_status_wutf = lib::regbit<10>;
    using rtc_init_status_tsf = lib::regbit<11>;
    using rtc_init_status_tsovf = lib::regbit<12>;
    using rtc_init_status_tamp1f = lib::regbit<13>;
    using rtc_init_status_tamp2f = lib::regbit<14>;
    using rtc_init_status_tamp3f = lib::regbit<15>;
    using rtc_init_status_recalpf = lib::regbit<16>;

    using rtc_prescaler_prediv_s = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_prescaler_prediv_a = lib::regbit<16, lib::u8, 7, 1>;

    struct rtc_wakeup_timer_t {
        uint16_t wut;
        uint16_t _unused0;
    };

    using rtc_calib_dc = lib::regbit<0, lib::u8, 5, 0>;
    using rtc_calib_dcs = lib::regbit<7>;

    using rtc_alarm_su = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_alarm_st = lib::regbit<4, lib::u8, 3, 0>;
    using rtc_alarm_msk1 = lib::regbit<7>;
    using rtc_alarm_mnu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_alarm_mnt = lib::regbit<12, lib::u8, 3, 0>;
    using rtc_alarm_msk2 = lib::regbit<15>;
    using rtc_alarm_hu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_alarm_ht = lib::regbit<20, lib::u8, 2, 0>;
    using rtc_alarm_pm = lib::regbit<22>;
    using rtc_alarm_msk3 = lib::regbit<23>;
    using rtc_alarm_du = lib::regbit<24, lib::u8, 4, 0>;
    using rtc_alarm_wdu =
        lib::regbit<24,
        rtc_date_wdu_t,
        3,
        rtc_date_wdu_t::monday>;
    using rtc_alarm_dt = lib::regbit<28, lib::u8, 2, 0>;
    using rtc_alarm_wdsel = lib::regbit<30>;
    using rtc_alarm_msk4 = lib::regbit<31>;

    struct rtc_sub_second_t {
        uint16_t ss;
        uint16_t _unused0;
    };

    using rtc_shift_subfs = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_shift_add1s = lib::regbit<31>;

    struct rtc_write_protect_t {
        uint8_t key;
        uint8_t _unused0[3];
    };

    using rtc_calib2_calm = lib::regbit<0, lib::u16, 9, 0>;
    using rtc_calib2_calw16 = lib::regbit<13>;
    using rtc_calib2_calw8 = lib::regbit<14>;
    using rtc_calib2_calp = lib::regbit<15>;

    using rtc_tamper_alt_func_tamp1e = lib::regbit<0>;
    using rtc_tamper_alt_func_tamp1trg = lib::regbit<1>;
    using rtc_tamper_alt_func_tampie = lib::regbit<2>;
    using rtc_tamper_alt_func_tamp2e = lib::regbit<3>;
    using rtc_tamper_alt_func_tamp2trg = lib::regbit<4>;
    using rtc_tamper_alt_func_tamp3e = lib::regbit<5>;
    using rtc_tamper_alt_func_tamp3trg = lib::regbit<6>;
    using rtc_tamper_alt_func_tampts = lib::regbit<7>;
    enum struct rtc_tamper_alt_func_tampfreq_t : lib::u8 {
        rtc_by32768 = 0x0,
        rtc_by16384 = 0x1,
        rtc_by8192 = 0x2,
        rtc_by4096 = 0x3,
        rtc_by2048 = 0x4,
        rtc_by1024 = 0x5,
        rtc_by512 = 0x6,
        rtc_by256 = 0x7,
    };
    using rtc_tamper_alt_func_tampfreq =
        lib::regbit<8,
        rtc_tamper_alt_func_tampfreq_t,
        3,
        rtc_tamper_alt_func_tampfreq_t::rtc_by32768>;
    enum struct rtc_tamper_alt_func_tampflt_t : lib::u8 {
        on_edge = 0x0,
        after2 = 0x1,
        after4 = 0x2,
        after8 = 0x3,
    };
    using rtc_tamper_alt_func_tampflt =
        lib::regbit<11,
        rtc_tamper_alt_func_tampflt_t,
        2,
        rtc_tamper_alt_func_tampflt_t::on_edge>;
    enum struct rtc_tamper_alt_func_tampprch_t : lib::u8 {
        each1 = 0x0,
        each2 = 0x1,
        each4 = 0x2,
        each8 = 0x3,
    };
    using rtc_tamper_alt_func_tampprch =
        lib::regbit<13,
        rtc_tamper_alt_func_tampprch_t,
        2,
        rtc_tamper_alt_func_tampprch_t::each1>;
    using rtc_tamper_alt_func_tamppudis = lib::regbit<15>;
    using rtc_tamper_alt_func_alarmouttype = lib::regbit<18>;

    using rtc_alarm_sub_second_ss = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_alarm_sub_second_maskss = lib::regbit<24, lib::u8, 4, 0>;

    template <lib::u32 addr, lib::u8 backup_size>
    struct rtc_d {
        struct rtc_t {
            uint32_t time;
            uint32_t date;
            uint32_t control;
            uint32_t init_status;
            uint32_t prescaler;
            rtc_wakeup_timer_t wakeup_timer;
            uint32_t calib;
            uint32_t alarma;
            uint32_t alarmb;
            rtc_write_protect_t write_protect;
            rtc_sub_second_t sub_second;
            uint32_t shift;
            uint32_t ts_time;
            uint32_t ts_date;
            rtc_sub_second_t ts_sub_second;
            uint32_t calib2;
            uint32_t tamper_alt_func;
            uint32_t alarma_sub_second;
            uint32_t alarmb_sub_second;
            uint32_t bkpr[backup_size];
        };

        static constexpr volatile rtc_t * const regs =
            reinterpret_cast<rtc_t *>(addr);
    };
}

#include "hal/rtc_d.hh"

#endif // RTC_HH
<commit_msg>Update hal/rtc - change types, change headers<commit_after>#ifndef RTC_HH
#define RTC_HH

#include "lib/types.hh"
#include "lib/regbit.hh"

namespace hal {
    using rtc_time_su = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_time_st = lib::regbit<4, lib::u8, 3, 0>;
    using rtc_time_mnu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_time_mnt = lib::regbit<12, lib::u8, 3, 0>;
    using rtc_time_hu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_time_ht = lib::regbit<20, lib::u8, 2, 0>;
    using rtc_time_pm = lib::regbit<22>;

    using rtc_date_du = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_date_dt = lib::regbit<4, lib::u8, 2, 0>;
    using rtc_date_mu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_date_mt = lib::regbit<12, lib::u8, 1, 0>;
    enum struct rtc_date_wdu_t : lib::u8 {
        monday = 0b001,
        tuesday = 0b010,
        wednesday = 0b011,
        thursday = 0b100,
        friday = 0b101,
        saturday = 0b110,
        sunday = 0b111
    };
    using rtc_date_wdu =
        lib::regbit<13,
        rtc_date_wdu_t,
        3,
        rtc_date_wdu_t::monday>;
    using rtc_date_yu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_date_yt = lib::regbit<20, lib::u8, 4, 0>;

    enum struct rtc_control_wucksel_t : lib::u8 {
        rtc_by16 = 0b000,
        rtc_by8 = 0b001,
        rtc_by4 = 0b010,
        rtc_by2 = 0b011,
        ck_spre = 0b100,
        ck_spre_wut_add = 0b110
    };
    using rtc_control_wucksel =
        lib::regbit<0,
        rtc_control_wucksel_t,
        3,
        rtc_control_wucksel_t::rtc_by16>;
    using rtc_control_tsedge = lib::regbit<3>;
    using rtc_control_refckon = lib::regbit<4>;
    using rtc_control_bypshad = lib::regbit<5>;
    using rtc_control_fmt = lib::regbit<6>;
    using rtc_control_dce = lib::regbit<7>;
    using rtc_control_alrae = lib::regbit<8>;
    using rtc_control_alrbe = lib::regbit<9>;
    using rtc_control_wute = lib::regbit<10>;
    using rtc_control_tse = lib::regbit<11>;
    using rtc_control_alraie = lib::regbit<12>;
    using rtc_control_alrbie = lib::regbit<13>;
    using rtc_control_wutie = lib::regbit<14>;
    using rtc_control_tsie = lib::regbit<15>;
    using rtc_control_add1h = lib::regbit<16>;
    using rtc_control_sub1h = lib::regbit<17>;
    using rtc_control_bkp = lib::regbit<18>;
    using rtc_control_cosel = lib::regbit<19>;
    using rtc_control_pol = lib::regbit<20>;
    enum struct rtc_control_osel_t : lib::u8 {
        disabled = 0b00,
        alarm_a = 0b01,
        alarm_b = 0b10,
        wakeup = 0b11,
    };
    using rtc_control_osel =
        lib::regbit<21,
        rtc_control_osel_t,
        2,
        rtc_control_osel_t::disabled>;
    using rtc_control_coe = lib::regbit<23>;

    using rtc_init_status_alrawf = lib::regbit<0>;
    using rtc_init_status_alrbwf = lib::regbit<1>;
    using rtc_init_status_wutwf = lib::regbit<2>;
    using rtc_init_status_shpf = lib::regbit<3>;
    using rtc_init_status_inits = lib::regbit<4>;
    using rtc_init_status_rsf = lib::regbit<5>;
    using rtc_init_status_initf = lib::regbit<6>;
    using rtc_init_status_init = lib::regbit<7>;
    using rtc_init_status_alraf = lib::regbit<8>;
    using rtc_init_status_alrbf = lib::regbit<9>;
    using rtc_init_status_wutf = lib::regbit<10>;
    using rtc_init_status_tsf = lib::regbit<11>;
    using rtc_init_status_tsovf = lib::regbit<12>;
    using rtc_init_status_tamp1f = lib::regbit<13>;
    using rtc_init_status_tamp2f = lib::regbit<14>;
    using rtc_init_status_tamp3f = lib::regbit<15>;
    using rtc_init_status_recalpf = lib::regbit<16>;

    using rtc_prescaler_prediv_s = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_prescaler_prediv_a = lib::regbit<16, lib::u8, 7, 1>;

    struct rtc_wakeup_timer_t {
        uint16_t wut;
        uint16_t _unused0;
    };

    using rtc_calib_dc = lib::regbit<0, lib::u8, 5, 0>;
    using rtc_calib_dcs = lib::regbit<7>;

    using rtc_alarm_su = lib::regbit<0, lib::u8, 4, 0>;
    using rtc_alarm_st = lib::regbit<4, lib::u8, 3, 0>;
    using rtc_alarm_msk1 = lib::regbit<7>;
    using rtc_alarm_mnu = lib::regbit<8, lib::u8, 4, 0>;
    using rtc_alarm_mnt = lib::regbit<12, lib::u8, 3, 0>;
    using rtc_alarm_msk2 = lib::regbit<15>;
    using rtc_alarm_hu = lib::regbit<16, lib::u8, 4, 0>;
    using rtc_alarm_ht = lib::regbit<20, lib::u8, 2, 0>;
    using rtc_alarm_pm = lib::regbit<22>;
    using rtc_alarm_msk3 = lib::regbit<23>;
    using rtc_alarm_du = lib::regbit<24, lib::u8, 4, 0>;
    using rtc_alarm_wdu =
        lib::regbit<24,
        rtc_date_wdu_t,
        3,
        rtc_date_wdu_t::monday>;
    using rtc_alarm_dt = lib::regbit<28, lib::u8, 2, 0>;
    using rtc_alarm_wdsel = lib::regbit<30>;
    using rtc_alarm_msk4 = lib::regbit<31>;

    struct rtc_sub_second_t {
        uint16_t ss;
        uint16_t _unused0;
    };

    using rtc_shift_subfs = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_shift_add1s = lib::regbit<31>;

    struct rtc_write_protect_t {
        uint8_t key;
        uint8_t _unused0[3];
    };

    using rtc_calib2_calm = lib::regbit<0, lib::u16, 9, 0>;
    using rtc_calib2_calw16 = lib::regbit<13>;
    using rtc_calib2_calw8 = lib::regbit<14>;
    using rtc_calib2_calp = lib::regbit<15>;

    using rtc_tamper_alt_func_tamp1e = lib::regbit<0>;
    using rtc_tamper_alt_func_tamp1trg = lib::regbit<1>;
    using rtc_tamper_alt_func_tampie = lib::regbit<2>;
    using rtc_tamper_alt_func_tamp2e = lib::regbit<3>;
    using rtc_tamper_alt_func_tamp2trg = lib::regbit<4>;
    using rtc_tamper_alt_func_tamp3e = lib::regbit<5>;
    using rtc_tamper_alt_func_tamp3trg = lib::regbit<6>;
    using rtc_tamper_alt_func_tampts = lib::regbit<7>;
    enum struct rtc_tamper_alt_func_tampfreq_t : lib::u8 {
        rtc_by32768 = 0x0,
        rtc_by16384 = 0x1,
        rtc_by8192 = 0x2,
        rtc_by4096 = 0x3,
        rtc_by2048 = 0x4,
        rtc_by1024 = 0x5,
        rtc_by512 = 0x6,
        rtc_by256 = 0x7,
    };
    using rtc_tamper_alt_func_tampfreq =
        lib::regbit<8,
        rtc_tamper_alt_func_tampfreq_t,
        3,
        rtc_tamper_alt_func_tampfreq_t::rtc_by32768>;
    enum struct rtc_tamper_alt_func_tampflt_t : lib::u8 {
        on_edge = 0x0,
        after2 = 0x1,
        after4 = 0x2,
        after8 = 0x3,
    };
    using rtc_tamper_alt_func_tampflt =
        lib::regbit<11,
        rtc_tamper_alt_func_tampflt_t,
        2,
        rtc_tamper_alt_func_tampflt_t::on_edge>;
    enum struct rtc_tamper_alt_func_tampprch_t : lib::u8 {
        each1 = 0x0,
        each2 = 0x1,
        each4 = 0x2,
        each8 = 0x3,
    };
    using rtc_tamper_alt_func_tampprch =
        lib::regbit<13,
        rtc_tamper_alt_func_tampprch_t,
        2,
        rtc_tamper_alt_func_tampprch_t::each1>;
    using rtc_tamper_alt_func_tamppudis = lib::regbit<15>;
    using rtc_tamper_alt_func_alarmouttype = lib::regbit<18>;

    using rtc_alarm_sub_second_ss = lib::regbit<0, lib::u16, 15, 0>;
    using rtc_alarm_sub_second_maskss = lib::regbit<24, lib::u8, 4, 0>;

    template <lib::u32 addr, lib::u8 backup_size>
    struct rtc_d {
        struct rtc_t {
            lib::u32 time;
            lib::u32 date;
            lib::u32 control;
            lib::u32 init_status;
            lib::u32 prescaler;
            rtc_wakeup_timer_t wakeup_timer;
            lib::u32 calib;
            lib::u32 alarma;
            lib::u32 alarmb;
            rtc_write_protect_t write_protect;
            rtc_sub_second_t sub_second;
            lib::u32 shift;
            lib::u32 ts_time;
            lib::u32 ts_date;
            rtc_sub_second_t ts_sub_second;
            lib::u32 calib2;
            lib::u32 tamper_alt_func;
            lib::u32 alarma_sub_second;
            lib::u32 alarmb_sub_second;
            lib::u32 bkpr[backup_size];
        };

        static constexpr volatile rtc_t * const regs =
            reinterpret_cast<rtc_t *>(addr);
    };
}

#include "hal/rtc_d.hh"

#endif // RTC_HH
<|endoftext|>


<commit_before>/*
 * logger.cpp
 *
 *  Created on: 2015. 8. 9.
 *      Author: hwang-linux
 */

#include "logger.hpp"
#include <iostream>
#include "interface/ilog.hpp"
#include "util/format.h"

namespace cossb {
namespace log {

logger::logger(){ }
logger::logger(interface::ilog* log):_logger(log) { }

logger::~logger() {
	_logger = nullptr;

}
void logger::log(const log::loglevel level, const char* str)
{
	log_base(level, str);
}

void logger::log_base(const loglevel level, const char* str)
{
	if(_logger)
	{
		switch(level)
		{
		case	loglevel::TRACE:	_logger->trace(str);	break;
		case	loglevel::DEBUG:	_logger->debug(str);	break;
		case	loglevel::INFO:	_logger->info(str);	break;
		case	loglevel::NOTICE: _logger->notice(str);	break;
		case	loglevel::WARN: _logger->warn(str);	break;
		case	loglevel::ERROR: _logger->error(str);	break;
		case	loglevel::CRITICAL: _logger->critical(str);	break;
		case	loglevel::ALERT: _logger->alert(str);	break;
		case	loglevel::EMERG: _logger->emerg(str);	break;
		}
	}
	else
	{
		switch(level)
		{
		case	loglevel::TRACE:	cout << "[TRACE]\t"	<< str << endl;	break;
		case	loglevel::DEBUG:	cout << "[DEBUG]\t"	<< str << endl;	break;
		case	loglevel::INFO:	cout << "[INFO]\t"	<< str << endl;	break;
		case	loglevel::NOTICE: cout << "[NOTICE]\t"	<< str << endl;	break;
		case	loglevel::WARN: cout << "[WARN]\t"	<< str << endl;	break;
		case	loglevel::ERROR: cout << "[ERROR]\t"	<< str << endl;	break;
		case	loglevel::CRITICAL: cout << "[CRITICAL]\t"	<< str << endl;	break;
		case	loglevel::ALERT: cout << "[ALERT]\t"	<< str << endl;	break;
		case	loglevel::EMERG: cout << "[EMERG]\t"	<< str << endl;	break;
		}
	}
}

void logger::adopt(interface::ilog* intlog)
{
	_logger = intlog;
}

/*
void logger::trace(const char* logstr)
{
	cout << _time.current_formatted() << "[TRACE] " << logstr << endl;
}
void logger::debug(const char* logstr)
{
	cout << _time.current_formatted() << "[DEBUG] " << logstr << endl;
}
void logger::info(const char* logstr)
{
	cout << _time.current_formatted() << "[INFO] " << logstr << endl;
}
void logger::notice(const char* logstr)
{
	cout << _time.current_formatted() << "[NOTICE] " << logstr << endl;
}
void logger::warn(const char* logstr)
{
	cout << _time.current_formatted() << "[WARNING] " << logstr << endl;
}
void logger::error(const char* logstr)
{
	cout << _time.current_formatted() << "[RROR] " << logstr << endl;
}
void logger::critical(const char* logstr)
{
	cout << _time.current_formatted() << "[CRITICAL] " << logstr << endl;
}
void logger::alert(const char* logstr)
{
	cout << _time.current_formatted() << "[ALERT] " << logstr << endl;
}
void logger::emerg(const char* logstr)
{
	cout << _time.current_formatted() << "[EMERGENCY] " << logstr << endl;
}
*/
} /* namespace log */
} /* namespace cossb */
<commit_msg>remove comment<commit_after>/*
 * logger.cpp
 *
 *  Created on: 2015. 8. 9.
 *      Author: hwang-linux
 */

#include "logger.hpp"
#include <iostream>
#include "interface/ilog.hpp"
#include "util/format.h"

namespace cossb {
namespace log {

logger::logger(){ }
logger::logger(interface::ilog* log):_logger(log) { }

logger::~logger() {
	_logger = nullptr;

}
void logger::log(const log::loglevel level, const char* str)
{
	log_base(level, str);
}

void logger::log_base(const loglevel level, const char* str)
{
	if(_logger)
	{
		switch(level)
		{
		case	loglevel::TRACE:	_logger->trace(str);	break;
		case	loglevel::DEBUG:	_logger->debug(str);	break;
		case	loglevel::INFO:	_logger->info(str);	break;
		case	loglevel::NOTICE: _logger->notice(str);	break;
		case	loglevel::WARN: _logger->warn(str);	break;
		case	loglevel::ERROR: _logger->error(str);	break;
		case	loglevel::CRITICAL: _logger->critical(str);	break;
		case	loglevel::ALERT: _logger->alert(str);	break;
		case	loglevel::EMERG: _logger->emerg(str);	break;
		}
	}
	else
	{
		switch(level)
		{
		case	loglevel::TRACE:	cout << "[TRACE]\t"	<< str << endl;	break;
		case	loglevel::DEBUG:	cout << "[DEBUG]\t"	<< str << endl;	break;
		case	loglevel::INFO:	cout << "[INFO]\t"	<< str << endl;	break;
		case	loglevel::NOTICE: cout << "[NOTICE]\t"	<< str << endl;	break;
		case	loglevel::WARN: cout << "[WARN]\t"	<< str << endl;	break;
		case	loglevel::ERROR: cout << "[ERROR]\t"	<< str << endl;	break;
		case	loglevel::CRITICAL: cout << "[CRITICAL]\t"	<< str << endl;	break;
		case	loglevel::ALERT: cout << "[ALERT]\t"	<< str << endl;	break;
		case	loglevel::EMERG: cout << "[EMERG]\t"	<< str << endl;	break;
		}
	}
}

void logger::adopt(interface::ilog* intlog)
{
	_logger = intlog;
}

} /* namespace log */
} /* namespace cossb */
<|endoftext|>


<commit_before>/// @author    Matei David, Ontario Institute for Cancer Research
/// @version   1.0
/// @date      2013-2015
/// @copyright MIT Public License
///
/// Logger mechanism.
///
/// Properties:
/// - thread-safe, non-garbled output (uses c++11's thread_local)
/// - customizable ostream sink. by default, uses std::clog
///
/// Exports:
/// - "LOG" macro (takes 1, 2, or 3 arguments, see below)
/// - "logger" namespace
/// - "logger::level" enum
/// - "logger::Logger" class
///
/// To use:
/// - In source code, use:
///
///     LOG(info) << "hello" << endl;
///     // or
///     LOG("main", info) << "hello" << endl;
///     // or
///     LOG("main", info, sink_os) << "hello" << endl;
///
///   Here, "main" is the facility (a string) and info is the message level.
///   Note that "logger" is a macro which knows how to look up the name info
///   inside logger namespace. The macro introduces C++ code equivalent to:
///
///     if (...message should be ignored...) then; else sink_os
///
///   NOTE: As with assert(), the code in the output stream following the
///   LOG() macro will ***not be executed*** if the log level of the
///   facility is higher than the level of the message.
///
/// - To set the default log level (for unspecified facilities):
///
///     logger::Logger::set_default_level(logger::Logger::level_from_string(s));
///
/// - To set the log level for the "main" facility:
///
///     logger::Logger::set_facility_level("main", logger::Logger::level_from_string(s));
///
/// - To parse a log facility level setting in the form "[<facility>:]<level>":
///
///     logger::Logger::set_level_from_option("alt:debug1", &cerr);
///
/// - By using these functions, one can set log levels using command-line
///   parameters and achieve dynamic log level settings without recompiling.

#ifndef __LOGGER_HPP
#define __LOGGER_HPP

#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
#include <mutex>

namespace logger
{

// log levels
enum level
{
    error = 0,
    warning,
    info,
    debug,
    debug1,
    debug2
};

class Logger
    : public std::ostringstream
{
public:
    // Constructor: initialize buffer.
    Logger(const std::string& facility, level msg_level,
           const std::string& file_name, unsigned line_num, const std::string& func_name,
           std::ostream& os = std::clog)
        : _os_p(&os)
    {
        *this << "= " << facility << "." << int(msg_level)
              << " " << file_name << ":" << line_num
              << " " << func_name << " ";
    }
    // Destructor: dump buffer to output.
    ~Logger()
    {
        _os_p->write(this->str().c_str(), this->str().size());
    }
    // Produce l-value for output chaining.
    std::ostream& l_value() { return *this; }

    // static methods for setting and getting facility log levels.
    static level get_default_level()
    {
        return default_level();
    }
    static void set_default_level(level l)
    {
        static std::mutex m;
        std::lock_guard< std::mutex > lg(m);
        default_level() = l;
    }
    static void set_default_level(int l)
    {
        set_default_level(get_level(l));
    }
    static void set_default_level(const std::string& s)
    {
        set_default_level(get_level(s));
    }
    static level get_facility_level(const std::string& facility)
    {
        return (facility_level_map().count(facility) > 0?
                facility_level_map().at(facility) : get_default_level());
    }
    static void set_facility_level(const std::string& facility, level l)
    {
        static std::mutex m;
        std::lock_guard< std::mutex > lg(m);
        facility_level_map()[facility] = l;
    }
    static void set_facility_level(const std::string& facility, int l)
    {
        set_facility_level(facility, get_level(l));
    }
    static void set_facility_level(const std::string& facility, const std::string& s)
    {
        set_facility_level(facility, get_level(s));
    }
    // static methods for setting log levels from command-line options
    static void set_level_from_option(const std::string& l, std::ostream* os_p = nullptr)
    {
        size_t i = l.find(':');
        if (i == std::string::npos)
        {
            set_default_level(l);
            if (os_p)
            {
                (*os_p) << "set default log level to: "
                        << static_cast< int >(Logger::get_default_level()) << std::endl;
            }
        }
        else
        {
            set_facility_level(l.substr(0, i), l.substr(i + 1));
            if (os_p)
            {
                (*os_p) << "set log level of '" << l.substr(0, i) << "' to: "
                        << static_cast< int >(Logger::get_facility_level(l.substr(0, i))) << std::endl;
            }
        }
    }
    static void set_levels_from_options(const std::vector< std::string >& v, std::ostream* os_p = nullptr)
    {
        for (const auto& l : v)
        {
            set_level_from_option(l, os_p);
        }
    }
    // public static utility functions (used by LOG macro)
    static level get_level(level l) { return l; }
    static level get_level(int i) { return static_cast< level >(i); }
    static level get_level(const std::string& s) { return level_from_string(s); }
    // public static member (used by LOG macro)
    static level& thread_local_last_level()
    {
        static thread_local level _last_level = error;
        return _last_level;
    }
private:
    // sink for this Logger object
    std::ostream* _os_p;

    // private static data members
    static level& default_level()
    {
        static level _default_level = error;
        return _default_level;
    }
    static std::map< std::string, level >& facility_level_map()
    {
        static std::map< std::string, level > _facility_level_map;
        return _facility_level_map;
    }
    // private static utility functions
    static level level_from_string(const std::string& s)
    {
        std::istringstream iss(s + "\n");
        int tmp_int = -1;
        iss >> tmp_int;
        if (iss.good())
        {
            return level(tmp_int);
        }
        else
        {
            if (s == "error") return logger::error;
            else if (s == "warning") return logger::warning;
            else if (s == "info") return logger::info;
            else if (s == "debug") return logger::debug;
            else if (s == "debug1") return logger::debug1;
            else if (s == "debug2") return logger::debug2;
            else
            {
                std::cerr << "could not parse log level: " << s << "\n";
                std::exit(1);
            }
        }
    }
}; // class Logger

} //namespace logger

#define __FILENAME__ (std::string(__FILE__).find('/') != std::string::npos? std::string(__FILE__).substr(std::string(__FILE__).rfind('/') + 1) : std::string(__FILE__))

/**
 * LOG macro
 *
 * Synopsis:
 *   LOG(facility, level_spec, sink) << message
 *   LOG(facility, level_spec) << message
 *   LOG(level_spec) << message
 *
 *   `facility`   : string
 *   `level_spec` : integer, string, or logger level
 *   `sink`       : sink ostream
 *
 * Log to `facility` at logger level `level_spec` and dump output to `sink`.
 * If sink is omitted, it defaults to std::clog.
 * If `facility` is omitted (logger has single argument), the macro LOG_FACILITY
 * is used instead, defaulting to "main".
 */

#define __LOG_3(facility, level_spec, sink)                                   \
    { using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
    if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
    else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__, sink).l_value()

#define __LOG_2(facility, level_spec)                                   \
    { using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
    if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
    else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__).l_value()

#define __LOG_1(level_spec) \
    __LOG_2(LOG_FACILITY, level_spec)

// we need 2-level indirection in order to trigger expansion after token pasting
// http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr
// http://stackoverflow.com/a/11763196/717706
#ifdef WIN32
#define __EXPAND(...) __VA_ARGS__
#define __LOG_aux2(N, ...) __EXPAND(__LOG_ ## N (__VA_ARGS__))
#else
#define __LOG_aux2(N, ...) __LOG_ ## N (__VA_ARGS__)
#endif

#define __LOG_aux1(N, ...) __LOG_aux2(N, __VA_ARGS__)

#define __NARGS_AUX(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9

#ifdef WIN32
#define __NARGS(...) __EXPAND(__NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0))
#else
#define __NARGS(...) __NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0)
#endif

#ifndef LOG_FACILITY
#define LOG_FACILITY "main"
#endif

#define LOG(...) __LOG_aux1(__NARGS(__VA_ARGS__), __VA_ARGS__)

#endif

#ifdef SAMPLE_LOGGER

/*

Compile:

g++ -std=c++11 -D SAMPLE_LOGGER -x c++ logger.hpp -o sample-logger

Run:
./sample-logger info
./sample-logger info alt:debug1

*/

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Use: " << argv[0] << " <log_level_setting> ..." << endl
             << "The program sends 5 log messages with decreasing priority (0=highest, 4=lowest)" << endl
             << "to 2 facilities \"main\" and \"alt\". Command-line arguments are interpreted as" << endl
             << "log facility level settings in the form [<facility>:]<level>." << endl;
        return EXIT_FAILURE;
    }
    for (int i = 1; i < argc; ++i)
    {
        cerr << "processing argument [" << argv[i] << "]" << endl;
        logger::Logger::set_level_from_option(argv[i], &cerr);
    }
    const vector< string > level_name{ "error", "warning", "info", "debug", "debug1", "debug2" };
    for (int l = 0; l < 5; ++l)
    {
        LOG(level_name[l]) << "message at level " << l << " (" << level_name[l]
                           << ") for facility main" << endl;
        LOG("alt", l) << "message at level " << l << " (" << level_name[l]
                      << ") for facility alt" << endl;
    }
}

#endif
<commit_msg>added LOG_ABORT and LOG_EXIT<commit_after>/// @author    Matei David, Ontario Institute for Cancer Research
/// @version   1.0
/// @date      2013-2015
/// @copyright MIT Public License
///
/// Logger mechanism.
///
/// Properties:
/// - thread-safe, non-garbled output (uses c++11's thread_local)
/// - customizable ostream sink. by default, uses std::clog
///
/// Exports:
/// - "LOG" macro (takes 1, 2, or 3 arguments, see below)
/// - "logger" namespace
/// - "logger::level" enum
/// - "logger::Logger" class
///
/// To use:
/// - In source code, use:
///
///     LOG(info) << "hello" << endl;
///     // or
///     LOG("main", info) << "hello" << endl;
///     // or
///     LOG("main", info, sink_os) << "hello" << endl;
///
///   Here, "main" is the facility (a string) and info is the message level.
///   Note that "logger" is a macro which knows how to look up the name info
///   inside logger namespace. The macro introduces C++ code equivalent to:
///
///     if (...message should be ignored...) then; else sink_os
///
///   NOTE: As with assert(), the code in the output stream following the
///   LOG() macro will ***not be executed*** if the log level of the
///   facility is higher than the level of the message.
///
/// - To set the default log level (for unspecified facilities):
///
///     logger::Logger::set_default_level(logger::Logger::level_from_string(s));
///
/// - To set the log level for the "main" facility:
///
///     logger::Logger::set_facility_level("main", logger::Logger::level_from_string(s));
///
/// - To parse a log facility level setting in the form "[<facility>:]<level>":
///
///     logger::Logger::set_level_from_option("alt:debug1", &cerr);
///
/// - By using these functions, one can set log levels using command-line
///   parameters and achieve dynamic log level settings without recompiling.

#ifndef __LOGGER_HPP
#define __LOGGER_HPP

#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
#include <mutex>

namespace logger
{

// log levels
enum level
{
    error = 0,
    warning,
    info,
    debug,
    debug1,
    debug2
};

class Logger
    : public std::ostringstream
{
public:
    // Constructor: initialize buffer.
    Logger(const std::string& facility, level msg_level,
           const std::string& file_name, unsigned line_num, const std::string& func_name,
           std::ostream& os = std::clog)
        : _os_p(&os), _policy(0)
    {
        *this << "= " << facility << "." << int(msg_level)
              << " " << file_name << ":" << line_num
              << " " << func_name << " ";
    }
    Logger(int policy, const std::string& file_name, unsigned line_num, const std::string& func_name,
           std::ostream& os = std::cerr)
        : _os_p(&os), _policy(policy)
    {
        *this << "= main." << int(error)
              << " " << file_name << ":" << line_num
              << " " << func_name << " ";
    }
    // Destructor: dump buffer to output.
    ~Logger()
    {
        _os_p->write(this->str().c_str(), this->str().size());
        if (_policy < 0) std::abort();
        if (_policy > 0) std::exit(_policy);
    }
    // Produce l-value for output chaining.
    std::ostream& l_value() { return *this; }

    // static methods for setting and getting facility log levels.
    static level get_default_level()
    {
        return default_level();
    }
    static void set_default_level(level l)
    {
        static std::mutex m;
        std::lock_guard< std::mutex > lg(m);
        default_level() = l;
    }
    static void set_default_level(int l)
    {
        set_default_level(get_level(l));
    }
    static void set_default_level(const std::string& s)
    {
        set_default_level(get_level(s));
    }
    static level get_facility_level(const std::string& facility)
    {
        return (facility_level_map().count(facility) > 0?
                facility_level_map().at(facility) : get_default_level());
    }
    static void set_facility_level(const std::string& facility, level l)
    {
        static std::mutex m;
        std::lock_guard< std::mutex > lg(m);
        facility_level_map()[facility] = l;
    }
    static void set_facility_level(const std::string& facility, int l)
    {
        set_facility_level(facility, get_level(l));
    }
    static void set_facility_level(const std::string& facility, const std::string& s)
    {
        set_facility_level(facility, get_level(s));
    }
    // static methods for setting log levels from command-line options
    static void set_level_from_option(const std::string& l, std::ostream* os_p = nullptr)
    {
        size_t i = l.find(':');
        if (i == std::string::npos)
        {
            set_default_level(l);
            if (os_p)
            {
                (*os_p) << "set default log level to: "
                        << static_cast< int >(Logger::get_default_level()) << std::endl;
            }
        }
        else
        {
            set_facility_level(l.substr(0, i), l.substr(i + 1));
            if (os_p)
            {
                (*os_p) << "set log level of '" << l.substr(0, i) << "' to: "
                        << static_cast< int >(Logger::get_facility_level(l.substr(0, i))) << std::endl;
            }
        }
    }
    static void set_levels_from_options(const std::vector< std::string >& v, std::ostream* os_p = nullptr)
    {
        for (const auto& l : v)
        {
            set_level_from_option(l, os_p);
        }
    }
    // public static utility functions (used by LOG macro)
    static level get_level(level l) { return l; }
    static level get_level(int i) { return static_cast< level >(i); }
    static level get_level(const std::string& s) { return level_from_string(s); }
    // public static member (used by LOG macro)
    static level& thread_local_last_level()
    {
        static thread_local level _last_level = error;
        return _last_level;
    }
private:
    // sink for this Logger object
    std::ostream* _os_p;
    int _policy;

    // private static data members
    static level& default_level()
    {
        static level _default_level = error;
        return _default_level;
    }
    static std::map< std::string, level >& facility_level_map()
    {
        static std::map< std::string, level > _facility_level_map;
        return _facility_level_map;
    }
    // private static utility functions
    static level level_from_string(const std::string& s)
    {
        std::istringstream iss(s + "\n");
        int tmp_int = -1;
        iss >> tmp_int;
        if (iss.good())
        {
            return level(tmp_int);
        }
        else
        {
            if (s == "error") return logger::error;
            else if (s == "warning") return logger::warning;
            else if (s == "info") return logger::info;
            else if (s == "debug") return logger::debug;
            else if (s == "debug1") return logger::debug1;
            else if (s == "debug2") return logger::debug2;
            else
            {
                std::cerr << "could not parse log level: " << s << "\n";
                std::exit(1);
            }
        }
    }
}; // class Logger

} //namespace logger

#define __FILENAME__ (std::string(__FILE__).find('/') != std::string::npos? std::string(__FILE__).substr(std::string(__FILE__).rfind('/') + 1) : std::string(__FILE__))

/**
 * LOG macro
 *
 * Synopsis:
 *   LOG(facility, level_spec, sink) << message
 *   LOG(facility, level_spec) << message
 *   LOG(level_spec) << message
 *
 *   `facility`   : string
 *   `level_spec` : integer, string, or logger level
 *   `sink`       : sink ostream
 *
 * Log to `facility` at logger level `level_spec` and dump output to `sink`.
 * If sink is omitted, it defaults to std::clog.
 * If `facility` is omitted (logger has single argument), the macro LOG_FACILITY
 * is used instead, defaulting to "main".
 */

#define __LOG_3(facility, level_spec, sink)                                   \
    { using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
    if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
    else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__, sink).l_value()

#define __LOG_2(facility, level_spec)                                   \
    { using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
    if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
    else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__).l_value()

#define __LOG_1(level_spec) \
    __LOG_2(LOG_FACILITY, level_spec)

// we need 2-level indirection in order to trigger expansion after token pasting
// http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr
// http://stackoverflow.com/a/11763196/717706
#ifdef WIN32
#define __EXPAND(...) __VA_ARGS__
#define __LOG_aux2(N, ...) __EXPAND(__LOG_ ## N (__VA_ARGS__))
#else
#define __LOG_aux2(N, ...) __LOG_ ## N (__VA_ARGS__)
#endif

#define __LOG_aux1(N, ...) __LOG_aux2(N, __VA_ARGS__)

#define __NARGS_AUX(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9

#ifdef WIN32
#define __NARGS(...) __EXPAND(__NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0))
#else
#define __NARGS(...) __NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0)
#endif

#ifndef LOG_FACILITY
#define LOG_FACILITY "main"
#endif

#define LOG(...) __LOG_aux1(__NARGS(__VA_ARGS__), __VA_ARGS__)
#define LOG_EXITCODE(c) logger::Logger((c), __FILENAME__, __LINE__, __func__).l_value()
#define LOG_ABORT LOG_EXITCODE(-1)
#define LOG_EXIT LOG_EXITCODE(EXIT_FAILURE)

#endif

#ifdef SAMPLE_LOGGER

/*

Compile:

g++ -std=c++11 -D SAMPLE_LOGGER -x c++ logger.hpp -o sample-logger

Run:
./sample-logger info
./sample-logger info alt:debug1

*/

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Use: " << argv[0] << " <log_level_setting> ..." << endl
             << "The program sends 5 log messages with decreasing priority (0=highest, 4=lowest)" << endl
             << "to 2 facilities \"main\" and \"alt\". Command-line arguments are interpreted as" << endl
             << "log facility level settings in the form [<facility>:]<level>." << endl;
        return EXIT_FAILURE;
    }
    for (int i = 1; i < argc; ++i)
    {
        cerr << "processing argument [" << argv[i] << "]" << endl;
        logger::Logger::set_level_from_option(argv[i], &cerr);
    }
    const vector< string > level_name{ "error", "warning", "info", "debug", "debug1", "debug2" };
    for (int l = 0; l < 5; ++l)
    {
        LOG(level_name[l]) << "message at level " << l << " (" << level_name[l]
                           << ") for facility main" << endl;
        LOG("alt", l) << "message at level " << l << " (" << level_name[l]
                      << ") for facility alt" << endl;
    }
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

class Matrix
{
private:
	int **matr;
	int st, cl;

public:
	Matrix();
	Matrix(int, int);
	Matrix(Matrix const &matrc);
	~Matrix();
	int rows()const;
	int columns()const;
	Matrix operator+ (const Matrix &mat_2) const;
	Matrix operator* (const Matrix &mat_2) const;
	Matrix& operator =(Matrix &);
	bool operator==(const Matrix&)const;
	friend istream& operator >> (istream& ist, Matrix& cmatr);
	friend ostream& operator << (ostream&, const Matrix&);
};
<commit_msg>Update matrix.hpp<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

class Matrix
{
private:
	int **matr;
	int st, cl;

public:
	Matrix();
	Matrix(int, int);
	Matrix(const Matrix &matrc);
	~Matrix();
	int rows()const;
	int columns()const;
	Matrix operator+ (const Matrix &mat_2) const;
	Matrix operator* (const Matrix &mat_2) const;
	Matrix& operator =(Matrix &);
	bool operator==(const Matrix&)const;
	friend istream& operator >> (istream& ist, Matrix& cmatr);
	friend ostream& operator << (ostream&, const Matrix&);
};
<|endoftext|>


<commit_before>// Converts tree.json to data.csv and tree.newick for https://github.com/acorg/isig

#include "acmacs-base/data-formatter.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/enumerate.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "signature-page/tree.hh"
#include "signature-page/tree-export.hh"

// ----------------------------------------------------------------------

const size_t sBjornPos[] = {145, 155, 156, 158, 159, 189, 193};

int main(int argc, const char* const* argv)
{
    int exit_code = 0;
    if (argc == 5) {
        std::string source_tree_file = argv[1];
        std::string source_chart = argv[2];
        std::string target_csv = argv[3];
        std::string target_tree_file = argv[4];

        const auto seqdb = seqdb::get();
        Tree tree;
        tree_import(source_tree_file, tree);
          // tree.match_seqdb(seqdb);

        auto chart = acmacs::chart::import_from_file(source_chart); // , acmacs::chart::Verify::None, report_time::No
        auto antigens = chart->antigens();
        const auto per_antigen = seqdb.match(*antigens, chart->info()->virus_type());

          // data.csv: no,map_x,map_y,date,antigen name,bjorn-145,155,156,158,159,189,193
        auto layout = chart->projection(0)->layout();
        const auto number_of_dimensions = layout->number_of_dimensions();
        std::string data_csv;
        using DF = acmacs::DataFormatterCSV;
        size_t antigens_in_tree = 0;
        for (auto [ag_no, antigen] : acmacs::enumerate(*antigens)) {
            DF::first_field(data_csv, ag_no);
            for (auto dim : acmacs::range(number_of_dimensions))
                DF::second_field(data_csv, (*layout)(ag_no, dim));
            DF::second_field(data_csv, antigen->date());
            DF::second_field(data_csv, antigen->full_name());
            const auto& entry = per_antigen[ag_no];
            if (entry) {
                // std::cout << "entry " << entry.entry().name() << " -- " << antigen->full_name() << '\n';
                const auto seq = entry.seq().amino_acids(true);
                for (auto bp : sBjornPos)
                    DF::second_field(data_csv, seq[bp - 1]);
                if (auto node = tree.find_leaf_by_seqid(entry.seq_id(seqdb::SeqdbEntrySeq::encoded_t::yes)); node) {
                      // std::cout << ag_no << ' ' << node->seq_id << '\n';
                    node->seq_id = "s-" + std::to_string(ag_no); // rename node according to isig spec
                    ++antigens_in_tree;
                }
            }
            else {
                for ([[maybe_unused ]] auto bp : sBjornPos)
                    DF::second_field(data_csv, "");
            }
            DF::end_of_record(data_csv);
        }
        acmacs::file::write(target_csv, data_csv);
        std::cerr << "INFO: antigens of chart found in the tree: " << antigens_in_tree << '\n';

          // rename rest of tree nodes
        size_t tree_node_id = layout->number_of_points();

        tree_export_to_json(target_tree_file, tree, 2);
    }
    else {
        std::cerr << "Usage: " << argv[0] << " tree.json[.xz] chart.ace data.csv tree.newick\n";
        exit_code = 1;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>make-isig development<commit_after>// Converts tree.json to data.csv and tree.newick for https://github.com/acorg/isig

#include "acmacs-base/data-formatter.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/enumerate.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "signature-page/tree.hh"
#include "signature-page/tree-export.hh"
#include "signature-page/tree-iterate.hh"

// ----------------------------------------------------------------------

const size_t sBjornPos[] = {145, 155, 156, 158, 159, 189, 193};

int main(int argc, const char* const* argv)
{
    int exit_code = 0;
    if (argc == 5) {
        std::string source_tree_file = argv[1];
        std::string source_chart = argv[2];
        std::string target_csv = argv[3];
        std::string target_tree_file = argv[4];

        const auto seqdb = seqdb::get();
        Tree tree;
        tree_import(source_tree_file, tree);
          // tree.match_seqdb(seqdb);

        auto chart = acmacs::chart::import_from_file(source_chart); // , acmacs::chart::Verify::None, report_time::No
        auto antigens = chart->antigens();
        const auto per_antigen = seqdb.match(*antigens, chart->info()->virus_type());

          // data.csv: no,map_x,map_y,date,antigen name,bjorn-145,155,156,158,159,189,193
        auto layout = chart->projection(0)->layout();
        const auto number_of_dimensions = layout->number_of_dimensions();
        std::string data_csv;
        using DF = acmacs::DataFormatterCSV;
        size_t antigens_in_tree = 0;
        for (auto [ag_no, antigen] : acmacs::enumerate(*antigens)) {
            DF::first_field(data_csv, ag_no);
            for (auto dim : acmacs::range(number_of_dimensions))
                DF::second_field(data_csv, (*layout)(ag_no, dim));
            DF::second_field(data_csv, antigen->date());
            DF::second_field(data_csv, antigen->full_name());
            const auto& entry = per_antigen[ag_no];
            if (entry) {
                // std::cout << "entry " << entry.entry().name() << " -- " << antigen->full_name() << '\n';
                const auto seq = entry.seq().amino_acids(true);
                for (auto bp : sBjornPos)
                    DF::second_field(data_csv, seq[bp - 1]);
                if (auto node = tree.find_leaf_by_seqid(entry.seq_id(seqdb::SeqdbEntrySeq::encoded_t::yes)); node) {
                      // std::cout << ag_no << ' ' << node->seq_id << '\n';
                    node->seq_id = "s-" + std::to_string(ag_no); // rename node according to isig spec
                    ++antigens_in_tree;
                }
            }
            else {
                for ([[maybe_unused ]] auto bp : sBjornPos)
                    DF::second_field(data_csv, "");
            }
            DF::end_of_record(data_csv);
        }
        acmacs::file::write(target_csv, data_csv);
        std::cerr << "INFO: antigens of chart found in the tree: " << antigens_in_tree << '\n';

          // rename rest of tree nodes
        size_t tree_node_id = layout->number_of_points();
        tree::iterate_leaf(tree, [&tree_node_id](Node& node) {
            if (node.seq_id.substr(0, 2) != "s-")
                node.seq_id = "s-" + std::to_string(++tree_node_id);
        });

        tree_export_to_json(target_tree_file, tree, 2);
    }
    else {
        std::cerr << "Usage: " << argv[0] << " tree.json[.xz] chart.ace data.csv tree.newick\n";
        exit_code = 1;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include "../util/string_piece.hh"
#include "../util/murmur_hash.hh"
#include "util/string_piece.hh"  //Tokenization and work with StringPiece
#include "util/tokenize_piece.hh"
#include <vector>

//Gets the MurmurmurHash for give string
uint64_t getHash(StringPiece text);

std::vector<uint64_t> getVocabIDs(StringPiece textin);

uint64_t getVocabID(std::string candidate);<commit_msg>Include hash only once<commit_after>#pragma once

#include "../util/string_piece.hh"
#include "../util/murmur_hash.hh"
#include "util/string_piece.hh"  //Tokenization and work with StringPiece
#include "util/tokenize_piece.hh"
#include <vector>

//Gets the MurmurmurHash for give string
uint64_t getHash(StringPiece text);

std::vector<uint64_t> getVocabIDs(StringPiece textin);

uint64_t getVocabID(std::string candidate);<|endoftext|>


<commit_before>#include "bob.h"
#include <algorithm>
#include <cctype>
#include <iterator>

using namespace std;

namespace bob
{
namespace
{

bool is_upper(string const& text)
{
    auto last = end(text);
    auto it = find_if_not(begin(text), last,
        [](char c) { return c == toupper(c); });
    return it == last;
}

bool has_alpha(string const& text)
{
    auto last = end(text);
    auto it = find_if(begin(text), last, [](char c) { return isalpha(c) != 0; });
    return it != last;
}

string trim(string const& text)
{
    auto first = text.find_first_not_of(' ');
    if (first == string::npos) {
        return string{};
    }
    auto last = text.find_last_not_of(' ');
    return string(&text[first], &text[last]);
}

bool is_shouting(string const &text)
{
    return is_upper(text) && has_alpha(text);
}

bool is_question(string const &text)
{
    return text.back() == '?';
}

bool is_silence(string const& text)
{
    return trim(text).length() == 0;
}

}

string hey(string const& text)
{
    if (is_silence(text)) {
        return "Fine. Be that way!";
    }
    if (is_shouting(text)) {
        return "Woah, chill out!";
    }
    if (is_question(text)) {
        return "Sure.";
    }
    return "Whatever.";
}

}
<commit_msg>Use boost::algorithm::trim_copy<commit_after>#include "bob.h"
#include <boost/algorithm/string/trim.hpp>
#include <algorithm>
#include <cctype>
#include <iterator>

using namespace std;

namespace bob
{
namespace
{

bool is_upper(string const& text)
{
    auto last = end(text);
    auto it = find_if_not(begin(text), last,
        [](char c) { return c == toupper(c); });
    return it == last;
}

bool has_alpha(string const& text)
{
    auto last = end(text);
    auto it = find_if(begin(text), last, [](char c) { return isalpha(c) != 0; });
    return it != last;
}

bool is_shouting(string const &text)
{
    return is_upper(text) && has_alpha(text);
}

bool is_question(string const &text)
{
    return text.back() == '?';
}

bool is_silence(string const& text)
{
    return boost::algorithm::trim_copy(text).length() == 0;
}

}

string hey(string const& text)
{
    if (is_silence(text)) {
        return "Fine. Be that way!";
    }
    if (is_shouting(text)) {
        return "Woah, chill out!";
    }
    if (is_question(text)) {
        return "Sure.";
    }
    return "Whatever.";
}

}
<|endoftext|>


<commit_before>///
///@Author  PEZY
///@Date    Aug. 2014
///@Brief
/// print the size and contents of the vectors from exercise 3.13.
/// Check whether your answers to that exercise were correct.
/// If not, restudy § 3.3.1 (p. 97) until you understand why you were wrong.
///

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using std::string;
using std::cout;
using std::endl;

int main()
{
  vector<int> v1;
  cout << "{\n \"v1\":{\"size\":\"" << v1.size() << "\",\"value\":[";
  for (auto i : v1)
    cout << i << ",";
  if (!v1.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<int> v2(10);
  cout << " \"v2\":{\"size\":\"" << v2.size() << "\",\"value\":[";
  for (auto i : v2)
    cout << i << ",";
  if (!v2.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<int> v3(10, 42);
  cout << " \"v3\":{\"size\":\"" << v3.size() << "\",\"value\":[";
  for (auto i : v3)
    cout << i << ",";
  if (!v3.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<int> v4{10};
  cout << " \"v4\":{\"size\":\"" << v4.size() << "\",\"value\":[";
  for (auto i : v4)
    cout << i << ",";
  if (!v4.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<int> v5{10, 42};
  cout << " \"v5\":{\"size\":\"" << v5.size() << "\",\"value\":[";
  for (auto i : v5)
    cout << i << ",";
  if (!v5.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<string> v6{10};
  cout << " \"v6\":{\"size\":\"" << v6.size() << "\",\"value\":[";
  for (auto i : v6)
    if (i.empty()) cout << "(null)" << ",";
    else cout << i << ",";
  if (!v6.empty()) cout << "\b";
  cout << "]}" << endl;

  vector<string> v7{10, "hi"};
  cout << " \"v7\":{\"size\":\"" << v7.size() << "\",\"value\":[";
  for (auto i : v7)
    if (i.empty()) cout << "(null)" << ",";
    else cout << i << ",";
  if (!v7.empty()) cout << "\b";
  cout << "]}\n}" << endl;

  return 0;
}

///
///@Output(JSON-like format)
///{
/// "v1":{"size":"0","value":[]}
/// "v2":{"size":"10","value":[0,0,0,0,0,0,0,0,0,0]}
/// "v3":{"size":"10","value":[42,42,42,42,42,42,42,42,42,42]}
/// "v4":{"size":"1","value":[10]}
/// "v5":{"size":"2","value":[10,42]}
/// "v6":{"size":"10","value":[(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)]}
/// "v7":{"size":"10","value":[hi,hi,hi,hi,hi,hi,hi,hi,hi,hi]}
///}
///
<commit_msg>Update ex3_16.cpp<commit_after>///
///@Author  PEZY
///@Date    Aug. 2014
///@Brief
/// print the size and contents of the vectors from exercise 3.13.
/// Check whether your answers to that exercise were correct.
/// If not, restudy § 3.3.1 (p. 97) until you understand why you were wrong.
///

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using std::string;
using std::cout;
using std::endl;

int main()
{
    vector<int> v1;
    cout << "{\n \"v1\":{\"size\":\"" << v1.size() << "\",\"value\":[";
    for (auto i : v1)
        cout << i << ",";
    if (!v1.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v2(10);
    cout << " \"v2\":{\"size\":\"" << v2.size() << "\",\"value\":[";
    for (auto i : v2)
        cout << i << ",";
    if (!v2.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v3(10, 42);
    cout << " \"v3\":{\"size\":\"" << v3.size() << "\",\"value\":[";
    for (auto i : v3)
        cout << i << ",";
    if (!v3.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v4{ 10 };
    cout << " \"v4\":{\"size\":\"" << v4.size() << "\",\"value\":[";
    for (auto i : v4)
        cout << i << ",";
    if (!v4.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v5{ 10, 42 };
    cout << " \"v5\":{\"size\":\"" << v5.size() << "\",\"value\":[";
    for (auto i : v5)
        cout << i << ",";
    if (!v5.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<string> v6{ 10 };
    cout << " \"v6\":{\"size\":\"" << v6.size() << "\",\"value\":[";
    for (auto i : v6)
        if (i.empty()) cout << "(null)" << ",";
        else cout << i << ",";
        if (!v6.empty()) cout << "\b";
        cout << "]}" << endl;

        vector<string> v7{ 10, "hi" };
        cout << " \"v7\":{\"size\":\"" << v7.size() << "\",\"value\":[";
        for (auto i : v7)
            if (i.empty()) cout << "(null)" << ",";
            else cout << i << ",";
            if (!v7.empty()) cout << "\b";
            cout << "]}\n}" << endl;

            return 0;
}

///
///@Output(JSON-like format)
///{
/// "v1":{"size":"0","value":[]}
/// "v2":{"size":"10","value":[0,0,0,0,0,0,0,0,0,0]}
/// "v3":{"size":"10","value":[42,42,42,42,42,42,42,42,42,42]}
/// "v4":{"size":"1","value":[10]}
/// "v5":{"size":"2","value":[10,42]}
/// "v6":{"size":"10","value":[(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)]}
/// "v7":{"size":"10","value":[hi,hi,hi,hi,hi,hi,hi,hi,hi,hi]}
///}
///
<|endoftext|>


<commit_before><commit_msg>ex5_25<commit_after>#include <iostream>
#include <stdexcept>

using namespace std;

int main(void)
{
	int a, b;
	cout << "Enter two numbers :" << endl;

	while (cin >> a >> b)
	{
		try{
			if (b == 0)
				throw runtime_error("divisor is 0");
			cout << static_cast<double>(a) / b << endl;
			break;
		}
		catch (runtime_error err){
			cout << err.what()
				<< "\nTry again ? Enter y or n" << endl;
			char c;
			cin >> c;
			if (!cin || c == 'n')
				break;
			else
			{
				cout << "Enter two numbers :" << endl;
			}
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>//!@Yue Wang
//!
//! Exercise 6.12:
//! Rewrite the program from exercise 6.10 in § 6.2.1 (p. 210) to use
//! references instead of pointers to swap the values of two ints. Which
//! version do you think would be easier to use and why?
//  The version using reference is easier.
//!
#include <iostream>

void swap(int& lhs, int& rhs)
{
    int temp = lhs;
    lhs = rhs;
    rhs = temp;
}

int main()
{
    for (int left, right;
         std::cout << "Please Enter:\n", std::cin >> left >> right;) {
        swap(left, right);
        std::cout << left << " " << right << std::endl;
    }

    return 0;
}
<commit_msg>Update ex6_12.cpp<commit_after>//!@Yue Wang
//!
//! Exercise 6.12:
//! Rewrite the program from exercise 6.10 in § 6.2.1 (p. 210) to use
//! references instead of pointers to swap the values of two ints. Which
//! version do you think would be easier to use and why?
//  The version using references is easier.
//!
#include <iostream>

void swap(int& lhs, int& rhs)
{
    int temp = lhs;
    lhs = rhs;
    rhs = temp;
}

int main()
{
    for (int left, right;
         std::cout << "Please Enter:\n", std::cin >> left >> right;) {
        swap(left, right);
        std::cout << left << " " << right << std::endl;
    }

    return 0;
}
<|endoftext|>