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

#include "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

/**
* Add-on namespace.
*/
namespace addon_strided_add {

	/**
	* Adds two doubles.
	*
	* @private
	* @param x  first double
	* @param y  second double
	* @return   sum
	*/
	double add( double x, double y ) {
		return x + y;
	}

	/**
	* Returns a typed array data type.
	*
	* @private
	* @param vtype  typed array type
	* @return       data type
	*/
	enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
		if ( vtype == napi_float64_array ) {
			return STDLIB_NDARRAY_FLOAT64;
		}
		if ( vtype == napi_float32_array ) {
			return STDLIB_NDARRAY_FLOAT32;
		}
		if ( vtype == napi_int32_array ) {
			return STDLIB_NDARRAY_INT32;
		}
		if ( vtype == napi_uint32_array ) {
			return STDLIB_NDARRAY_UINT32;
		}
		if ( vtype == napi_int16_array ) {
			return STDLIB_NDARRAY_INT16;
		}
		if ( vtype == napi_uint16_array ) {
			return STDLIB_NDARRAY_UINT16;
		}
		if ( vtype == napi_int8_array ) {
			return STDLIB_NDARRAY_INT8;
		}
		if ( vtype == napi_uint8_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		if ( vtype == napi_uint8_clamped_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		// FIXME: handle BigInt64Array and BigUint64Array
	}

	/**
	* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
	*
	* ## Notes
	*
	* -   The function assumes the following argument order:
	*
	*     ```text
	*     [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
	*     ```
	*
	*     where
	*
	*     -   `N` is the number of elements over which to iterate
	*     -   `ia#` is an input strided array
	*     -   `is#` is a corresponding input strided array stride (in units of elements)
	*     -   `oa#` is an output strided array
	*     -   `os#` is a corresponding output strided array stride (in units of elements)
	*
	* -   We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
	*
	* @private
	* @param env      environment
	* @param info     arguments
	* @param nargs    total number of expected arguments
	* @param nin      number of input strided array arguments
	* @param nout     number of output strided array arguments
	* @param arrays   destination array containing pointers to both input and output strided byte arrays
	* @param shape    destination array containing the array shape (dimensions)
	* @param strides  destination array containing array strides (in bytes) for each strided array
	* @param types    destination array containing strided array argument data types
	* @throws         must provide expected number of input arguments
	* @throws         stride arguments must be numbers
	* @throws         input strided array arguments must be either typed arrays or scalars
	* @throws         output strided array arguments must be typed arrays
	* @throws         must provide at least one input strided array
	* @return         number of scalar strided "array" arguments
	*/
	int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
		napi_status status;
		int64_t i;
		int64_t j;

		// Compute the index of the first output strided array argument:
		int64_t iout = ( nin*2 ) + 1;

		// Initialize variables used to track scalar input arguments:
		int64_t nsargs = 0;
		int64_t sargs = 0;

		// Get callback arguments:
		size_t argc = 7;
		napi_value argv[ 7 ];
		status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
		assert( status == napi_ok );

		if ( (int64_t)argc != nargs ) {
			napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
			return -1;
		}

		// The first argument is always the number of elements over which to iterate...
		napi_valuetype vtype0;
		status = napi_typeof( env, argv[ 0 ], &vtype0 );
		assert( status == napi_ok );
		if ( vtype0 != napi_number ) {
			napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
			return -1;
		}

		// Retrieve the number of elements:
		int64_t N;
		status = napi_get_value_int64( env, argv[ 0 ], &N );
		assert( status == napi_ok );

		shape[ 0 ] = N;

		// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
		for ( i = 2; i < nargs; i += 2 ) {
			napi_valuetype vtype;
			status = napi_typeof( env, argv[ i ], &vtype );
			assert( status == napi_ok );
			if ( vtype != napi_number ) {
				napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
				return -1;
			}

			int64_t stride;
			status = napi_get_value_int64( env, argv[ i ], &stride );
			assert( status == napi_ok );

			j = ( i-2 ) / 2;
			strides[ j ] = stride;
		}

		// Input strided array arguments are every other argument beginning from the second argument...
		for ( i = 1; i < iout; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				double v;
				status = napi_get_value_double( env, argv[ i ], &v );
				if ( status != napi_ok ) {
					napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
					return -1;
				}
				sargs |= (1<<j);
				nsargs += 1;
			}
		}

		// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
		for ( i = iout; i < nargs; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
				return -1;
			}
		}

		// Check if we have been provided only scalar input arguments...
		if ( nin > 0 && nsargs == nin ) {
			napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
			return -1;
		}
		return nsargs;
	}

	/**
	* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
	*
	* ## Notes
	*
	* -   When called from JavaScript, the function expects the following arguments:
	*
	*     -   `N`: number of indexed elements
	*     -   `X`: input array (or scalar constant)
	*     -   `strideX`: `X` stride length
	*     -   `Y`: input array (or scalar constant)
	*     -   `strideY`: `Y` stride length
	*     -   `Z`: destination array
	*     -   `strideZ`: `Z` stride length
	*/
	napi_value node_add( napi_env env, napi_callback_info info ) {
		enum STDLIB_NDARRAY_DTYPE types[ 3 ];
		uint8_t *arrays[ 3 ];
		int64_t strides[ 3 ];
		int64_t shape[ 1 ];
		int64_t nsargs;
		int64_t nargs;
		int64_t nout;
		int64_t nin;

		// Total number of input arguments:
		nargs = 7;

		// Number of input and output strided array arguments:
		nin = 2;
		nout = 1;

		// Process the provided arguments:
		nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
		if ( nsargs < 0 ) {
			return nullptr;
		}

		// Broadcasting of scalar arguments...
		if ( nsargs > 0 ) {
			// FIXME
			// Create an array having the closest "compatible" type...
			// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
		}

		// Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):
		stdlib_strided_dd_d( arrays, shape, strides, (void *)add );

		return nullptr;
	}

	napi_value Init( napi_env env, napi_value exports ) {
		napi_status status;
		napi_value fcn;
		status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
		assert( status == napi_ok );
		return fcn;
	}

	NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<commit_msg>Resolve TODO item<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

/**
* Add-on namespace.
*/
namespace addon_strided_add {

	/**
	* Adds two doubles.
	*
	* @private
	* @param x  first double
	* @param y  second double
	* @return   sum
	*/
	double add( double x, double y ) {
		return x + y;
	}

	/**
	* Returns a typed array data type.
	*
	* @private
	* @param vtype  typed array type
	* @return       data type
	*/
	enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
		if ( vtype == napi_float64_array ) {
			return STDLIB_NDARRAY_FLOAT64;
		}
		if ( vtype == napi_float32_array ) {
			return STDLIB_NDARRAY_FLOAT32;
		}
		if ( vtype == napi_int32_array ) {
			return STDLIB_NDARRAY_INT32;
		}
		if ( vtype == napi_uint32_array ) {
			return STDLIB_NDARRAY_UINT32;
		}
		if ( vtype == napi_int16_array ) {
			return STDLIB_NDARRAY_INT16;
		}
		if ( vtype == napi_uint16_array ) {
			return STDLIB_NDARRAY_UINT16;
		}
		if ( vtype == napi_int8_array ) {
			return STDLIB_NDARRAY_INT8;
		}
		if ( vtype == napi_uint8_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		if ( vtype == napi_uint8_clamped_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		if ( vtype == napi_bigint64_array ) {
			return STDLIB_NDARRAY_INT64;
		}
		return STDLIB_NDARRAY_UINT64; // vtype == napi_biguint64_array
	}

	/**
	* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
	*
	* ## Notes
	*
	* -   The function assumes the following argument order:
	*
	*     ```text
	*     [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
	*     ```
	*
	*     where
	*
	*     -   `N` is the number of elements over which to iterate
	*     -   `ia#` is an input strided array
	*     -   `is#` is a corresponding input strided array stride (in units of elements)
	*     -   `oa#` is an output strided array
	*     -   `os#` is a corresponding output strided array stride (in units of elements)
	*
	* -   We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
	*
	* @private
	* @param env      environment
	* @param info     arguments
	* @param nargs    total number of expected arguments
	* @param nin      number of input strided array arguments
	* @param nout     number of output strided array arguments
	* @param arrays   destination array containing pointers to both input and output strided byte arrays
	* @param shape    destination array containing the array shape (dimensions)
	* @param strides  destination array containing array strides (in bytes) for each strided array
	* @param types    destination array containing strided array argument data types
	* @throws         must provide expected number of input arguments
	* @throws         stride arguments must be numbers
	* @throws         input strided array arguments must be either typed arrays or scalars
	* @throws         output strided array arguments must be typed arrays
	* @throws         must provide at least one input strided array
	* @return         number of scalar strided "array" arguments
	*/
	int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
		napi_status status;
		int64_t i;
		int64_t j;

		// Compute the index of the first output strided array argument:
		int64_t iout = ( nin*2 ) + 1;

		// Initialize variables used to track scalar input arguments:
		int64_t nsargs = 0;
		int64_t sargs = 0;

		// Get callback arguments:
		size_t argc = 7;
		napi_value argv[ 7 ];
		status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
		assert( status == napi_ok );

		if ( (int64_t)argc != nargs ) {
			napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
			return -1;
		}

		// The first argument is always the number of elements over which to iterate...
		napi_valuetype vtype0;
		status = napi_typeof( env, argv[ 0 ], &vtype0 );
		assert( status == napi_ok );
		if ( vtype0 != napi_number ) {
			napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
			return -1;
		}

		// Retrieve the number of elements:
		int64_t N;
		status = napi_get_value_int64( env, argv[ 0 ], &N );
		assert( status == napi_ok );

		shape[ 0 ] = N;

		// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
		for ( i = 2; i < nargs; i += 2 ) {
			napi_valuetype vtype;
			status = napi_typeof( env, argv[ i ], &vtype );
			assert( status == napi_ok );
			if ( vtype != napi_number ) {
				napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
				return -1;
			}

			int64_t stride;
			status = napi_get_value_int64( env, argv[ i ], &stride );
			assert( status == napi_ok );

			j = ( i-2 ) / 2;
			strides[ j ] = stride;
		}

		// Input strided array arguments are every other argument beginning from the second argument...
		for ( i = 1; i < iout; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				double v;
				status = napi_get_value_double( env, argv[ i ], &v );
				if ( status != napi_ok ) {
					napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
					return -1;
				}
				sargs |= (1<<j);
				nsargs += 1;
			}
		}

		// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
		for ( i = iout; i < nargs; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
				return -1;
			}
		}

		// Check if we have been provided only scalar input arguments...
		if ( nin > 0 && nsargs == nin ) {
			napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
			return -1;
		}
		return nsargs;
	}

	/**
	* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
	*
	* ## Notes
	*
	* -   When called from JavaScript, the function expects the following arguments:
	*
	*     -   `N`: number of indexed elements
	*     -   `X`: input array (or scalar constant)
	*     -   `strideX`: `X` stride length
	*     -   `Y`: input array (or scalar constant)
	*     -   `strideY`: `Y` stride length
	*     -   `Z`: destination array
	*     -   `strideZ`: `Z` stride length
	*/
	napi_value node_add( napi_env env, napi_callback_info info ) {
		enum STDLIB_NDARRAY_DTYPE types[ 3 ];
		uint8_t *arrays[ 3 ];
		int64_t strides[ 3 ];
		int64_t shape[ 1 ];
		int64_t nsargs;
		int64_t nargs;
		int64_t nout;
		int64_t nin;

		// Total number of input arguments:
		nargs = 7;

		// Number of input and output strided array arguments:
		nin = 2;
		nout = 1;

		// Process the provided arguments:
		nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
		if ( nsargs < 0 ) {
			return nullptr;
		}

		// Broadcasting of scalar arguments...
		if ( nsargs > 0 ) {
			// FIXME
			// Create an array having the closest "compatible" type...
			// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
		}

		// Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):
		stdlib_strided_dd_d( arrays, shape, strides, (void *)add );

		return nullptr;
	}

	napi_value Init( napi_env env, napi_value exports ) {
		napi_status status;
		napi_value fcn;
		status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
		assert( status == napi_ok );
		return fcn;
	}

	NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

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

#include "razorcpuload.h"
#include "razorcpuloadconfiguration.h"
#include <QtCore>
#include <QPainter>
#include <QLinearGradient>

extern "C" {
#include <statgrab.h>
}

EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorCpuLoad)

RazorCpuLoad::RazorCpuLoad(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
	RazorPanelPlugin(startInfo, parent),
	m_showText(false)
{
	setObjectName("CpuLoad");
	addWidget(&m_stuff);

	/* Initialise statgrab */
	sg_init();

	/* Drop setuid/setgid privileges. */
	if (sg_drop_privileges() != 0) {
		perror("Error. Failed to drop privileges");
	}

	m_font.setPointSizeF(8);
	startTimer(500);

	settigsChanged();
}

RazorCpuLoad::~RazorCpuLoad()
{
}

void RazorCpuLoad::resizeEvent(QResizeEvent *)
{
	if( panel()->isHorizontal() )
	{
		m_stuff.setMinimumWidth(m_stuff.height() * 0.5);
		m_stuff.setMinimumHeight(0);
	} else
	{
		m_stuff.setMinimumHeight(m_stuff.width() * 2.0);
		m_stuff.setMinimumWidth(0);
	}

	update();
}

double RazorCpuLoad::getLoadCpu() const
{
	sg_cpu_percents* cur = sg_get_cpu_percents();
	return (cur->user + cur->kernel + cur->nice);
}

void RazorCpuLoad::timerEvent(QTimerEvent *event)
{
	double avg = getLoadCpu();
	if ( qAbs(m_avg-avg)>1 )
	{
		m_avg = avg;
		setToolTip(tr("Cpu load %1%").arg(m_avg));
		update();
	}
}

void RazorCpuLoad::paintEvent ( QPaintEvent * )
{
	QPainter p(this);
	QPen pen;
	pen.setWidth(2);
	p.setPen(pen);
	p.setRenderHint(QPainter::Antialiasing, true);

	p.setFont(m_font);

	QLinearGradient shade(0, 0, width(), 0);
	shade.setSpread(QLinearGradient::ReflectSpread);
	shade.setColorAt(0, QColor(0, 196, 0, 128));
	shade.setColorAt(0.5, QColor(0, 128, 0, 255) );
	shade.setColorAt(1, QColor(0, 196, 0 , 128));

	QRectF r = rect();
	float o = r.height()*(1-m_avg*0.01);
	QRectF r1(r.left(), r.top()+o, r.width(), r.height()-o );
	p.fillRect(r1, shade);

	if( m_showText )
		p.drawText(rect(), Qt::AlignCenter, QString::number(m_avg));
}

void RazorCpuLoad::showConfigureDialog()
{
	RazorCpuLoadConfiguration *confWindow =
			this->findChild<RazorCpuLoadConfiguration*>("RazorCpuLoadConfigurationWindow");

	if (!confWindow)
	{
		confWindow = new RazorCpuLoadConfiguration(settings(), this);
	}

	confWindow->show();
	confWindow->raise();
	confWindow->activateWindow();
}

void RazorCpuLoad::settigsChanged()
{
	m_showText = settings().value("showText", false).toBool();
	update();
}

<commit_msg>Improve size of cpu monitor on change of pannel orientation.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

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

#include "razorcpuload.h"
#include "razorcpuloadconfiguration.h"
#include <QtCore>
#include <QPainter>
#include <QLinearGradient>

extern "C" {
#include <statgrab.h>
}

EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorCpuLoad)

RazorCpuLoad::RazorCpuLoad(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
	RazorPanelPlugin(startInfo, parent),
	m_showText(false)
{
	setObjectName("CpuLoad");
	addWidget(&m_stuff);

	/* Initialise statgrab */
	sg_init();

	/* Drop setuid/setgid privileges. */
	if (sg_drop_privileges() != 0) {
		perror("Error. Failed to drop privileges");
	}

	m_font.setPointSizeF(8);
	startTimer(500);

	settigsChanged();
}

RazorCpuLoad::~RazorCpuLoad()
{
}

void RazorCpuLoad::resizeEvent(QResizeEvent *)
{
	m_stuff.setMinimumWidth(18);
	m_stuff.setMaximumWidth(18);
	m_stuff.setMinimumHeight(24);

	update();
}

double RazorCpuLoad::getLoadCpu() const
{
	sg_cpu_percents* cur = sg_get_cpu_percents();
	return (cur->user + cur->kernel + cur->nice);
}

void RazorCpuLoad::timerEvent(QTimerEvent *event)
{
	double avg = getLoadCpu();
	if ( qAbs(m_avg-avg)>1 )
	{
		m_avg = avg;
		setToolTip(tr("Cpu load %1%").arg(m_avg));
		update();
	}
}

void RazorCpuLoad::paintEvent ( QPaintEvent * )
{
	QPainter p(this);
	QPen pen;
	pen.setWidth(2);
	p.setPen(pen);
	p.setRenderHint(QPainter::Antialiasing, true);
	const double w = 20;

	p.setFont(m_font);
	QRectF r = rect();

	float vo = r.height()*(1-m_avg*0.01);
	float ho = (r.width() - w )/2.0;
	QRectF r1(r.left()+ho, r.top()+vo, r.width()-2*ho, r.height()-vo );

	QLinearGradient shade(0, 0, r1.width(), 0);
	shade.setSpread(QLinearGradient::ReflectSpread);
	shade.setColorAt(0, QColor(0, 196, 0, 128));
	shade.setColorAt(0.5, QColor(0, 128, 0, 255) );
	shade.setColorAt(1, QColor(0, 196, 0 , 128));

	p.fillRect(r1, shade);

	if( m_showText )
		p.drawText(rect(), Qt::AlignCenter, QString::number(m_avg));
}

void RazorCpuLoad::showConfigureDialog()
{
	RazorCpuLoadConfiguration *confWindow =
			this->findChild<RazorCpuLoadConfiguration*>("RazorCpuLoadConfigurationWindow");

	if (!confWindow)
	{
		confWindow = new RazorCpuLoadConfiguration(settings(), this);
	}

	confWindow->show();
	confWindow->raise();
	confWindow->activateWindow();
}

void RazorCpuLoad::settigsChanged()
{
	m_showText = settings().value("showText", false).toBool();
	update();
}

<|endoftext|>


<commit_before>#include "vtkConditionVariable.h"
#include "vtkMultiThreader.h"

#include <stdlib.h>

// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>

// Cross platform sleep (horked from vtkGeoTerrain.cxx)
inline void vtkSleep( double duration )
{
  duration = duration; // avoid warnings
  // sleep according to OS preference
#ifdef _WIN32
  Sleep( (int)( 1000 * duration ) );
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
  struct timespec sleep_time, dummy;
  sleep_time.tv_sec = static_cast<int>( duration );
  sleep_time.tv_nsec = static_cast<int>( 1000000000 * ( duration - sleep_time.tv_sec ) );
  nanosleep( &sleep_time, &dummy );
#endif
}

typedef struct {
  vtkMutexLock* Lock;
  vtkConditionVariable* Condition;
  int Done;
  int NumberOfWorkers;
} vtkThreadUserData;

VTK_THREAD_RETURN_TYPE vtkTestCondVarThread( void* arg )
{
  int threadId = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->ThreadID;
  int threadCount = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->NumberOfThreads;
  vtkThreadUserData* td = static_cast<vtkThreadUserData*>(
    static_cast<vtkMultiThreader::ThreadInfo*>(arg)->UserData );
  if ( td )
    {
    if ( threadId == 0 )
      {
      td->Done = 0;
      td->Lock->Lock();
      cout << "Thread " << ( threadId + 1 ) << " of " << threadCount << " initializing.\n";
      cout.flush();
      td->Lock->Unlock();

      int i;
      for ( i = 0; i < 2 * threadCount; ++ i )
        {
        td->Lock->Lock();
        cout << "Signaling (count " << i << ")...\n";
        cout.flush();
        td->Lock->Unlock();
        td->Condition->Signal();

        //sleep( 1 );
        }

      i = 0;
      do
        {
        td->Lock->Lock();
        td->Done = 1;
        cout << "Broadcasting...\n";
        cout.flush();
        td->Lock->Unlock();
        td->Condition->Broadcast();
        vtkSleep( 0.2 ); // 0.2 s between broadcasts
        }
      while ( td->NumberOfWorkers > 0 && ( i ++ < 1000 ) );
      if ( i >= 1000 )
        {
        exit( 2 );
        }
      }
    else
      {
      // Wait for thread 0 to initialize... Ugly but effective
      while ( td->Done < 0 )
        {
        vtkSleep( 0.2 ); // 0.2 s between checking
        }

      // Wait for the condition and then note we were signaled.
      while ( td->Done <= 0 )
        {
        td->Lock->Lock();
        cout << " Thread " << ( threadId + 1 ) << " waiting.\n";
        cout.flush();
        td->Condition->Wait( td->Lock );
        cout << " Thread " << ( threadId + 1 ) << " responded.\n";
        cout.flush();
        td->Lock->Unlock();
        }
      td->Lock->Lock();
      -- td->NumberOfWorkers;
      td->Lock->Unlock();
      }

    td->Lock->Lock();
    cout << "  Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
    cout.flush();
    td->Lock->Unlock();
    }
  else
    {
    cout << "No thread data!\n";
    cout << "  Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
    -- td->NumberOfWorkers;
    cout.flush();
    }

  return VTK_THREAD_RETURN_VALUE;
}

int TestConditionVariable( int, char*[] )
{
  vtkMultiThreader* threader = vtkMultiThreader::New();
  int numThreads = threader->GetNumberOfThreads();

  vtkThreadUserData data;
  data.Lock = vtkMutexLock::New();
  data.Condition = vtkConditionVariable::New();
  data.Done = -1;
  data.NumberOfWorkers = numThreads - 1;

  threader->SetNumberOfThreads( numThreads );
  threader->SetSingleMethod( vtkTestCondVarThread, &data );
  threader->SingleMethodExecute();

  cout << "Done with threader.\n";
  cout.flush();

  vtkIndent indent;
  indent = indent.GetNextIndent();
  data.Condition->PrintSelf( cout, indent );

  data.Lock->Delete();
  data.Condition->Delete();
  threader->Delete();
  return 0;
}
<commit_msg>BUG:Try to fix the test on dashmacmini2 (unix/release). lock/unlock where misplaced, now it really looks like a Hansen Monitor implementation.<commit_after>#include "vtkConditionVariable.h"
#include "vtkMultiThreader.h"

#include <stdlib.h>

// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>

// Cross platform sleep (horked from vtkGeoTerrain.cxx)
inline void vtkSleep( double duration )
{
  duration = duration; // avoid warnings
  // sleep according to OS preference
#ifdef _WIN32
  Sleep( (int)( 1000 * duration ) );
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
  struct timespec sleep_time, dummy;
  sleep_time.tv_sec = static_cast<int>( duration );
  sleep_time.tv_nsec = static_cast<int>( 1000000000 * ( duration - sleep_time.tv_sec ) );
  nanosleep( &sleep_time, &dummy );
#endif
}

typedef struct {
  vtkMutexLock* Lock;
  vtkConditionVariable* Condition;
  int Done;
  int NumberOfWorkers;
} vtkThreadUserData;

VTK_THREAD_RETURN_TYPE vtkTestCondVarThread( void* arg )
{
  int threadId = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->ThreadID;
  int threadCount = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->NumberOfThreads;
  vtkThreadUserData* td = static_cast<vtkThreadUserData*>(
    static_cast<vtkMultiThreader::ThreadInfo*>(arg)->UserData );
  if ( td )
    {
    if ( threadId == 0 )
      {
      td->Done = 0;
      td->Lock->Lock();
      cout << "Thread " << ( threadId + 1 ) << " of " << threadCount << " initializing.\n";
      cout.flush();
      td->Lock->Unlock();

      int i;
      for ( i = 0; i < 2 * threadCount; ++ i )
        {
        td->Lock->Lock();
        cout << "Signaling (count " << i << ")...\n";
        cout.flush();
        td->Lock->Unlock();
        td->Condition->Signal();

        //sleep( 1 );
        }

      i = 0;
      do
        {
        td->Lock->Lock();
        td->Done = 1;
        cout << "Broadcasting...\n";
        cout.flush();
        td->Lock->Unlock();
        td->Condition->Broadcast();
        vtkSleep( 0.2 ); // 0.2 s between broadcasts
        }
      while ( td->NumberOfWorkers > 0 && ( i ++ < 1000 ) );
      if ( i >= 1000 )
        {
        exit( 2 );
        }
      }
    else
      {
      // Wait for thread 0 to initialize... Ugly but effective
      while ( td->Done < 0 )
        {
        vtkSleep( 0.2 ); // 0.2 s between checking
        }

      // Wait for the condition and then note we were signaled.
      // This part looks like a Hansen Monitor:
      // ref: http://www.cs.utexas.edu/users/lorenzo/corsi/cs372h/07S/notes/Lecture12.pdf (page 2/5), code on Tradeoff slide.

      td->Lock->Lock();
      while ( td->Done <= 0 )
        {
        cout << " Thread " << ( threadId + 1 ) << " waiting.\n";
        cout.flush();
        // Wait() performs an Unlock internally.
        td->Condition->Wait( td->Lock );
        // Once Wait() returns, the lock is locked again.
        cout << " Thread " << ( threadId + 1 ) << " responded.\n";
        cout.flush();
        }
      -- td->NumberOfWorkers;
      td->Lock->Unlock();
      }

    td->Lock->Lock();
    cout << "  Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
    cout.flush();
    td->Lock->Unlock();
    }
  else
    {
    cout << "No thread data!\n";
    cout << "  Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
    -- td->NumberOfWorkers;
    cout.flush();
    }

  return VTK_THREAD_RETURN_VALUE;
}

int TestConditionVariable( int, char*[] )
{
  vtkMultiThreader* threader = vtkMultiThreader::New();
  int numThreads = threader->GetNumberOfThreads();

  vtkThreadUserData data;
  data.Lock = vtkMutexLock::New();
  data.Condition = vtkConditionVariable::New();
  data.Done = -1;
  data.NumberOfWorkers = numThreads - 1;

  threader->SetNumberOfThreads( numThreads );
  threader->SetSingleMethod( vtkTestCondVarThread, &data );
  threader->SingleMethodExecute();

  cout << "Done with threader.\n";
  cout.flush();

  vtkIndent indent;
  indent = indent.GetNextIndent();
  data.Condition->PrintSelf( cout, indent );

  data.Lock->Delete();
  data.Condition->Delete();
  threader->Delete();
  return 0;
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#pragma once
#include <af/defines.h>
#include <Array.hpp>
#include <complex>

namespace cpu
{
namespace kernel
{

template<typename T> T
conj(T  x) { return x; }

template<> cfloat  conj<cfloat> (cfloat  c) { return std::conj(c); }
template<> cdouble conj<cdouble>(cdouble c) { return std::conj(c); }

template<typename T, bool conjugate, bool both_conjugate>
void dot(Array<T> output, const Array<T> &lhs, const Array<T> &rhs,
         af_mat_prop optLhs, af_mat_prop optRhs)
{
    int N = lhs.dims()[0];

    T out = 0;
    const T *pL = lhs.get();
    const T *pR = rhs.get();

    for(int i = 0; i < N; i++)
        out += (conjugate ? kernel::conj(pL[i]) : pL[i]) * pR[i];

    if(both_conjugate) out = kernel::conj(out);

    *output.get() = out;

}

}
}
<commit_msg>fixed cpu::kernel::dot fn signature<commit_after>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#pragma once
#include <af/defines.h>
#include <Array.hpp>
#include <complex>

namespace cpu
{
namespace kernel
{

template<typename T> T
conj(T  x) { return x; }

template<> cfloat  conj<cfloat> (cfloat  c) { return std::conj(c); }
template<> cdouble conj<cdouble>(cdouble c) { return std::conj(c); }

template<typename T, bool conjugate, bool both_conjugate>
void dot(Array<T> output, const Array<T> lhs, const Array<T> rhs,
         af_mat_prop optLhs, af_mat_prop optRhs)
{
    int N = lhs.dims()[0];

    T out = 0;
    const T *pL = lhs.get();
    const T *pR = rhs.get();

    for(int i = 0; i < N; i++)
        out += (conjugate ? kernel::conj(pL[i]) : pL[i]) * pR[i];

    if(both_conjugate) out = kernel::conj(out);

    *output.get() = out;

}

}
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "vtkMitkRectangleProp.h"

#include <vtkObjectFactory.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkLine.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkProperty2D.h>
#include <vtkActor2D.h>
#include <vtkPolyDataMapper2D.h>

vtkStandardNewMacro(vtkMitkRectangleProp);

vtkMitkRectangleProp::vtkMitkRectangleProp()
{
  vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New();
  m_RectangleActor = vtkSmartPointer<vtkActor2D>::New();
  m_PolyData = vtkSmartPointer<vtkPolyData>::New();

  vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();

  m_PolyData->SetPoints(points);
  m_PolyData->SetLines(lines);

  this->CreateRectangle();

  mapper->SetInputData(m_PolyData);
  m_RectangleActor->SetMapper(mapper);
}

vtkMitkRectangleProp::~vtkMitkRectangleProp()
{
}

int vtkMitkRectangleProp::RenderOverlay(vtkViewport* viewport)
{
  double right = m_RenderWindow->GetSize()[0];
  double top = m_RenderWindow->GetSize()[1];
  double bottom = 0.5;
  double left = 0.5;
  double defaultDepth = 0.0;

  vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
  //change the corners to adapt the size of the renderwindow was resized
  points->SetPoint(m_BottomLeft, left, bottom, defaultDepth);
  points->SetPoint(m_TopLeft, left, top, defaultDepth);
  points->SetPoint(m_TopRight, right, top, defaultDepth);
  points->SetPoint(m_BottomRight, right, bottom, defaultDepth);

  //adapt color
  m_RectangleActor->GetProperty()->SetColor( m_Color[0], m_Color[1], m_Color[2]);

  //render the actor
  m_RectangleActor->RenderOverlay(viewport);
  return 1;
}

void vtkMitkRectangleProp::CreateRectangle()
{
  vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
  vtkSmartPointer<vtkCellArray> lines = m_PolyData->GetLines();

  double bottom = 0.5;
  double left = 0.5;
  double right = 199.0;
  double top = 199.0;
  double defaultDepth = 0.0;

  //4 corner points
  m_BottomLeft = points->InsertNextPoint(left, bottom, defaultDepth);
  m_BottomRight = points->InsertNextPoint(right, bottom, defaultDepth);
  m_TopLeft = points->InsertNextPoint(left, top, defaultDepth);
  m_TopRight = points->InsertNextPoint(right, top, defaultDepth);

  vtkSmartPointer<vtkLine> lineVtk =  vtkSmartPointer<vtkLine>::New();
  lineVtk->GetPointIds()->SetNumberOfIds(5);
  //connect the lines
  lineVtk->GetPointIds()->SetId(0,m_BottomLeft);
  lineVtk->GetPointIds()->SetId(1,m_BottomRight);
  lineVtk->GetPointIds()->SetId(2,m_TopRight);
  lineVtk->GetPointIds()->SetId(3,m_TopLeft);
  lineVtk->GetPointIds()->SetId(4,m_BottomLeft);

  lines->InsertNextCell(lineVtk);
}

void vtkMitkRectangleProp::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renWin)
{
  m_RenderWindow = renWin;
}

void vtkMitkRectangleProp::SetColor(float col1, float col2, float col3)
{
  m_Color[0] = col1;
  m_Color[1] = col2;
  m_Color[2] = col3;
}
<commit_msg>Rectangle prop now correctly uses the viewport.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "vtkMitkRectangleProp.h"

#include <vtkObjectFactory.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkLine.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkProperty2D.h>
#include <vtkActor2D.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkViewport.h>

vtkStandardNewMacro(vtkMitkRectangleProp);

vtkMitkRectangleProp::vtkMitkRectangleProp()
{
  vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New();
  m_RectangleActor = vtkSmartPointer<vtkActor2D>::New();
  m_PolyData = vtkSmartPointer<vtkPolyData>::New();

  vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();

  m_PolyData->SetPoints(points);
  m_PolyData->SetLines(lines);

  this->CreateRectangle();

  mapper->SetInputData(m_PolyData);
  m_RectangleActor->SetMapper(mapper);
}

vtkMitkRectangleProp::~vtkMitkRectangleProp()
{
}

int vtkMitkRectangleProp::RenderOverlay(vtkViewport* viewport)
{
  double right = viewport->GetSize()[0];
  double top = viewport->GetSize()[1];
//  double bottom = 0.0;
  double left = viewport->GetOrigin()[0] + 0.5;
  double bottom = viewport->GetOrigin()[1] + 0.5;
//  double left = 0.0;
  double defaultDepth = 0.0;

  vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
  //change the corners to adapt the size of the renderwindow was resized
  points->SetPoint(m_BottomLeft, left, bottom, defaultDepth);
  points->SetPoint(m_TopLeft, left, top, defaultDepth);
  points->SetPoint(m_TopRight, right, top, defaultDepth);
  points->SetPoint(m_BottomRight, right, bottom, defaultDepth);

  //adapt color
  m_RectangleActor->GetProperty()->SetColor( m_Color[0], m_Color[1], m_Color[2]);

  //render the actor
  m_RectangleActor->RenderOverlay(viewport);
  return 1;
}

void vtkMitkRectangleProp::CreateRectangle()
{
  vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
  vtkSmartPointer<vtkCellArray> lines = m_PolyData->GetLines();

  //just some default values until a renderwindow/viewport is initialized
  double bottom = 0.0;
  double left = 0.0;
  double right = 200.0;
  double top = 200.0;
  double defaultDepth = 0.0;

  //4 corner points
  m_BottomLeft = points->InsertNextPoint(left, bottom, defaultDepth);
  m_BottomRight = points->InsertNextPoint(right, bottom, defaultDepth);
  m_TopLeft = points->InsertNextPoint(left, top, defaultDepth);
  m_TopRight = points->InsertNextPoint(right, top, defaultDepth);

  vtkSmartPointer<vtkLine> lineVtk =  vtkSmartPointer<vtkLine>::New();
  lineVtk->GetPointIds()->SetNumberOfIds(5);
  //connect the lines
  lineVtk->GetPointIds()->SetId(0,m_BottomLeft);
  lineVtk->GetPointIds()->SetId(1,m_BottomRight);
  lineVtk->GetPointIds()->SetId(2,m_TopRight);
  lineVtk->GetPointIds()->SetId(3,m_TopLeft);
  lineVtk->GetPointIds()->SetId(4,m_BottomLeft);

  lines->InsertNextCell(lineVtk);
}

void vtkMitkRectangleProp::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renWin)
{
  m_RenderWindow = renWin;
}

void vtkMitkRectangleProp::SetColor(float col1, float col2, float col3)
{
  m_Color[0] = col1;
  m_Color[1] = col2;
  m_Color[2] = col3;
}
<|endoftext|>


<commit_before>#include <iostream>

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

<commit_msg>Random numbers example compiles and runs<commit_after>#include <iostream>
#include <random>
#include <functional>

int main(int argc, char* argv[])
{
	std::uniform_int_distribution<int> distribution(0,99);
	std::mt19937 engine;
	auto generator = std::bind(distribution,engine);

	for ( int i=0; i<50; ++i )
	{
		int random = generator();
		std::cout << random << " ";
	}
	std::cout << std::endl;
}

<|endoftext|>


<commit_before>// bslmf_assert.t.cpp                                                 -*-C++-*-
#include <bslmf_assert.h>

#include <bsls_bsltestutil.h>
#include <bsls_compilerfeatures.h>
#include <bsls_platform.h>

#include <stdio.h>   // printf
#include <stdlib.h>  // atoi

//=============================================================================
//                                TEST PLAN
//-----------------------------------------------------------------------------
//                                Overview
//                                --------
//-----------------------------------------------------------------------------
// [ 1] BSLMF_ASSERT(expr)i
// ----------------------------------------------------------------------------
// [  ] USAGE EXAMPLE
// [ 2] CONCERN: BSLMF_ASSERT in non-instantiated template classes

//=============================================================================
//
//                       STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;

void aSsErT(bool b, const char *s, int i)
{
    if (b) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", i, s);
        if (testStatus >= 0 && testStatus <= 100) ++testStatus;
    }
}

# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }

//=============================================================================
//                       STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT

#define Q   BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P   BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_  BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLS_BSLTESTUTIL_L_  // current Line number

//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

namespace BloombergLP {
namespace bslmftest {

                           // ======================
                           // class SomeTemplateType
                           // ======================

template <class SOME_TYPE>
class SomeTemplateType {
    // This specialization of 'SomeTemplateType' defines an alias 'Type' for a
    // functor that delegates to a function pointer matching the parameterized
    // 'SOME_TYPE' type.

    BSLMF_ASSERT(4 == sizeof(SOME_TYPE));
        // This 'BSLMF_ASSERT' statement ensures that the parameter 'SOME_TYPE'
        // must be a function pointer.
};

}  // close package namespace
}  // close enterprise namespace

// namespace scope

BSLMF_ASSERT(sizeof(int) >= sizeof(char));

// un-named namespace
namespace {
    BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
    BSLMF_ASSERT(1);
#else
    BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
}  // close unnamed namespace

namespace {
    BSLMF_ASSERT(1);
}  // close unnamed namespace

namespace Bar {

    BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
    BSLMF_ASSERT(1);
#else
    BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
}  // close namespace Bar

class MyType {
    // class scope

    BSLMF_ASSERT(sizeof(int) >= sizeof(char));
    BSLMF_ASSERT(sizeof(int) >= sizeof(char));

  public:
    int d_data;
    void foo();
};

void MyType::foo()
{
    // function scope

    BSLMF_ASSERT(sizeof(int) >= sizeof(char));
    BSLMF_ASSERT(1);

    using namespace BloombergLP;
    BSLMF_ASSERT(1);
}

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    bool verbose = argc > 2;
    // bool veryVerbose = argc > 3;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 2: {
        // --------------------------------------------------------------------
        // BSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS
        //   Sun Studio has historically required a special implementation of
        //   'BSMF_ASSERT'.  According to DRQS 79918675, starting with Sun
        //   Studio 12.4 the special implementation causes build failures by
        //   its mere presence in a templatized class, even if that class is
        //   never instantiated.  On the other hand, Sun Studio 12.4 has
        //   improved template instantiation, and therefore does not need the
        //   special implementation.  This test case checks that the case
        //   reported in DRQS 79918675 is fixed by switching to the standard
        //   implementation on versions 12.4 and better.
        //
        // Concerns:
        //  1 Uses of BSLMF_ASSERT in non-instantiated templates does not cause
        //    a build failure when the assertion depends on a template
        //    parameter.
        //
        // Plan:
        //  1 Create a template class having an assertion dependent on the
        //    template parameter, but do not instantiate the class.  If the code
        //    builds on Sun Studio 12.4, the test passes.  (C-1)
        //
        // Testing:
        //   CONCERN: BSLMF_ASSERT in non-instantiated template classes
        // --------------------------------------------------------------------

        if (verbose) printf("\nBSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS"
                            "\n========================================\n");

        // Do nothing.  The test is entirely encapsulated in the definition of
        // 'SomeTemplateType' above.

        ASSERT(true);
      } break;
      case 1: {
        // --------------------------------------------------------------------
        // TESTING BSLMF_ASSERT MACRO
        // We have the following concerns:
        //   1. Works for all non-zero integral values.
        //   2. Works in and out of class scope.
        //
        // Plan:
        //   Invoke the macro at namespace, class, and function scope (above)
        //   and verify that it does not cause a compiler error.  Please see
        //   the 'ttt' test package group for test cases where the macro
        //   should cause a compile-time error.
        //
        // Testing:
        //   BSLMF_ASSERT(expr)
        // --------------------------------------------------------------------

        if (verbose) printf("\nBSLMF_ASSERT Macro"
                            "\n==================\n");

        BSLMF_ASSERT(sizeof(int) >= sizeof(char));
        BSLMF_ASSERT(sizeof(int) >= sizeof(char));
        BSLMF_ASSERT(1);  ASSERT(145 == __LINE__);
        BSLMF_ASSERT(1);  ASSERT(146 == __LINE__);
        BSLMF_ASSERT(1 > 0 && 1);

// MSVC: __LINE__ macro breaks when /ZI is used (see Q199057 or KB199057)
// SUN:  BSLMF_ASSERT is defined the way that breaks this test
// GCC:  Declares a function, rather than a typedef, from v4.8.1
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_STATIC_ASSERT) && \
    !defined(BSLS_PLATFORM_CMP_MSVC) &&                      \
    !defined(BSLS_PLATFORM_CMP_SUN)  &&                      \
    !(defined(BSLS_PLATFORM_CMP_GNU) && BSLS_PLATFORM_CMP_VER_MAJOR > 40800)
        bslmf_Assert_145 t1; // test typedef name creation; matches above line
        bslmf_Assert_146 t2; // test typedef name creation; matches above line
        ASSERT(sizeof t1 == sizeof t2);  // use t1 and t2
#endif

        BSLMF_ASSERT(2);
        BSLMF_ASSERT(-1);

#if defined(BSLS_PLATFORM_CMP_SUN)
        BSLMF_ASSERT(1);
#else
        BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif

      } break;
      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }

    return testStatus;
}

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Update line numbers in bslmf_assert test driver<commit_after>// bslmf_assert.t.cpp                                                 -*-C++-*-
#include <bslmf_assert.h>

#include <bsls_bsltestutil.h>
#include <bsls_compilerfeatures.h>
#include <bsls_platform.h>

#include <stdio.h>   // printf
#include <stdlib.h>  // atoi

//=============================================================================
//                                TEST PLAN
//-----------------------------------------------------------------------------
//                                Overview
//                                --------
//-----------------------------------------------------------------------------
// [ 1] BSLMF_ASSERT(expr)i
// ----------------------------------------------------------------------------
// [  ] USAGE EXAMPLE
// [ 2] CONCERN: BSLMF_ASSERT in non-instantiated template classes

//=============================================================================
//
//                       STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;

void aSsErT(bool b, const char *s, int i)
{
    if (b) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", i, s);
        if (testStatus >= 0 && testStatus <= 100) ++testStatus;
    }
}

# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }

//=============================================================================
//                       STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT

#define Q   BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P   BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_  BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLS_BSLTESTUTIL_L_  // current Line number

//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

namespace BloombergLP {
namespace bslmftest {

                           // ======================
                           // class SomeTemplateType
                           // ======================

template <class SOME_TYPE>
class SomeTemplateType {
    // This specialization of 'SomeTemplateType' defines an alias 'Type' for a
    // functor that delegates to a function pointer matching the parameterized
    // 'SOME_TYPE' type.

    BSLMF_ASSERT(4 == sizeof(SOME_TYPE));
        // This 'BSLMF_ASSERT' statement ensures that the parameter 'SOME_TYPE'
        // must be a function pointer.
};

}  // close package namespace
}  // close enterprise namespace

// namespace scope

BSLMF_ASSERT(sizeof(int) >= sizeof(char));

// un-named namespace
namespace {
    BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
    BSLMF_ASSERT(1);
#else
    BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
}  // close unnamed namespace

namespace {
    BSLMF_ASSERT(1);
}  // close unnamed namespace

namespace Bar {

    BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
    BSLMF_ASSERT(1);
#else
    BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
}  // close namespace Bar

class MyType {
    // class scope

    BSLMF_ASSERT(sizeof(int) >= sizeof(char));
    BSLMF_ASSERT(sizeof(int) >= sizeof(char));

  public:
    int d_data;
    void foo();
};

void MyType::foo()
{
    // function scope

    BSLMF_ASSERT(sizeof(int) >= sizeof(char));
    BSLMF_ASSERT(1);

    using namespace BloombergLP;
    BSLMF_ASSERT(1);
}

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    bool verbose = argc > 2;
    // bool veryVerbose = argc > 3;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 2: {
        // --------------------------------------------------------------------
        // BSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS
        //   Sun Studio has historically required a special implementation of
        //   'BSMF_ASSERT'.  According to DRQS 79918675, starting with Sun
        //   Studio 12.4 the special implementation causes build failures by
        //   its mere presence in a templatized class, even if that class is
        //   never instantiated.  On the other hand, Sun Studio 12.4 has
        //   improved template instantiation, and therefore does not need the
        //   special implementation.  This test case checks that the case
        //   reported in DRQS 79918675 is fixed by switching to the standard
        //   implementation on versions 12.4 and better.
        //
        // Concerns:
        //  1 Uses of BSLMF_ASSERT in non-instantiated templates does not cause
        //    a build failure when the assertion depends on a template
        //    parameter.
        //
        // Plan:
        //  1 Create a template class having an assertion dependent on the
        //    template parameter, but do not instantiate the class.  If the code
        //    builds on Sun Studio 12.4, the test passes.  (C-1)
        //
        // Testing:
        //   CONCERN: BSLMF_ASSERT in non-instantiated template classes
        // --------------------------------------------------------------------

        if (verbose) printf("\nBSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS"
                            "\n========================================\n");

        // Do nothing.  The test is entirely encapsulated in the definition of
        // 'SomeTemplateType' above.

        ASSERT(true);
      } break;
      case 1: {
        // --------------------------------------------------------------------
        // TESTING BSLMF_ASSERT MACRO
        // We have the following concerns:
        //   1. Works for all non-zero integral values.
        //   2. Works in and out of class scope.
        //
        // Plan:
        //   Invoke the macro at namespace, class, and function scope (above)
        //   and verify that it does not cause a compiler error.  Please see
        //   the 'ttt' test package group for test cases where the macro
        //   should cause a compile-time error.
        //
        // Testing:
        //   BSLMF_ASSERT(expr)
        // --------------------------------------------------------------------

        if (verbose) printf("\nBSLMF_ASSERT Macro"
                            "\n==================\n");

        BSLMF_ASSERT(sizeof(int) >= sizeof(char));
        BSLMF_ASSERT(sizeof(int) >= sizeof(char));
        BSLMF_ASSERT(1);  ASSERT(202 == __LINE__);
        BSLMF_ASSERT(1);  ASSERT(203 == __LINE__);
        BSLMF_ASSERT(1 > 0 && 1);

// MSVC: __LINE__ macro breaks when /ZI is used (see Q199057 or KB199057)
// SUN:  BSLMF_ASSERT is defined the way that breaks this test
// GCC:  Declares a function, rather than a typedef, from v4.8.1
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_STATIC_ASSERT) && \
    !defined(BSLS_PLATFORM_CMP_MSVC) &&                      \
    !defined(BSLS_PLATFORM_CMP_SUN)  &&                      \
    !(defined(BSLS_PLATFORM_CMP_GNU) && BSLS_PLATFORM_CMP_VER_MAJOR > 40800)
        bslmf_Assert_202 t1; // test typedef name creation; matches above line
        bslmf_Assert_203 t2; // test typedef name creation; matches above line
        ASSERT(sizeof t1 == sizeof t2);  // use t1 and t2
#endif

        BSLMF_ASSERT(2);
        BSLMF_ASSERT(-1);

#if defined(BSLS_PLATFORM_CMP_SUN)
        BSLMF_ASSERT(1);
#else
        BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif

      } break;
      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }

    return testStatus;
}

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.

#ifndef GUARD_report_panel_hpp_8629163596140763
#define GUARD_report_panel_hpp_8629163596140763

#include "entry.hpp"
#include <boost/noncopyable.hpp>
#include <wx/combobox.h>
#include <wx/button.h>
#include <wx/event.h>
#include <wx/gbsizer.h>
#include <wx/panel.h>
#include <wx/window.h>
#include <vector>

namespace phatbooks
{

// Begin forward declarations

class Account;
class OrdinaryJournal;
class PhatbooksDatabaseConnection;

namespace gui
{

class DateCtrl;
class Report;

// End forward declarations

/**
 * Panel for holding date-filtered balance sheet and profit-and-loss
 * reports.
 *
 * @todo We can make things more straightforward and speed start-up times
 * by having the date boxes start out blank. We can then have
 * BalanceSheetReport initially just use the balance() of each Account
 * simpliciter as "Closing balance" and "Movement", and use a
 * \e nil amount for the "Opening balance" column. This can be written
 * into the code for initializing the m_balance_map.
 *
 * @todo HIGH PRIORITY Make it so this only runs when "Run" is clicked, not
 * automatically on creation.
 */
class ReportPanel: public wxPanel, private boost::noncopyable
{
public:
	ReportPanel
	(	wxWindow* p_parent,
		PhatbooksDatabaseConnection& p_database_connection
	);

	void update_for_new(OrdinaryJournal const& p_journal);
	void update_for_amended(OrdinaryJournal const& p_journal);
	void update_for_new(Account const& p_account);
	void update_for_amended(Account const& p_account);
	void update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids);

private:
	void on_run_button_click(wxCommandEvent& event);

	void configure_top();
	void configure_bottom();

	account_super_type::AccountSuperType selected_account_super_type() const;

	static int const s_min_date_ctrl_id = wxID_HIGHEST + 1;
	static int const s_max_date_ctrl_id = s_min_date_ctrl_id + 1;
	static int const s_run_button_id = s_max_date_ctrl_id + 1;

	int m_next_row;

	int m_client_size_aux;
	int m_text_ctrl_height;

	wxGridBagSizer* m_top_sizer;
	wxComboBox* m_report_type_ctrl;
	DateCtrl* m_min_date_ctrl;
	DateCtrl* m_max_date_ctrl;
	wxButton* m_run_button;
	Report* m_report;
	PhatbooksDatabaseConnection& m_database_connection;

	DECLARE_EVENT_TABLE()

};  // class ReportPanel

}  // namespace gui
}  // namespace phatbooks

#endif  // GUARD_report_panel_hpp_8629163596140763
<commit_msg>Update a TODO.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.

#ifndef GUARD_report_panel_hpp_8629163596140763
#define GUARD_report_panel_hpp_8629163596140763

#include "entry.hpp"
#include <boost/noncopyable.hpp>
#include <wx/combobox.h>
#include <wx/button.h>
#include <wx/event.h>
#include <wx/gbsizer.h>
#include <wx/panel.h>
#include <wx/window.h>
#include <vector>

namespace phatbooks
{

// Begin forward declarations

class Account;
class OrdinaryJournal;
class PhatbooksDatabaseConnection;

namespace gui
{

class DateCtrl;
class Report;

// End forward declarations

/**
 * Panel for holding date-filtered balance sheet and profit-and-loss
 * reports.
 *
 * @todo We can make things more straightforward and speed start-up times
 * by having the date boxes start out blank. We can then have
 * BalanceSheetReport initially just use the balance() of each Account
 * simpliciter as "Closing balance" and "Movement", and use a
 * \e nil amount for the "Opening balance" column. This can be written
 * into the code for initializing the m_balance_map.
 */
class ReportPanel: public wxPanel, private boost::noncopyable
{
public:
	ReportPanel
	(	wxWindow* p_parent,
		PhatbooksDatabaseConnection& p_database_connection
	);

	void update_for_new(OrdinaryJournal const& p_journal);
	void update_for_amended(OrdinaryJournal const& p_journal);
	void update_for_new(Account const& p_account);
	void update_for_amended(Account const& p_account);
	void update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids);

private:
	void on_run_button_click(wxCommandEvent& event);

	void configure_top();
	void configure_bottom();

	account_super_type::AccountSuperType selected_account_super_type() const;

	static int const s_min_date_ctrl_id = wxID_HIGHEST + 1;
	static int const s_max_date_ctrl_id = s_min_date_ctrl_id + 1;
	static int const s_run_button_id = s_max_date_ctrl_id + 1;

	int m_next_row;

	int m_client_size_aux;
	int m_text_ctrl_height;

	wxGridBagSizer* m_top_sizer;
	wxComboBox* m_report_type_ctrl;
	DateCtrl* m_min_date_ctrl;
	DateCtrl* m_max_date_ctrl;
	wxButton* m_run_button;
	Report* m_report;
	PhatbooksDatabaseConnection& m_database_connection;

	DECLARE_EVENT_TABLE()

};  // class ReportPanel

}  // namespace gui
}  // namespace phatbooks

#endif  // GUARD_report_panel_hpp_8629163596140763
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

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

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"

#include "OgreException.h"

#include <iostream>

namespace Ogre {

    //-----------------------------------------------------------------------
    ConfigFile::ConfigFile()
    {
    }
    //-----------------------------------------------------------------------
    ConfigFile::~ConfigFile()
    {
        SettingsBySection::iterator seci, secend;
        secend = mSettings.end();
        for (seci = mSettings.begin(); seci != secend; ++seci)
        {
            OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
        }
    }
    //-----------------------------------------------------------------------
    void ConfigFile::clear(void)
    {
        for (SettingsBySection::iterator seci = mSettings.begin();
            seci != mSettings.end(); ++seci)
        {
             OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
        }
        mSettings.clear();
    }
    //-----------------------------------------------------------------------
    void ConfigFile::load(const String& filename, const String& separators, bool trimWhitespace)
    {
        loadDirect(filename, separators, trimWhitespace);
    }
    //-----------------------------------------------------------------------
    void ConfigFile::load(const String& filename, const String& resourceGroup,
        const String& separators, bool trimWhitespace)
    {
		loadFromResourceSystem(filename, resourceGroup, separators, trimWhitespace);
    }
	//-----------------------------------------------------------------------
	void ConfigFile::loadDirect(const String& filename, const String& separators,
		bool trimWhitespace)
	{
		/* Open the configuration file */
		std::ifstream fp;
        // Always open in binary mode
		fp.open(filename.c_str(), std::ios::in | std::ios::binary);
		if(!fp)
			OGRE_EXCEPT(
			Exception::ERR_FILE_NOT_FOUND, "'" + filename + "' file not found!", "ConfigFile::load" );

		// Wrap as a stream
		DataStreamPtr stream(OGRE_NEW FileStreamDataStream(filename, &fp, false));
		load(stream, separators, trimWhitespace);

	}
	//-----------------------------------------------------------------------
	void ConfigFile::loadFromResourceSystem(const String& filename,
		const String& resourceGroup, const String& separators, bool trimWhitespace)
	{
		DataStreamPtr stream =
			ResourceGroupManager::getSingleton().openResource(filename, resourceGroup);
		load(stream, separators, trimWhitespace);
	}
    //-----------------------------------------------------------------------
    void ConfigFile::load(const DataStreamPtr& stream, const String& separators,
        bool trimWhitespace)
    {
        /* Clear current settings map */
        clear();

        String currentSection = StringUtil::BLANK;
        SettingsMultiMap* currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
        mSettings[currentSection] = currentSettings;

        /* Process the file line for line */
        String line, optName, optVal;
        while (!stream->eof())
        {
            line = stream->getLine();
            /* Ignore comments & blanks */
            if (line.length() > 0 && line.at(0) != '#' && line.at(0) != '@')
            {
                if (line.at(0) == '[' && line.at(line.length()-1) == ']')
                {
                    // Section
                    currentSection = line.substr(1, line.length() - 2);
					SettingsBySection::const_iterator seci = mSettings.find(currentSection);
					if (seci == mSettings.end())
					{
						currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
						mSettings[currentSection] = currentSettings;
					}
					else
					{
						currentSettings = seci->second;
					}
                }
                else
                {
                    /* Find the first seperator character and split the string there */
                    std::string::size_type separator_pos = line.find_first_of(separators, 0);
                    if (separator_pos != std::string::npos)
                    {
                        optName = line.substr(0, separator_pos);
                        /* Find the first non-seperator character following the name */
                        std::string::size_type nonseparator_pos = line.find_first_not_of(separators, separator_pos);
                        /* ... and extract the value */
                        /* Make sure we don't crash on an empty setting (it might be a valid value) */
                        optVal = (nonseparator_pos == std::string::npos) ? "" : line.substr(nonseparator_pos);
                        if (trimWhitespace)
                        {
                            StringUtil::trim(optVal);
                            StringUtil::trim(optName);
                        }
                        currentSettings->insert(std::multimap<String, String>::value_type(optName, optVal));
                    }
                }
            }
        }
    }
    //-----------------------------------------------------------------------
    String ConfigFile::getSetting(const String& key, const String& section, const String& defaultValue) const
    {

        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci == mSettings.end())
        {
            return defaultValue;
        }
        else
        {
            SettingsMultiMap::const_iterator i = seci->second->find(key);
            if (i == seci->second->end())
            {
                return StringUtil::BLANK;
            }
            else
            {
                return i->second;
            }
        }
    }
    //-----------------------------------------------------------------------
    StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const
    {
        StringVector ret;

        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci != mSettings.end())
        {
            SettingsMultiMap::const_iterator i;

            i = seci->second->find(key);
            // Iterate over matches
            while (i != seci->second->end() && i->first == key)
            {
                ret.push_back(i->second);
                ++i;
            }
        }
        return ret;

    }
    //-----------------------------------------------------------------------
    ConfigFile::SettingsIterator ConfigFile::getSettingsIterator(const String& section)
    {
        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci == mSettings.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
                "Cannot find section " + section,
                "ConfigFile::getSettingsIterator");
        }
        else
        {
            return SettingsIterator(seci->second->begin(), seci->second->end());
        }
    }
    //-----------------------------------------------------------------------
    ConfigFile::SectionIterator ConfigFile::getSectionIterator(void)
    {
        return SectionIterator(mSettings.begin(), mSettings.end());
    }

}
<commit_msg>Patch 2482278: return default value properly from ConfigFile::getSetting<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

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

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"

#include "OgreException.h"

#include <iostream>

namespace Ogre {

    //-----------------------------------------------------------------------
    ConfigFile::ConfigFile()
    {
    }
    //-----------------------------------------------------------------------
    ConfigFile::~ConfigFile()
    {
        SettingsBySection::iterator seci, secend;
        secend = mSettings.end();
        for (seci = mSettings.begin(); seci != secend; ++seci)
        {
            OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
        }
    }
    //-----------------------------------------------------------------------
    void ConfigFile::clear(void)
    {
        for (SettingsBySection::iterator seci = mSettings.begin();
            seci != mSettings.end(); ++seci)
        {
             OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
        }
        mSettings.clear();
    }
    //-----------------------------------------------------------------------
    void ConfigFile::load(const String& filename, const String& separators, bool trimWhitespace)
    {
        loadDirect(filename, separators, trimWhitespace);
    }
    //-----------------------------------------------------------------------
    void ConfigFile::load(const String& filename, const String& resourceGroup,
        const String& separators, bool trimWhitespace)
    {
		loadFromResourceSystem(filename, resourceGroup, separators, trimWhitespace);
    }
	//-----------------------------------------------------------------------
	void ConfigFile::loadDirect(const String& filename, const String& separators,
		bool trimWhitespace)
	{
		/* Open the configuration file */
		std::ifstream fp;
        // Always open in binary mode
		fp.open(filename.c_str(), std::ios::in | std::ios::binary);
		if(!fp)
			OGRE_EXCEPT(
			Exception::ERR_FILE_NOT_FOUND, "'" + filename + "' file not found!", "ConfigFile::load" );

		// Wrap as a stream
		DataStreamPtr stream(OGRE_NEW FileStreamDataStream(filename, &fp, false));
		load(stream, separators, trimWhitespace);

	}
	//-----------------------------------------------------------------------
	void ConfigFile::loadFromResourceSystem(const String& filename,
		const String& resourceGroup, const String& separators, bool trimWhitespace)
	{
		DataStreamPtr stream =
			ResourceGroupManager::getSingleton().openResource(filename, resourceGroup);
		load(stream, separators, trimWhitespace);
	}
    //-----------------------------------------------------------------------
    void ConfigFile::load(const DataStreamPtr& stream, const String& separators,
        bool trimWhitespace)
    {
        /* Clear current settings map */
        clear();

        String currentSection = StringUtil::BLANK;
        SettingsMultiMap* currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
        mSettings[currentSection] = currentSettings;

        /* Process the file line for line */
        String line, optName, optVal;
        while (!stream->eof())
        {
            line = stream->getLine();
            /* Ignore comments & blanks */
            if (line.length() > 0 && line.at(0) != '#' && line.at(0) != '@')
            {
                if (line.at(0) == '[' && line.at(line.length()-1) == ']')
                {
                    // Section
                    currentSection = line.substr(1, line.length() - 2);
					SettingsBySection::const_iterator seci = mSettings.find(currentSection);
					if (seci == mSettings.end())
					{
						currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
						mSettings[currentSection] = currentSettings;
					}
					else
					{
						currentSettings = seci->second;
					}
                }
                else
                {
                    /* Find the first seperator character and split the string there */
                    std::string::size_type separator_pos = line.find_first_of(separators, 0);
                    if (separator_pos != std::string::npos)
                    {
                        optName = line.substr(0, separator_pos);
                        /* Find the first non-seperator character following the name */
                        std::string::size_type nonseparator_pos = line.find_first_not_of(separators, separator_pos);
                        /* ... and extract the value */
                        /* Make sure we don't crash on an empty setting (it might be a valid value) */
                        optVal = (nonseparator_pos == std::string::npos) ? "" : line.substr(nonseparator_pos);
                        if (trimWhitespace)
                        {
                            StringUtil::trim(optVal);
                            StringUtil::trim(optName);
                        }
                        currentSettings->insert(std::multimap<String, String>::value_type(optName, optVal));
                    }
                }
            }
        }
    }
    //-----------------------------------------------------------------------
    String ConfigFile::getSetting(const String& key, const String& section, const String& defaultValue) const
    {

        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci == mSettings.end())
        {
            return defaultValue;
        }
        else
        {
            SettingsMultiMap::const_iterator i = seci->second->find(key);
            if (i == seci->second->end())
            {
                return defaultValue;
            }
            else
            {
                return i->second;
            }
        }
    }
    //-----------------------------------------------------------------------
    StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const
    {
        StringVector ret;

        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci != mSettings.end())
        {
            SettingsMultiMap::const_iterator i;

            i = seci->second->find(key);
            // Iterate over matches
            while (i != seci->second->end() && i->first == key)
            {
                ret.push_back(i->second);
                ++i;
            }
        }
        return ret;

    }
    //-----------------------------------------------------------------------
    ConfigFile::SettingsIterator ConfigFile::getSettingsIterator(const String& section)
    {
        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci == mSettings.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
                "Cannot find section " + section,
                "ConfigFile::getSettingsIterator");
        }
        else
        {
            return SettingsIterator(seci->second->begin(), seci->second->end());
        }
    }
    //-----------------------------------------------------------------------
    ConfigFile::SectionIterator ConfigFile::getSectionIterator(void)
    {
        return SectionIterator(mSettings.begin(), mSettings.end());
    }

}
<|endoftext|>