<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(XALANVERSION_HEADER_GUARD_1357924680)
#define XALANVERSION_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   H E A D E R   D O C U M E N T A T I O N

/**
 * User Documentation for Xalan Version Values:
 *
 *
 *
 * Xalan  Notes:
 *
 * Xalan Committers Documentation:
 *
 *    Xalan committers normally only need to modify one or two of the
 *    following macros:
 *
 *      XALAN_VERSION_MAJOR
 *      XALAN_VERSION_MINOR
 *      XALAN_VERSION_REVISION
 *
 *    The integer values of these macros define the Xalan version number. All
 *    other constants and preprocessor macros are automatically generated from
 *    these three definitions.
 *
 * Xalan User Documentation:
 *
 *  The following sections in the user documentation have examples based upon
 *  the following three version input values:
 *
 *    #define XALAN_VERSION_MAJOR 19
 *    #define XALAN_VERSION_MINOR 3
 *    #define XALAN_VERSION_REVISION 74
 *
 *  The minor and revision (patch level) numbers have two digits of resolution
 *  which means that '3' becomes '03' in this example. This policy guarantees
 *  that when using preprocessor macros, version 19.3.74 will be greater than
 *  version 1.94.74 since the first will expand to 190374 and the second to
 *  19474.
 *
 *  Preprocessor Macros:
 *
 *    _XALAN_VERSION defines the primary preprocessor macro that users will
 *    introduce into their code to perform conditional compilation where the
 *    version of Xalan is detected in order to enable or disable version
 *    specific capabilities. The value of _XALAN_VERSION for the above example
 *    will be 190374. To use it a user would perform an operation such as the
 *    following:
 *
 *      #if _XALAN_VERSION >= 190374
 *        // code specific to new version of Xalan...
 *      #else
 *        // old code here...
 *      #endif
 *
 *    XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74".
 *
 *    XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19.3.74".
 *
 *    XALAN_VERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19374". This
 *    particular macro is very dangerous if it were to be used for comparing
 *    version numbers since ordering will not be guaranteed.
 *
 *    Xalan_DLLVersionStr is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74". This
 *    macro is provided for backwards compatibility to pre-1.7 versions of
 *    Xalan.
 *
 *  String Constants:
 *
 *    gXalanVersionStr is a global string constant whose value corresponds to
 *    the value "19_3" for the above example.
 *
 *    gXalanFullVersionStr is a global string constant whose value corresponds
 *    to the value "19_3_74" for the above example.
 *
 *  Numeric Constants:
 *
 *    gXalanMajVersion is a global integer constant whose value corresponds to
 *    the major version number. For the above example its value will be 19.
 *
 *    gXalanMinVersion is a global integer constant whose value corresponds to
 *    the minor version number. For the above example its value will be 3.
 *
 *    gXalanRevision is a global integer constant whose value corresponds to
 *    the revision (patch) version number. For the above example its value will
 *    be 74.
 *
 */

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   S P E C I F I C A T I O N

/**
 * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION
 * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
 */

#define XALAN_VERSION_MAJOR 1
#define XALAN_VERSION_MINOR 4
#define XALAN_VERSION_REVISION 0

/** DO NOT MODIFY BELOW THIS LINE */

/**
 * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
 *
 *	Xalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,
 *	gXalanMajVersion, gXalanMinVersion, gXalanRevision
 */

// ---------------------------------------------------------------------------
// T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b

// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)

// ---------------------------------------------------------------------------
// T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c

// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)

// ---------------------------------------------------------------------------
// C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M

#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   I N F O R M A T I O N

// Xalan version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants

#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)

// original from Xalan header
#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR

const char* const    gXalanVersionStr = XALAN_VERSIONSTR;
const char* const    gXalanFullVersionStr = XALAN_FULLVERSIONSTR;
const unsigned int   gXalanMajVersion = XALAN_VERSION_MAJOR;
const unsigned int   gXalanMinVersion = XALAN_VERSION_MINOR;
const unsigned int   gXalanRevision   = XALAN_VERSION_REVISION;

// Xalan version numeric constants that can be used for conditional
// compilation purposes.

#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)

#endif // XALANVERSION_HEADER_GUARD_1357924680
<commit_msg>Bumped minor version number.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(XALANVERSION_HEADER_GUARD_1357924680)
#define XALANVERSION_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   H E A D E R   D O C U M E N T A T I O N

/**
 * User Documentation for Xalan Version Values:
 *
 *
 *
 * Xalan  Notes:
 *
 * Xalan Committers Documentation:
 *
 *    Xalan committers normally only need to modify one or two of the
 *    following macros:
 *
 *      XALAN_VERSION_MAJOR
 *      XALAN_VERSION_MINOR
 *      XALAN_VERSION_REVISION
 *
 *    The integer values of these macros define the Xalan version number. All
 *    other constants and preprocessor macros are automatically generated from
 *    these three definitions.
 *
 * Xalan User Documentation:
 *
 *  The following sections in the user documentation have examples based upon
 *  the following three version input values:
 *
 *    #define XALAN_VERSION_MAJOR 19
 *    #define XALAN_VERSION_MINOR 3
 *    #define XALAN_VERSION_REVISION 74
 *
 *  The minor and revision (patch level) numbers have two digits of resolution
 *  which means that '3' becomes '03' in this example. This policy guarantees
 *  that when using preprocessor macros, version 19.3.74 will be greater than
 *  version 1.94.74 since the first will expand to 190374 and the second to
 *  19474.
 *
 *  Preprocessor Macros:
 *
 *    _XALAN_VERSION defines the primary preprocessor macro that users will
 *    introduce into their code to perform conditional compilation where the
 *    version of Xalan is detected in order to enable or disable version
 *    specific capabilities. The value of _XALAN_VERSION for the above example
 *    will be 190374. To use it a user would perform an operation such as the
 *    following:
 *
 *      #if _XALAN_VERSION >= 190374
 *        // code specific to new version of Xalan...
 *      #else
 *        // old code here...
 *      #endif
 *
 *    XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74".
 *
 *    XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19.3.74".
 *
 *    XALAN_VERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19374". This
 *    particular macro is very dangerous if it were to be used for comparing
 *    version numbers since ordering will not be guaranteed.
 *
 *    Xalan_DLLVersionStr is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74". This
 *    macro is provided for backwards compatibility to pre-1.7 versions of
 *    Xalan.
 *
 *  String Constants:
 *
 *    gXalanVersionStr is a global string constant whose value corresponds to
 *    the value "19_3" for the above example.
 *
 *    gXalanFullVersionStr is a global string constant whose value corresponds
 *    to the value "19_3_74" for the above example.
 *
 *  Numeric Constants:
 *
 *    gXalanMajVersion is a global integer constant whose value corresponds to
 *    the major version number. For the above example its value will be 19.
 *
 *    gXalanMinVersion is a global integer constant whose value corresponds to
 *    the minor version number. For the above example its value will be 3.
 *
 *    gXalanRevision is a global integer constant whose value corresponds to
 *    the revision (patch) version number. For the above example its value will
 *    be 74.
 *
 */

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   S P E C I F I C A T I O N

/**
 * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION
 * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
 */

#define XALAN_VERSION_MAJOR 1
#define XALAN_VERSION_MINOR 5
#define XALAN_VERSION_REVISION 0

/** DO NOT MODIFY BELOW THIS LINE */

/**
 * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
 *
 *	Xalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,
 *	gXalanMajVersion, gXalanMinVersion, gXalanRevision
 */

// ---------------------------------------------------------------------------
// T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b

// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)

// ---------------------------------------------------------------------------
// T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c

// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)

// ---------------------------------------------------------------------------
// C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M

#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )

// ---------------------------------------------------------------------------
// X A L A N   V E R S I O N   I N F O R M A T I O N

// Xalan version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants

#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)

// original from Xalan header
#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR

const char* const    gXalanVersionStr = XALAN_VERSIONSTR;
const char* const    gXalanFullVersionStr = XALAN_FULLVERSIONSTR;
const unsigned int   gXalanMajVersion = XALAN_VERSION_MAJOR;
const unsigned int   gXalanMinVersion = XALAN_VERSION_MINOR;
const unsigned int   gXalanRevision   = XALAN_VERSION_REVISION;

// Xalan version numeric constants that can be used for conditional
// compilation purposes.

#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)

#endif // XALANVERSION_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>//************************************************************/
//
//	Frame Options Implementation
//
//	Implements the SPXPlotConfiguration class, which describes the options
//	for each frame to plot. The options are:
//
//		data_steering_files -- Comma separated list of all data steering files
//		grid_steering_files -- Comma separated list of all grid steering files
//		marker_style -- Comma separated list of marker style options
//		marker_color -- Comma separated list of marker color options
//
//		Optional options:
//
//			ref_line_style -- Reference line style list
//			ref_line_color -- Reference line color list
//			desc -- Description of the entire plot (not a list)
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		29.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <stdlib.h> //atoi

#include "SPXPlotConfiguration.h"
#include "SPXUtilities.h"

//Class names for debug statements
const std::string cn = "SPXPlotConfiguration::";

//Must define the static debug variable in the implementation
bool SPXPlotConfiguration::debug;
bool SPXPlotConfigurationInstance::debug;

//Constructs an SPXPlotConfiguration object with a vector of string vectors, where indices are:
//	options[0] --> Vector of data steering files
//	options[1] --> Vector of grid steering files
//	options[2] --> Vector of marker styles
//	options[3] --> Vector of marker colors
// 	options[4] --> Vector of reference line styles (optional)
//	options[5] --> Vector of reference line colors (optional)
//
//Description is the (optional) frame description
//And numberOfConfigurationInstances is the size of the vector of string vectors
SPXPlotConfiguration::SPXPlotConfiguration(const std::vector<std::vector<std::string> > & options, const std::string description, unsigned int numberOfConfigurationInstances) {
	this->SetDefaults();
	this->description = description;
	this->numberOfConfigurationInstances = numberOfConfigurationInstances;

	//Attempt to parse the options instances
	try {
		this->Parse(options);
	} catch(const SPXException &e) {
		std::cerr << e.what() << std::endl;

		throw SPXParseException("Unable to parse SPXPlotConfiguration instances");
	}
}

//Parse the vector of vector of strings into a vector of SPXPlotConfigurationInstances, convert
//	strings to integers where needed, and check each instance for errors (and IsEmpty) before
//	adding it to the vector (call AddOptionsInstance(), which checks IsEmpty and IsValid)
void SPXPlotConfiguration::Parse(const std::vector<std::vector<std::string> > & options) {
	std::string mn = "Parse: ";

	//Return false if size of options vector is less than 4
	if(options.size() < 4) {
		std::ostringstream oss;

		oss << "Too few vectors in options vector: Only " << options.size() << " options: Options vector MUST contain vectors for:" << std::endl;
		oss << "\t Data Steering Files" << std::endl;
		oss << "\t Grid Steering Files" << std::endl;
		oss << "\t Marker Styles" << std::endl;
		oss << "\t Marker Colors" << std::endl;

		oss << "\t\t\t\t\t And optionally for:" << std::endl;
		oss << "\t Reference Line Styles" << std::endl;
		oss << "\t Reference Line Colors";

		throw SPXParseException(oss.str());
	}

	if(debug) {
		std::cout << cn << mn << "Parsing frame options vector:" << std::endl;

		std::vector<std::string> tmpVector;

		tmpVector = options[0];
		std::cout << "\tdata_steering_files = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[1];
		std::cout << "\tgrid_steering_files = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[2];
		std::cout << "\tmarker_style = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[3];
		std::cout << "\tmarker_color = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		if(options.size() >= 5) {
			tmpVector = options[4];
			std::cout << "\tref_line_style = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;
		} else {
			if(debug) std::cout << cn << mn << "No reference line style option specified" << std::endl;
		}

		if(options.size() == 6) {
			tmpVector = options[5];
			std::cout << "\tref_line_color = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;
		} else {
			if(debug) std::cout << cn << mn << "No reference line color option specified" << std::endl;
		}
	}

	if(debug) std::cout << cn << mn << "numberOfConfigurationInstances = " << numberOfConfigurationInstances << std::endl;

	//Check options vector sizes against numberOfConfigurationInstances (should ALL be equal)
	if(numberOfConfigurationInstances != options[0].size()) {
		std::ostringstream oss;
		oss << "Size of Data Steering File vector (" << options[0].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[1].size()) {
		std::ostringstream oss;
		oss << "Size of Grid Steering File vector (" << options[1].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[2].size()) {
		std::ostringstream oss;
		oss << "Size of Marker Style vector (" << options[2].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[3].size()) {
		std::ostringstream oss;
		oss << "Size of Marker Color vector (" << options[3].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}

	if(options.size() >= 5) {
		if(numberOfConfigurationInstances != options[4].size()) {
			std::ostringstream oss;
			oss << "Size of Reference Line Style vector (" << options[4].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
			throw SPXParseException(oss.str());
		}
	}

	if(options.size() == 6) {
		if(numberOfConfigurationInstances != options[5].size()) {
			std::ostringstream oss;
			oss << "Size of Reference Line Color vector (" << options[5].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
			throw SPXParseException(oss.str());
		}
	}

	//For each options instance, create an SPXPlotConfigurationInstance object and add it to the vector
	for(int i = 0; i < numberOfConfigurationInstances; i++) {
		SPXPlotConfigurationInstance pci;
		pci.SetDefaults();

		//Create objects and set the filename for the Data/Grid Steering Files
		pci.dataSteeringFile = SPXDataSteeringFile(options[0][i]);
		pci.gridSteeringFile = SPXGridSteeringFile(options[1][i]);

		pci.markerStyle = atoi(options[2][i].c_str());
		pci.markerColor = atoi(options[3][i].c_str());

		if(options.size() >= 5) {
			pci.refLineStyle = atoi(options[4][i].c_str());
		}

		if(options.size() == 6) {
			pci.refLineColor = atoi(options[5][i].c_str());
		}

		//Attempt to add the configuration instance
		try {
			AddConfigurationInstance(pci);
		} catch(const SPXException &e) {
			std::cerr << e.what() << std::endl;

			throw SPXParseException("ERROR: Could not add options configuration to configuration instance vector: Instance was empty or invalid");
		}
	}
}

//Print displays the output of ToString to the console
/*
void SPXPlotConfiguration::Print(void) {
	std::string mn = "Print: ";
	//std::cout << this->ToString() << std::endl;
}
*/

//ToString does the opposite of Parse
/*
const std::string & SPXPlotConfiguration::ToString(void) const {
	std::string mn = "ToString: ";

	//Empty frame options
	if(this->IsEmpty()) {
		return "";
	}

	//Check for validity
	if(!this->IsValid()) {
		return "INVALID_FRAME_OPTIONS";
	}

}
*/

//Determines whether the Frame Options object is empty or not
bool SPXPlotConfiguration::IsEmpty(void) {
	std::string mn = "IsEmpty: ";

	//Return true if all options vector is empty and numberOfConfigurationInstances is 0
	if((numberOfConfigurationInstances == 0) && (configurationInstances.size() == 0)) {
		return true;
	}

	return false;
}

//Determines the validity of the frame options
bool SPXPlotConfiguration::IsValid(void) {
	std::string mn = "IsValid: ";

	//Valid, but empty
	if(IsEmpty()) {
		return true;
	}

	//Return false if the numberOfConfigurationInstances does not match the size of the configurationInstances vector
	if(numberOfConfigurationInstances != configurationInstances.size()) {
		if(debug) std::cout << cn << mn << "Size of Options Instances vector (" << configurationInstances.size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")" << std::endl;
		return false;
	}

	//Return false if ANY of the frame options are invalid
	for(int i = 0; i < numberOfConfigurationInstances; i++) {
		if(!configurationInstances[i].IsValid()) {
			if(debug) std::cout << cn << mn << "An invalid options instance was found at index " << i << std::endl;
			return false;
		}
	}

	return true;
}

<commit_msg>Added x and y scale. STILL NEED TO PARSE! NEED TO CHANGE vector<vector<string>> to map<string, vector<string>>...<commit_after>//************************************************************/
//
//	Frame Options Implementation
//
//	Implements the SPXPlotConfiguration class, which describes the options
//	for each frame to plot. The options are:
//
//		data_steering_files -- Comma separated list of all data steering files
//		grid_steering_files -- Comma separated list of all grid steering files
//		marker_style -- Comma separated list of marker style options
//		marker_color -- Comma separated list of marker color options
//
//		Optional options:
//
//			ref_line_style -- Reference line style list
//			ref_line_color -- Reference line color list
//			desc -- Description of the entire plot (not a list)
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		29.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <stdlib.h> //atoi

#include "SPXPlotConfiguration.h"
#include "SPXUtilities.h"

//Class names for debug statements
const std::string cn = "SPXPlotConfiguration::";

//Must define the static debug variable in the implementation
bool SPXPlotConfiguration::debug;
bool SPXPlotConfigurationInstance::debug;

//Constructs an SPXPlotConfiguration object with a vector of string vectors, where indices are:
//	options[0] --> Vector of data steering files
//	options[1] --> Vector of grid steering files
//	options[2] --> Vector of marker styles
//	options[3] --> Vector of marker colors
// 	options[4] --> Vector of reference line styles (optional)
//	options[5] --> Vector of reference line colors (optional)
//
//Description is the (optional) frame description
//And numberOfConfigurationInstances is the size of the vector of string vectors
SPXPlotConfiguration::SPXPlotConfiguration(const std::vector<std::vector<std::string> > & options, const std::string description, unsigned int numberOfConfigurationInstances) {
	this->SetDefaults();
	this->description = description;
	this->numberOfConfigurationInstances = numberOfConfigurationInstances;

	//Attempt to parse the options instances
	try {
		this->Parse(options);
	} catch(const SPXException &e) {
		std::cerr << e.what() << std::endl;

		throw SPXParseException("Unable to parse SPXPlotConfiguration instances");
	}
}

//Parse the vector of vector of strings into a vector of SPXPlotConfigurationInstances, convert
//	strings to integers where needed, and check each instance for errors (and IsEmpty) before
//	adding it to the vector (call AddOptionsInstance(), which checks IsEmpty and IsValid)
void SPXPlotConfiguration::Parse(const std::vector<std::vector<std::string> > & options) {
	std::string mn = "Parse: ";

	//Return false if size of options vector is less than 4
	if(options.size() < 4) {
		std::ostringstream oss;

		oss << "Too few vectors in options vector: Only " << options.size() << " options: Options vector MUST contain vectors for:" << std::endl;
		oss << "\t Data Steering Files" << std::endl;
		oss << "\t Grid Steering Files" << std::endl;
		oss << "\t Marker Styles" << std::endl;
		oss << "\t Marker Colors" << std::endl;

		oss << "\t\t\t\t\t And optionally for:" << std::endl;
		oss << "\t Reference Line Styles" << std::endl;
		oss << "\t Reference Line Colors" << std::endl;
		oss << "\t X Scale" << std::endl;
		oss << "\t Y Scale";

		throw SPXParseException(oss.str());
	}

	if(debug) {
		std::cout << cn << mn << "Parsing frame options vector:" << std::endl;

		std::vector<std::string> tmpVector;

		tmpVector = options[0];
		std::cout << "\tdata_steering_files = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[1];
		std::cout << "\tgrid_steering_files = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[2];
		std::cout << "\tmarker_style = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		tmpVector = options[3];
		std::cout << "\tmarker_color = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;

		if(options.size() >= 5) {
			tmpVector = options[4];
			std::cout << "\tref_line_style = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;
		} else {
			if(debug) std::cout << cn << mn << "No reference line style option specified" << std::endl;
		}

		if(options.size() == 6) {
			tmpVector = options[5];
			std::cout << "\tref_line_color = " << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;
		} else {
			if(debug) std::cout << cn << mn << "No reference line color option specified" << std::endl;
		}
	}

	if(debug) std::cout << cn << mn << "numberOfConfigurationInstances = " << numberOfConfigurationInstances << std::endl;

	//Check options vector sizes against numberOfConfigurationInstances (should ALL be equal)
	if(numberOfConfigurationInstances != options[0].size()) {
		std::ostringstream oss;
		oss << "Size of Data Steering File vector (" << options[0].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[1].size()) {
		std::ostringstream oss;
		oss << "Size of Grid Steering File vector (" << options[1].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[2].size()) {
		std::ostringstream oss;
		oss << "Size of Marker Style vector (" << options[2].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}
	if(numberOfConfigurationInstances != options[3].size()) {
		std::ostringstream oss;
		oss << "Size of Marker Color vector (" << options[3].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
		throw SPXParseException(oss.str());
	}

	if(options.size() >= 5) {
		if(numberOfConfigurationInstances != options[4].size()) {
			std::ostringstream oss;
			oss << "Size of Reference Line Style vector (" << options[4].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
			throw SPXParseException(oss.str());
		}
	}

	if(options.size() == 6) {
		if(numberOfConfigurationInstances != options[5].size()) {
			std::ostringstream oss;
			oss << "Size of Reference Line Color vector (" << options[5].size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")";
			throw SPXParseException(oss.str());
		}
	}

	//For each options instance, create an SPXPlotConfigurationInstance object and add it to the vector
	for(int i = 0; i < numberOfConfigurationInstances; i++) {
		SPXPlotConfigurationInstance pci;
		pci.SetDefaults();

		//Create objects and set the filename for the Data/Grid Steering Files
		pci.dataSteeringFile = SPXDataSteeringFile(options[0][i]);
		pci.gridSteeringFile = SPXGridSteeringFile(options[1][i]);

		pci.markerStyle = atoi(options[2][i].c_str());
		pci.markerColor = atoi(options[3][i].c_str());

		if(options.size() >= 5) {
			pci.refLineStyle = atoi(options[4][i].c_str());
		}

		if(options.size() == 6) {
			pci.refLineColor = atoi(options[5][i].c_str());
		}

		//Attempt to add the configuration instance
		try {
			AddConfigurationInstance(pci);
		} catch(const SPXException &e) {
			std::cerr << e.what() << std::endl;

			throw SPXParseException("ERROR: Could not add options configuration to configuration instance vector: Instance was empty or invalid");
		}
	}
}

//Print displays the output of ToString to the console
/*
void SPXPlotConfiguration::Print(void) {
	std::string mn = "Print: ";
	//std::cout << this->ToString() << std::endl;
}
*/

//ToString does the opposite of Parse
/*
const std::string & SPXPlotConfiguration::ToString(void) const {
	std::string mn = "ToString: ";

	//Empty frame options
	if(this->IsEmpty()) {
		return "";
	}

	//Check for validity
	if(!this->IsValid()) {
		return "INVALID_FRAME_OPTIONS";
	}

}
*/

//Determines whether the Frame Options object is empty or not
bool SPXPlotConfiguration::IsEmpty(void) {
	std::string mn = "IsEmpty: ";

	//Return true if all options vector is empty and numberOfConfigurationInstances is 0
	if((numberOfConfigurationInstances == 0) && (configurationInstances.size() == 0)) {
		return true;
	}

	return false;
}

//Determines the validity of the frame options
bool SPXPlotConfiguration::IsValid(void) {
	std::string mn = "IsValid: ";

	//Valid, but empty
	if(IsEmpty()) {
		return true;
	}

	//Return false if the numberOfConfigurationInstances does not match the size of the configurationInstances vector
	if(numberOfConfigurationInstances != configurationInstances.size()) {
		if(debug) std::cout << cn << mn << "Size of Options Instances vector (" << configurationInstances.size() << ") is NOT equal to the number of options instances (" << numberOfConfigurationInstances << ")" << std::endl;
		return false;
	}

	//Return false if ANY of the frame options are invalid
	for(int i = 0; i < numberOfConfigurationInstances; i++) {
		if(!configurationInstances[i].IsValid()) {
			if(debug) std::cout << cn << mn << "An invalid options instance was found at index " << i << std::endl;
			return false;
		}
	}

	return true;
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <objbase.h>
#include "memfile.hpp"
#include <cassert>

MemFile::MemFile() :
    m_hFile(INVALID_HANDLE_VALUE),
    m_hMap(0),
    m_pView(0),
    m_size(0)
{
}

MemFile::~MemFile()
{
    const HRESULT hr = Close();
    hr;
    assert(SUCCEEDED(hr));
}

HRESULT MemFile::Open(const wchar_t* strFileName)
{
    if (strFileName == 0)
        return E_INVALIDARG;

    if (m_hFile != INVALID_HANDLE_VALUE)
        return E_UNEXPECTED;

    assert(m_hMap == 0);
    assert(m_pView == 0);

    m_hFile = CreateFile(
                strFileName,
                GENERIC_READ,
                0,  //no sharing
                0,  //security attributes
                OPEN_EXISTING,
                FILE_ATTRIBUTE_READONLY,
                0);

    if (m_hFile == INVALID_HANDLE_VALUE)
    {
        const DWORD e = GetLastError();
        return HRESULT_FROM_WIN32(e);
    }

    LARGE_INTEGER size;

    const BOOL b = GetFileSizeEx(m_hFile, &size);

    if (!b)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    m_size = size.QuadPart;
    assert(m_size >= 0);

    m_hMap = CreateFileMapping(m_hFile, 0, PAGE_READONLY, 0, 0, 0);

    if (m_hMap == 0)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    m_pView = MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);

    if (m_pView == 0)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    return S_OK;
}

HRESULT MemFile::Close()
{
    if (m_hFile == INVALID_HANDLE_VALUE)  //already closed
        return S_FALSE;

    if (m_pView)
    {
        const BOOL b = UnmapViewOfFile(m_pView);
        assert(b);

        m_pView = 0;
    }

    if (m_hMap)
    {
        const BOOL b = CloseHandle(m_hMap);
        assert(b);

        m_hMap = 0;
    }

    m_size = 0;

    const BOOL b = CloseHandle(m_hFile);

    m_hFile = INVALID_HANDLE_VALUE;

    if (b)
        return S_OK;

    const DWORD e = GetLastError();
    return HRESULT_FROM_WIN32(e);
}

bool MemFile::IsOpen() const
{
    return (m_hFile != INVALID_HANDLE_VALUE);
}

HRESULT MemFile::GetView(
    const BYTE*& buf,
    LONGLONG& len) const
{
    if (!IsOpen())
        return E_FAIL;

    buf = static_cast<const BYTE*>(m_pView);
    len = m_size;

    return S_OK;
}
<commit_msg>makewebm: use DELETE_ON_CLOSE when opening stats buffer file<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <objbase.h>
#include "memfile.hpp"
#include <cassert>

MemFile::MemFile() :
    m_hFile(INVALID_HANDLE_VALUE),
    m_hMap(0),
    m_pView(0),
    m_size(0)
{
}

MemFile::~MemFile()
{
    const HRESULT hr = Close();
    hr;
    assert(SUCCEEDED(hr));
}

HRESULT MemFile::Open(const wchar_t* strFileName)
{
    if (strFileName == 0)
        return E_INVALIDARG;

    if (m_hFile != INVALID_HANDLE_VALUE)
        return E_UNEXPECTED;

    assert(m_hMap == 0);
    assert(m_pView == 0);

    m_hFile = CreateFile(
                strFileName,
                GENERIC_READ,
                0,  //no sharing
                0,  //security attributes
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                0);

    if (m_hFile == INVALID_HANDLE_VALUE)
    {
        const DWORD e = GetLastError();
        return HRESULT_FROM_WIN32(e);
    }

    LARGE_INTEGER size;

    const BOOL b = GetFileSizeEx(m_hFile, &size);

    if (!b)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    m_size = size.QuadPart;
    assert(m_size >= 0);

    m_hMap = CreateFileMapping(m_hFile, 0, PAGE_READONLY, 0, 0, 0);

    if (m_hMap == 0)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    m_pView = MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);

    if (m_pView == 0)
    {
        const DWORD e = GetLastError();
        Close();
        return HRESULT_FROM_WIN32(e);
    }

    return S_OK;
}

HRESULT MemFile::Close()
{
    if (m_hFile == INVALID_HANDLE_VALUE)  //already closed
        return S_FALSE;

    if (m_pView)
    {
        const BOOL b = UnmapViewOfFile(m_pView);
        assert(b);

        m_pView = 0;
    }

    if (m_hMap)
    {
        const BOOL b = CloseHandle(m_hMap);
        assert(b);

        m_hMap = 0;
    }

    m_size = 0;

    const BOOL b = CloseHandle(m_hFile);

    m_hFile = INVALID_HANDLE_VALUE;

    if (b)
        return S_OK;

    const DWORD e = GetLastError();
    return HRESULT_FROM_WIN32(e);
}

bool MemFile::IsOpen() const
{
    return (m_hFile != INVALID_HANDLE_VALUE);
}

HRESULT MemFile::GetView(
    const BYTE*& buf,
    LONGLONG& len) const
{
    if (!IsOpen())
        return E_FAIL;

    buf = static_cast<const BYTE*>(m_pView);
    len = m_size;

    return S_OK;
}
<|endoftext|>


<commit_before>#include "InlierDetector.hpp"

namespace registration {

void InlierDetector::set_input(const FeatureMat * const inFeatures,
                        const FeatureMat * const inCorrespondingFeatures,
                        const VecDynFloat * const inCorrespondingFlags)
{
    //# Set input
    _inFeatures = inFeatures;
    _inCorrespondingFeatures = inCorrespondingFeatures;
    _inCorrespondingFlags = inCorrespondingFlags;

    //# Update internal variables
    _numElements = _inFeatures->rows();
}

void InlierDetector::set_output(VecDynFloat * const ioProbability)
{
    _ioProbability = ioProbability;
}

void InlierDetector::set_parameters(const float kappa, const bool useOrientation)
{
    _kappa = kappa;
    _useOrientation = useOrientation;
}

void InlierDetector::update() {

//    _parameterList["jos"] = 2.0f;
//    _parameterList.insert(std::make_pair("ljkewqr", 3));
//    _parameterList.insert(std::make_pair("beschrijving", "Wat een moeilijkheden"));
//    _parameterList.insert(std::make_pair("inlierKappa", int(3)));
//    std::cout << "Parameter list 'beschrijving':" << _parameterList["beschrijving"] << std::endl;
//
//    DictionaryType::iterator it = _parameterList.begin();
//    while(it != _parameterList.end())
//    {
//        std::cout<<it->first<<" :: "<<it->second<<std::endl;
//        it++;
//    }

    //# Flag based inlier/outlier classification
    //## If a floating node is attracted to a corresponding node with flag 0.0,
    //## its inlier weight should be made zero as well. So we can use the
    //## corresponding flags as a first way to determine inlier weights for the
    //## floating nodes.
    //## -> Initialize the probabilities as a copy of the flags
    *_ioProbability = *_inCorrespondingFlags;

    //# Distance based inlier/outlier classification
    //## Re-calculate the parameters sigma and lambda
    float sigmaa = 0.0;
    float lambdaa = 0.0;
    float sigmaNumerator = 0.0;
    float sigmaDenominator = 0.0;
    //DEBUG
    std::cout << "===========================" << std::endl;
    std::cout << "Computing SIGMA." << std::endl;
    //END DEBUG
    for (size_t i = 0 ; i < _numElements ; i++) {
        //### Compute distance (squared)
        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);
        const float distanceSquared = difVector.squaredNorm();

        sigmaNumerator += (*_ioProbability)[i] * distanceSquared;
        sigmaDenominator += (*_ioProbability)[i];
    }
    //### sigma and lambda
    sigmaa = std::sqrt(sigmaNumerator/sigmaDenominator);
    if (sigmaa < _minimalSigma) {sigmaa = _minimalSigma;}
    else if (sigmaa > _maximalSigma) {sigmaa = _maximalSigma;}

    lambdaa = 1.0/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * _kappa * _kappa);

    //## Recalculate the distance-based probabilities
    for (size_t i = 0 ; i < _numElements ; i++) {
        //### Get squared distance
        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);
        const float distanceSquared = difVector.squaredNorm();
        //### Compute probability
        float probability = 1.0/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * distanceSquared / std::pow(sigmaa, 2.0));
        probability /= (probability + lambdaa);
        (*_ioProbability)[i] *= probability;

    }

    //#Gradient Based inlier/outlier classification
    if (_useOrientation){
        float averageOrientationInlierWeight = 0.0f; //simply to warn the user when this is too low, they probably have the normals flipped.
        for (size_t i = 0 ; i < _numElements ; i++) {
            const Vec3Float normal = _inFeatures->row(i).tail(3);
            const Vec3Float correspondingNormal = _inCorrespondingFeatures->row(i).tail(3);
            //## Dot product gives an idea of how well they point in the same
            //## direction. This gives a weight between -1.0 and +1.0
            const float dotProduct = normal.dot(correspondingNormal);
            //## Rescale this result so that it's continuous between 0.0 and +1.0
            float probability = dotProduct / 2.0 + 0.5;
            (*_ioProbability)[i] *= probability;
            averageOrientationInlierWeight += probability;
        }

        averageOrientationInlierWeight /= _numElements;
        if (averageOrientationInlierWeight < 0.5f) {
            std::cout << "Warning: very low inlier weights due to surface normals. Are you sure one of the surfaces doesn't have its vertex normals flipped?" <<std::endl;
        }
    }

}//end inlier_detection

}
<commit_msg>Further cleaned print commands.<commit_after>#include "InlierDetector.hpp"

namespace registration {

void InlierDetector::set_input(const FeatureMat * const inFeatures,
                        const FeatureMat * const inCorrespondingFeatures,
                        const VecDynFloat * const inCorrespondingFlags)
{
    //# Set input
    _inFeatures = inFeatures;
    _inCorrespondingFeatures = inCorrespondingFeatures;
    _inCorrespondingFlags = inCorrespondingFlags;

    //# Update internal variables
    _numElements = _inFeatures->rows();
}

void InlierDetector::set_output(VecDynFloat * const ioProbability)
{
    _ioProbability = ioProbability;
}

void InlierDetector::set_parameters(const float kappa, const bool useOrientation)
{
    _kappa = kappa;
    _useOrientation = useOrientation;
}

void InlierDetector::update() {

//    _parameterList["jos"] = 2.0f;
//    _parameterList.insert(std::make_pair("ljkewqr", 3));
//    _parameterList.insert(std::make_pair("beschrijving", "Wat een moeilijkheden"));
//    _parameterList.insert(std::make_pair("inlierKappa", int(3)));
//    std::cout << "Parameter list 'beschrijving':" << _parameterList["beschrijving"] << std::endl;
//
//    DictionaryType::iterator it = _parameterList.begin();
//    while(it != _parameterList.end())
//    {
//        std::cout<<it->first<<" :: "<<it->second<<std::endl;
//        it++;
//    }

    //# Flag based inlier/outlier classification
    //## If a floating node is attracted to a corresponding node with flag 0.0,
    //## its inlier weight should be made zero as well. So we can use the
    //## corresponding flags as a first way to determine inlier weights for the
    //## floating nodes.
    //## -> Initialize the probabilities as a copy of the flags
    *_ioProbability = *_inCorrespondingFlags;

    //# Distance based inlier/outlier classification
    //## Re-calculate the parameters sigma and lambda
    float sigmaa = 0.0;
    float lambdaa = 0.0;
    float sigmaNumerator = 0.0;
    float sigmaDenominator = 0.0;
    for (size_t i = 0 ; i < _numElements ; i++) {
        //### Compute distance (squared)
        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);
        const float distanceSquared = difVector.squaredNorm();

        sigmaNumerator += (*_ioProbability)[i] * distanceSquared;
        sigmaDenominator += (*_ioProbability)[i];
    }
    //### sigma and lambda
    sigmaa = std::sqrt(sigmaNumerator/sigmaDenominator);
    if (sigmaa < _minimalSigma) {sigmaa = _minimalSigma;}
    else if (sigmaa > _maximalSigma) {sigmaa = _maximalSigma;}

    lambdaa = 1.0/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * _kappa * _kappa);

    //## Recalculate the distance-based probabilities
    for (size_t i = 0 ; i < _numElements ; i++) {
        //### Get squared distance
        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);
        const float distanceSquared = difVector.squaredNorm();
        //### Compute probability
        float probability = 1.0/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * distanceSquared / std::pow(sigmaa, 2.0));
        probability /= (probability + lambdaa);
        (*_ioProbability)[i] *= probability;

    }

    //#Gradient Based inlier/outlier classification
    if (_useOrientation){
        float averageOrientationInlierWeight = 0.0f; //simply to warn the user when this is too low, they probably have the normals flipped.
        for (size_t i = 0 ; i < _numElements ; i++) {
            const Vec3Float normal = _inFeatures->row(i).tail(3);
            const Vec3Float correspondingNormal = _inCorrespondingFeatures->row(i).tail(3);
            //## Dot product gives an idea of how well they point in the same
            //## direction. This gives a weight between -1.0 and +1.0
            const float dotProduct = normal.dot(correspondingNormal);
            //## Rescale this result so that it's continuous between 0.0 and +1.0
            float probability = dotProduct / 2.0 + 0.5;
            (*_ioProbability)[i] *= probability;
            averageOrientationInlierWeight += probability;
        }

        averageOrientationInlierWeight /= _numElements;
        if (averageOrientationInlierWeight < 0.5f) {
            std::cout << "Warning: very low inlier weights due to surface normals. Are you sure one of the surfaces doesn't have its vertex normals flipped?" <<std::endl;
        }
    }

}//end inlier_detection

}
<|endoftext|>


<commit_before>#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <QtTest/QtTest>

#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Debug>

#include <telepathy-glib/debug.h>

#include <tests/lib/glib/contactlist/conn.h>
#include <tests/lib/test.h>

using namespace Tp;

class TestConnRoster : public Test
{
    Q_OBJECT

public:
    TestConnRoster(QObject *parent = 0)
        : Test(parent), mConnService(0)
    { }

protected Q_SLOTS:
    void expectConnInvalidated();
    void expectPendingContactsFinished(Tp::PendingOperation *);
    void expectPresenceStateChanged(Tp::Contact::PresenceState);
    void expectAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testRoster();

    void cleanup();
    void cleanupTestCase();

private:
    QString mConnName, mConnPath;
    ExampleContactListConnection *mConnService;
    ConnectionPtr mConn;
    QList<ContactPtr> mContacts;
    int mHowManyKnownContacts;
};

void TestConnRoster::expectConnInvalidated()
{
    mLoop->exit(0);
}

void TestConnRoster::expectPendingContactsFinished(PendingOperation *op)
{
    if (!op->isFinished()) {
        qWarning() << "unfinished";
        mLoop->exit(1);
        return;
    }

    if (op->isError()) {
        qWarning().nospace() << op->errorName()
            << ": " << op->errorMessage();
        mLoop->exit(2);
        return;
    }

    if (!op->isValid()) {
        qWarning() << "inconsistent results";
        mLoop->exit(3);
        return;
    }

    qDebug() << "finished";
    PendingContacts *pending = qobject_cast<PendingContacts *>(op);
    mContacts = pending->contacts();

    mLoop->exit(0);
}

void TestConnRoster::expectAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed)
{
    qDebug() << added.size() << " contacts added, " << removed.size() << " contacts removed";
    mHowManyKnownContacts += added.size();
    mHowManyKnownContacts -= removed.size();
    if (mConn->contactManager()->allKnownContacts().size() != mHowManyKnownContacts) {
        qWarning() << "Contacts number mismatch! Watched value: " << mHowManyKnownContacts
                   << "allKnownContacts(): " << mConn->contactManager()->allKnownContacts().size();
        mLoop->exit(1);
    } else {
        mLoop->exit(0);
    }
}

void TestConnRoster::expectPresenceStateChanged(Contact::PresenceState state)
{
    mLoop->exit(0);
}

void TestConnRoster::initTestCase()
{
    initTestCaseImpl();

    g_type_init();
    g_set_prgname("conn-roster");
    tp_debug_set_flags("all");
    dbus_g_bus_get(DBUS_BUS_STARTER, 0);

    gchar *name;
    gchar *connPath;
    GError *error = 0;

    mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new(
            EXAMPLE_TYPE_CONTACT_LIST_CONNECTION,
            "account", "me@example.com",
            "protocol", "contactlist",
            "simulation-delay", 1,
            NULL));
    QVERIFY(mConnService != 0);
    QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),
                "contacts", &name, &connPath, &error));
    QVERIFY(error == 0);

    QVERIFY(name != 0);
    QVERIFY(connPath != 0);

    mConnName = QLatin1String(name);
    mConnPath = QLatin1String(connPath);

    g_free(name);
    g_free(connPath);
}

void TestConnRoster::init()
{
    initImpl();

    mConn = Connection::create(mConnName, mConnPath);

    QVERIFY(connect(mConn->requestConnect(),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QCOMPARE(mConn->isReady(), true);
    QCOMPARE(mConn->status(), Connection::StatusConnected);
}

void TestConnRoster::testRoster()
{
    Features features = Features() << Connection::FeatureRoster;
    QVERIFY(connect(mConn->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QCOMPARE(mConn->isReady(features), true);

    QStringList toCheck = QStringList() <<
        QLatin1String("sjoerd@example.com") <<
        QLatin1String("travis@example.com") <<
        QLatin1String("wim@example.com") <<
        QLatin1String("olivier@example.com") <<
        QLatin1String("helen@example.com") <<
        QLatin1String("geraldine@example.com") <<
        QLatin1String("guillaume@example.com") <<
        QLatin1String("christian@example.com");
    QStringList ids;
    QList<ContactPtr> pendingSubscription;
    QList<ContactPtr> pendingPublish;
    Q_FOREACH (const ContactPtr &contact,
            mConn->contactManager()->allKnownContacts()) {
        qDebug() << " contact:" << contact->id() <<
            "- subscription:" << contact->subscriptionState() <<
            "- publish:" << contact->publishState();
        ids << contact->id();
        if (contact->subscriptionState() == Contact::PresenceStateAsk) {
            pendingSubscription.append(contact);
        } else if (contact->publishState() == Contact::PresenceStateAsk) {
            pendingPublish.append(contact);
        }
    }
    ids.sort();
    toCheck.sort();
    QCOMPARE(ids, toCheck);
    QCOMPARE(pendingSubscription.size(), 2);
    QCOMPARE(pendingPublish.size(), 2);

    // Wait for the contacts to be built
    ids = QStringList() << QString(QLatin1String("john@example.com"))
        << QString(QLatin1String("mary@example.com"));
    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);

    int i = 0;

    Q_FOREACH (const ContactPtr &contact, mContacts) {
        QVERIFY(connect(contact.data(),
                        SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));
        QVERIFY(connect(contact.data(),
                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));
        if ((i % 2) == 0) {
            contact->requestPresenceSubscription(QLatin1String("please add me"));
        } else {
            contact->requestPresenceSubscription(QLatin1String("add me now"));
        }

        QCOMPARE(mLoop->exec(), 0);

        if ((i % 2) == 0) {
            // I asked to see his presence - he might have already accepted it, though
            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk
                    || contact->subscriptionState() == Contact::PresenceStateYes);

            // if he accepted it already, one iteration won't be enough as the
            // first iteration will just flush the subscription -> Yes event
            while (contact->publishState() != Contact::PresenceStateAsk) {
                QCOMPARE(mLoop->exec(), 0);
            }

            contact->authorizePresencePublication();
            QCOMPARE(mLoop->exec(), 0);
            // I authorized him to see my presence
            QCOMPARE(static_cast<uint>(contact->publishState()),
                     static_cast<uint>(Contact::PresenceStateYes));
            // He replied the presence request
            QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                     static_cast<uint>(Contact::PresenceStateYes));

            contact->removePresenceSubscription();
            QCOMPARE(mLoop->exec(), 0);
            QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                     static_cast<uint>(Contact::PresenceStateNo));
        } else {
            // I asked to see his presence - she might have already rejected it, though
            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk
                    || contact->subscriptionState() == Contact::PresenceStateNo);

            // If she didn't already reject it, wait until she does
            if (contact->subscriptionState() != Contact::PresenceStateNo) {
                QCOMPARE(mLoop->exec(), 0);
                QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                        static_cast<uint>(Contact::PresenceStateNo));
            }
        }

        ++i;

        // Disconnect the signals so the contacts doing something won't early-exit future mainloop
        // iterations (the simulation CM does things like - after a delay since we removed them, try
        // to re-add us - and such, which mess up the test if the simulated network event happens
        // before we've finished with the next contact)
        QVERIFY(contact->disconnect(this));

        // TODO: The roster API, frankly speaking, seems rather error/race prone, as evidenced by
        // this test. Should we perhaps change its semantics? Then again, this test also simulates
        // the remote user accepting/rejecting the request with a quite unpredictable timer delay,
        // while real-world applications don't do any such assumptions about the timing of the
        // remote user actions, so most of the problems won't be applicable there.
    }

    i = 0;
    Contact::PresenceState expectedPresenceState;
    Q_FOREACH (const ContactPtr &contact, pendingPublish) {
        QVERIFY(connect(contact.data(),
                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));

        if ((i % 2) == 0) {
            expectedPresenceState = Contact::PresenceStateYes;
            contact->authorizePresencePublication();
        } else {
            expectedPresenceState = Contact::PresenceStateNo;
            contact->removePresencePublication();
        }

        QCOMPARE(mLoop->exec(), 0);
        QCOMPARE(static_cast<uint>(contact->publishState()),
                 static_cast<uint>(expectedPresenceState));

        ++i;
    }

    // Test allKnownContactsChanged.
    // In this test, everytime a subscription is requested or rejected, allKnownContacts changes
    // Cache the current value
    mHowManyKnownContacts = mConn->contactManager()->allKnownContacts().size();
    // Watch for contacts changed
    QVERIFY(connect(mConn->contactManager(),
                    SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
                    SLOT(expectAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))));

    // Wait for the contacts to be built
    ids = QStringList() << QString(QLatin1String("kctest1@example.com"))
        << QString(QLatin1String("kctest2@example.com"));
    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);

    Q_FOREACH (const ContactPtr &contact, mContacts) {
        contact->requestPresenceSubscription(QLatin1String("add me now"));

        // allKnownContacts is supposed to change here.
        QCOMPARE(mLoop->exec(), 0);
    }
}

void TestConnRoster::cleanup()
{
    if (mConn) {
        // Disconnect and wait for the readiness change
        QVERIFY(connect(mConn->requestDisconnect(),
                        SIGNAL(finished(Tp::PendingOperation*)),
                        SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
        QCOMPARE(mLoop->exec(), 0);

        if (mConn->isValid()) {
            QVERIFY(connect(mConn.data(),
                            SIGNAL(invalidated(Tp::DBusProxy *,
                                               const QString &, const QString &)),
                            SLOT(expectConnInvalidated())));
            QCOMPARE(mLoop->exec(), 0);
        }
    }

    cleanupImpl();
}

void TestConnRoster::cleanupTestCase()
{
    if (mConnService != 0) {
        g_object_unref(mConnService);
        mConnService = 0;
    }

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestConnRoster)
#include "_gen/conn-roster.cpp.moc.hpp"
<commit_msg>Test details in ContactManager::allKnownContactsChanged()<commit_after>#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <QtTest/QtTest>

#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Debug>

#include <telepathy-glib/debug.h>

#include <tests/lib/glib/contactlist/conn.h>
#include <tests/lib/test.h>

using namespace Tp;

class TestConnRoster : public Test
{
    Q_OBJECT

public:
    TestConnRoster(QObject *parent = 0)
        : Test(parent), mConnService(0)
    { }

protected Q_SLOTS:
    void expectConnInvalidated();
    void expectPendingContactsFinished(Tp::PendingOperation *);
    void expectPresenceStateChanged(Tp::Contact::PresenceState);
    void expectAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed,
            const Tp::Channel::GroupMemberChangeDetails &details);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testRoster();

    void cleanup();
    void cleanupTestCase();

private:
    QString mConnName, mConnPath;
    ExampleContactListConnection *mConnService;
    ConnectionPtr mConn;
    QList<ContactPtr> mContacts;
    int mHowManyKnownContacts;
};

void TestConnRoster::expectConnInvalidated()
{
    mLoop->exit(0);
}

void TestConnRoster::expectPendingContactsFinished(PendingOperation *op)
{
    if (!op->isFinished()) {
        qWarning() << "unfinished";
        mLoop->exit(1);
        return;
    }

    if (op->isError()) {
        qWarning().nospace() << op->errorName()
            << ": " << op->errorMessage();
        mLoop->exit(2);
        return;
    }

    if (!op->isValid()) {
        qWarning() << "inconsistent results";
        mLoop->exit(3);
        return;
    }

    qDebug() << "finished";
    PendingContacts *pending = qobject_cast<PendingContacts *>(op);
    mContacts = pending->contacts();

    mLoop->exit(0);
}

void TestConnRoster::expectAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed,
        const Tp::Channel::GroupMemberChangeDetails &details)
{
    qDebug() << added.size() << " contacts added, " << removed.size() << " contacts removed";
    mHowManyKnownContacts += added.size();
    mHowManyKnownContacts -= removed.size();
    QVERIFY(details.hasMessage());
    QCOMPARE(details.message(), QLatin1String("add me now"));
    if (mConn->contactManager()->allKnownContacts().size() != mHowManyKnownContacts) {
        qWarning() << "Contacts number mismatch! Watched value: " << mHowManyKnownContacts
                   << "allKnownContacts(): " << mConn->contactManager()->allKnownContacts().size();
        mLoop->exit(1);
    } else {
        mLoop->exit(0);
    }
}

void TestConnRoster::expectPresenceStateChanged(Contact::PresenceState state)
{
    mLoop->exit(0);
}

void TestConnRoster::initTestCase()
{
    initTestCaseImpl();

    g_type_init();
    g_set_prgname("conn-roster");
    tp_debug_set_flags("all");
    dbus_g_bus_get(DBUS_BUS_STARTER, 0);

    gchar *name;
    gchar *connPath;
    GError *error = 0;

    mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new(
            EXAMPLE_TYPE_CONTACT_LIST_CONNECTION,
            "account", "me@example.com",
            "protocol", "contactlist",
            "simulation-delay", 1,
            NULL));
    QVERIFY(mConnService != 0);
    QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),
                "contacts", &name, &connPath, &error));
    QVERIFY(error == 0);

    QVERIFY(name != 0);
    QVERIFY(connPath != 0);

    mConnName = QLatin1String(name);
    mConnPath = QLatin1String(connPath);

    g_free(name);
    g_free(connPath);
}

void TestConnRoster::init()
{
    initImpl();

    mConn = Connection::create(mConnName, mConnPath);

    QVERIFY(connect(mConn->requestConnect(),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QCOMPARE(mConn->isReady(), true);
    QCOMPARE(mConn->status(), Connection::StatusConnected);
}

void TestConnRoster::testRoster()
{
    Features features = Features() << Connection::FeatureRoster;
    QVERIFY(connect(mConn->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QCOMPARE(mConn->isReady(features), true);

    QStringList toCheck = QStringList() <<
        QLatin1String("sjoerd@example.com") <<
        QLatin1String("travis@example.com") <<
        QLatin1String("wim@example.com") <<
        QLatin1String("olivier@example.com") <<
        QLatin1String("helen@example.com") <<
        QLatin1String("geraldine@example.com") <<
        QLatin1String("guillaume@example.com") <<
        QLatin1String("christian@example.com");
    QStringList ids;
    QList<ContactPtr> pendingSubscription;
    QList<ContactPtr> pendingPublish;
    Q_FOREACH (const ContactPtr &contact,
            mConn->contactManager()->allKnownContacts()) {
        qDebug() << " contact:" << contact->id() <<
            "- subscription:" << contact->subscriptionState() <<
            "- publish:" << contact->publishState();
        ids << contact->id();
        if (contact->subscriptionState() == Contact::PresenceStateAsk) {
            pendingSubscription.append(contact);
        } else if (contact->publishState() == Contact::PresenceStateAsk) {
            pendingPublish.append(contact);
        }
    }
    ids.sort();
    toCheck.sort();
    QCOMPARE(ids, toCheck);
    QCOMPARE(pendingSubscription.size(), 2);
    QCOMPARE(pendingPublish.size(), 2);

    // Wait for the contacts to be built
    ids = QStringList() << QString(QLatin1String("john@example.com"))
        << QString(QLatin1String("mary@example.com"));
    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);

    int i = 0;

    Q_FOREACH (const ContactPtr &contact, mContacts) {
        QVERIFY(connect(contact.data(),
                        SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));
        QVERIFY(connect(contact.data(),
                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));
        if ((i % 2) == 0) {
            contact->requestPresenceSubscription(QLatin1String("please add me"));
        } else {
            contact->requestPresenceSubscription(QLatin1String("add me now"));
        }

        QCOMPARE(mLoop->exec(), 0);

        if ((i % 2) == 0) {
            // I asked to see his presence - he might have already accepted it, though
            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk
                    || contact->subscriptionState() == Contact::PresenceStateYes);

            // if he accepted it already, one iteration won't be enough as the
            // first iteration will just flush the subscription -> Yes event
            while (contact->publishState() != Contact::PresenceStateAsk) {
                QCOMPARE(mLoop->exec(), 0);
            }

            contact->authorizePresencePublication();
            QCOMPARE(mLoop->exec(), 0);
            // I authorized him to see my presence
            QCOMPARE(static_cast<uint>(contact->publishState()),
                     static_cast<uint>(Contact::PresenceStateYes));
            // He replied the presence request
            QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                     static_cast<uint>(Contact::PresenceStateYes));

            contact->removePresenceSubscription();
            QCOMPARE(mLoop->exec(), 0);
            QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                     static_cast<uint>(Contact::PresenceStateNo));
        } else {
            // I asked to see his presence - she might have already rejected it, though
            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk
                    || contact->subscriptionState() == Contact::PresenceStateNo);

            // If she didn't already reject it, wait until she does
            if (contact->subscriptionState() != Contact::PresenceStateNo) {
                QCOMPARE(mLoop->exec(), 0);
                QCOMPARE(static_cast<uint>(contact->subscriptionState()),
                        static_cast<uint>(Contact::PresenceStateNo));
            }
        }

        ++i;

        // Disconnect the signals so the contacts doing something won't early-exit future mainloop
        // iterations (the simulation CM does things like - after a delay since we removed them, try
        // to re-add us - and such, which mess up the test if the simulated network event happens
        // before we've finished with the next contact)
        QVERIFY(contact->disconnect(this));

        // TODO: The roster API, frankly speaking, seems rather error/race prone, as evidenced by
        // this test. Should we perhaps change its semantics? Then again, this test also simulates
        // the remote user accepting/rejecting the request with a quite unpredictable timer delay,
        // while real-world applications don't do any such assumptions about the timing of the
        // remote user actions, so most of the problems won't be applicable there.
    }

    i = 0;
    Contact::PresenceState expectedPresenceState;
    Q_FOREACH (const ContactPtr &contact, pendingPublish) {
        QVERIFY(connect(contact.data(),
                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),
                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));

        if ((i % 2) == 0) {
            expectedPresenceState = Contact::PresenceStateYes;
            contact->authorizePresencePublication();
        } else {
            expectedPresenceState = Contact::PresenceStateNo;
            contact->removePresencePublication();
        }

        QCOMPARE(mLoop->exec(), 0);
        QCOMPARE(static_cast<uint>(contact->publishState()),
                 static_cast<uint>(expectedPresenceState));

        ++i;
    }

    // Test allKnownContactsChanged.
    // In this test, everytime a subscription is requested or rejected, allKnownContacts changes
    // Cache the current value
    mHowManyKnownContacts = mConn->contactManager()->allKnownContacts().size();
    // Watch for contacts changed
    QVERIFY(connect(mConn->contactManager(),
                    SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,
                            Tp::Channel::GroupMemberChangeDetails)),
                    SLOT(expectAllKnownContactsChanged(Tp::Contacts,Tp::Contacts,
                            Tp::Channel::GroupMemberChangeDetails))));

    // Wait for the contacts to be built
    ids = QStringList() << QString(QLatin1String("kctest1@example.com"))
        << QString(QLatin1String("kctest2@example.com"));
    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);

    Q_FOREACH (const ContactPtr &contact, mContacts) {
        contact->requestPresenceSubscription(QLatin1String("add me now"));

        // allKnownContacts is supposed to change here.
        QCOMPARE(mLoop->exec(), 0);
    }
}

void TestConnRoster::cleanup()
{
    if (mConn) {
        // Disconnect and wait for the readiness change
        QVERIFY(connect(mConn->requestDisconnect(),
                        SIGNAL(finished(Tp::PendingOperation*)),
                        SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
        QCOMPARE(mLoop->exec(), 0);

        if (mConn->isValid()) {
            QVERIFY(connect(mConn.data(),
                            SIGNAL(invalidated(Tp::DBusProxy *,
                                               const QString &, const QString &)),
                            SLOT(expectConnInvalidated())));
            QCOMPARE(mLoop->exec(), 0);
        }
    }

    cleanupImpl();
}

void TestConnRoster::cleanupTestCase()
{
    if (mConnService != 0) {
        g_object_unref(mConnService);
        mConnService = 0;
    }

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestConnRoster)
#include "_gen/conn-roster.cpp.moc.hpp"
<|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 "razormount.h"
#include "rzmountproviders.h"
#include <QtCore/QDebug>

RazorMountDevice::RazorMountDevice():
    QObject(0),
    mIsValid(false),
    mIsExternal(false),
    mIsMounted(false),
    mIsEjectable(false)
{
}

QString RazorMountDevice::sizeToString(qulonglong size)
{
    double n;
    n = size / (1024.0 * 1024 * 1024);
    if (n >= 1.0)
        return QObject::tr("%1 GB").arg(n, 0, 'f', 1);

    n = size / (1024.0 * 1024);
    if (n >= 1.0)
        return QObject::tr("%1 MB").arg(n, 0, 'f', 1);

    n = size / (1024.0);
    if (n >= 1.0)
        return QObject::tr("%1 KB").arg(n, 0, 'f', 1);

    return QObject::tr("%1 B").arg(size);
}

RazorMountManager::RazorMountManager(QObject *parent):
    QObject(parent),
    mProvider(0)
{
    mProvider = new UDisks2Provider(this);
    if (!mProvider->isValid())
    {
        delete mProvider;
        mProvider = 0;

        mProvider = new UDiskProvider(this);
        if (!mProvider->isValid())
        {
            delete mProvider;
            mProvider = 0;
        }
    }

    if (!mProvider)
        return;

    update();

    connect(mProvider, SIGNAL(deviceAdded(RazorMountDevice*)),
                 this, SIGNAL(deviceAdded(RazorMountDevice*)));

    connect(mProvider, SIGNAL(deviceChanged(RazorMountDevice*)),
                 this, SIGNAL(deviceChanged(RazorMountDevice*)));

    connect(mProvider, SIGNAL(deviceRemoved(RazorMountDevice*)),
                 this, SIGNAL(deviceRemoved(RazorMountDevice*)));
}

RazorMountManager::~RazorMountManager()
{
    delete mProvider;
}

void RazorMountManager::update()
{
    if (mProvider)
        mProvider->update();
    else
        qDebug() << "RazorMountDeviceList RazorMountManager::update() no valid provider in use";

}

const RazorMountDeviceList RazorMountManager::devices() const
{
    if (mProvider)
    {
        qDebug() << "RazorMountManager::devices" << mProvider->devices();
        return mProvider->devices();
    }
    else
    {
        qDebug() << "RazorMountDeviceList RazorMountManager::devices() no valid provider in use";
        return RazorMountDeviceList();
    }
}

QDebug operator<<(QDebug dbg, const RazorMountDevice &device)
{
    dbg << device.devFile();

    switch (device.mediaType())
    {
    case RazorMountDevice::MediaTypeUnknown:    dbg<<"Type: MediaTypeUnknown";  break;
    case RazorMountDevice::MediaTypeDrive:      dbg<<"Type: MediaTypeDrive";    break;
    case RazorMountDevice::MediaTypePartition:  dbg<<"Type: MediaTypePartition";break;
    case RazorMountDevice::MediaTypeFdd:        dbg<<"Type: MediaTypeFdd";      break;
    case RazorMountDevice::MediaTypeOptical:    dbg<<"Type: MediaTypeOptical";  break;
    default:                                    dbg<<"Type: "<<device.mediaType();break;
    }
    dbg << "Label: " << device.label();
    dbg << "Mount path:" << device.mountPath();
    return dbg.space();
}

QDebug operator<<(QDebug dbg, const RazorMountDevice *device)
{
    return operator<<(dbg, *device);
}
<commit_msg>"KB" changed to "kB"<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 "razormount.h"
#include "rzmountproviders.h"
#include <QtCore/QDebug>

RazorMountDevice::RazorMountDevice():
    QObject(0),
    mIsValid(false),
    mIsExternal(false),
    mIsMounted(false),
    mIsEjectable(false)
{
}

QString RazorMountDevice::sizeToString(qulonglong size)
{
    double n;
    n = size / (1024.0 * 1024 * 1024);
    if (n >= 1.0)
        return QObject::tr("%1 GB").arg(n, 0, 'f', 1);

    n = size / (1024.0 * 1024);
    if (n >= 1.0)
        return QObject::tr("%1 MB").arg(n, 0, 'f', 1);

    n = size / (1024.0);
    if (n >= 1.0)
        return QObject::tr("%1 kB").arg(n, 0, 'f', 1);

    return QObject::tr("%1 B").arg(size);
}

RazorMountManager::RazorMountManager(QObject *parent):
    QObject(parent),
    mProvider(0)
{
    mProvider = new UDisks2Provider(this);
    if (!mProvider->isValid())
    {
        delete mProvider;
        mProvider = 0;

        mProvider = new UDiskProvider(this);
        if (!mProvider->isValid())
        {
            delete mProvider;
            mProvider = 0;
        }
    }

    if (!mProvider)
        return;

    update();

    connect(mProvider, SIGNAL(deviceAdded(RazorMountDevice*)),
                 this, SIGNAL(deviceAdded(RazorMountDevice*)));

    connect(mProvider, SIGNAL(deviceChanged(RazorMountDevice*)),
                 this, SIGNAL(deviceChanged(RazorMountDevice*)));

    connect(mProvider, SIGNAL(deviceRemoved(RazorMountDevice*)),
                 this, SIGNAL(deviceRemoved(RazorMountDevice*)));
}

RazorMountManager::~RazorMountManager()
{
    delete mProvider;
}

void RazorMountManager::update()
{
    if (mProvider)
        mProvider->update();
    else
        qDebug() << "RazorMountDeviceList RazorMountManager::update() no valid provider in use";

}

const RazorMountDeviceList RazorMountManager::devices() const
{
    if (mProvider)
    {
        qDebug() << "RazorMountManager::devices" << mProvider->devices();
        return mProvider->devices();
    }
    else
    {
        qDebug() << "RazorMountDeviceList RazorMountManager::devices() no valid provider in use";
        return RazorMountDeviceList();
    }
}

QDebug operator<<(QDebug dbg, const RazorMountDevice &device)
{
    dbg << device.devFile();

    switch (device.mediaType())
    {
    case RazorMountDevice::MediaTypeUnknown:    dbg<<"Type: MediaTypeUnknown";  break;
    case RazorMountDevice::MediaTypeDrive:      dbg<<"Type: MediaTypeDrive";    break;
    case RazorMountDevice::MediaTypePartition:  dbg<<"Type: MediaTypePartition";break;
    case RazorMountDevice::MediaTypeFdd:        dbg<<"Type: MediaTypeFdd";      break;
    case RazorMountDevice::MediaTypeOptical:    dbg<<"Type: MediaTypeOptical";  break;
    default:                                    dbg<<"Type: "<<device.mediaType();break;
    }
    dbg << "Label: " << device.label();
    dbg << "Mount path:" << device.mountPath();
    return dbg.space();
}

QDebug operator<<(QDebug dbg, const RazorMountDevice *device)
{
    return operator<<(dbg, *device);
}
<|endoftext|>


<commit_before>#include "twister.h"

const unsigned CYCLE = 0x100;

const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
	0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
  };
int triad_units[][0x03] = {
	0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
                               0xcf, 0xad, 0xdf, 0xff, 0xce,
                               0x32, 0x40, 0xd3, 0x27, 0x82,
                               0xda, 0xee, 0xff, 0xfc, 0xbf,
                               0x1c, 0x90, 0x13, 0x4a, 0xa5,
                               0xe0, 0x21, 0x9f, 0xe1, 0xc6,
                               0xe4, 0x38, 0x1f, 0x60, 0x24,
                               0x0c, 0x35, 0x51, 0x32, 0xcf,
                               0x12, 0x9a, 0x30, 0x44, 0x72,
                               0x04, 0x1c, 0x52, 0xca, 0xdf,
                               0x12, 0x0b, 0x30, 0xa0, 0x1e,
                               0x03, 0x14, 0x09, 0x73, 0x23,
                               0xf2, 0xca, 0xa2, 0x51, 0xc6,
                               0xcb, 0xbd, 0xba, 0xac, 0xdf,
			       0xdf, 0xde, 0xcd, 0xfd, 0xca };

int ENTRY_LINK__ = 0x05;

unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
  return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
	return (*s)(pos)^a;
}

void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^base(d, g, d);
    }
    data[i] = d;
  }
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^(*g)(d);
    }
    data[i] = d;
  }
}

void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d);
    }
    data[i] = d;
  }
}

vector<double> f_dist(vector<unsigned char>& in)
{
  vector<double> fdist;
  fdist.resize(256);
  for(unsigned i = 0; i<in.size(); i++)
  {
    fdist[in[i]]++;
  }

  for(unsigned i=0; i<fdist.size(); i++)
  {
    fdist[i] = (fdist[i] / in.size()) * 100;
  }

  return fdist;
}

double s_entropy(vector<double> v)
{
  double entropy = 0;
  double p;

  for(unsigned i = 0; i < v.size(); i++)
  {
    p = v[i] / 100;
    if (p == 0) continue;
    entropy += p * std::log(p) / std::log(2);
  }
  return -entropy;
}
void rms(const string& s, string& r)
{
  for(unsigned int i=0; i<s.size(); i++)
  {
    if(::isspace(s[i])) continue;
    r+= s[i];
  }
}

double sw(double weight, int i, int j, int (*inv)(int, int))
{
  return weight*(*inv)(i, j);
}
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))
{
  if(s == 1)
  {
    (*p)(n);
    return;
  }
  for(int i=0; i< s; i++)
  {
    hPerm(s-1, n, p, inv);
    if(s%2 == 1)
      (*inv)(0, s-1);
    else
      (*inv)(i, s-1);
  }
}

double ic(const string& t)
{
  string text; rms(t, text);
  vector<double> freq(256,0);
  for(unsigned int i=0; i<text.size(); i++)
  {
    if(text[i] == ' ') continue;
    freq[text[i]] ++;
  }
  double sum=0;
  for(unsigned int i=0; i<freq.size(); i++)
  {
    if(freq[i] != 0)
    {
      double c = freq[i];
      if(c != 0)
        sum += c * (c - 1);
    }
  }
  double ic = 26 * sum / (text.size() * (text.size() - 1));
  return ic;
}

void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
  //test seq
  (*p)(transition_seq[ENTRY_LINK__], m);
}
<commit_msg>util test, seq<commit_after>#include "twister.h"

const unsigned CYCLE = 0x100;

const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
	0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
  };
int triad_units[][0x03] = {
	0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
                               0xcf, 0xad, 0xdf, 0xff, 0xce,
                               0x32, 0x40, 0xd3, 0x27, 0x82,
                               0xda, 0xee, 0xff, 0xfc, 0xbf,
                               0x1c, 0x90, 0x13, 0x4a, 0xa5,
                               0xe0, 0x21, 0x9f, 0xe1, 0xc6,
                               0xe4, 0x38, 0x1f, 0x60, 0x24,
                               0x0c, 0x35, 0x51, 0x32, 0xcf,
                               0x12, 0x9a, 0x30, 0x44, 0x72,
                               0x04, 0x1c, 0x52, 0xca, 0xdf,
                               0x12, 0x0b, 0x30, 0xa0, 0x1e,
                               0x03, 0x14, 0x09, 0x73, 0x23,
                               0xf2, 0xca, 0xa2, 0x51, 0xc6,
                               0xcb, 0xbd, 0xba, 0xac, 0xdf,
			       0xdf, 0xde, 0xcd, 0xfd, 0xca };

int ENTRY_LINK__ = 0x05;
int ENTRY_LINK__TEST = 0x09;

unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
  return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
	return (*s)(pos)^a;
}

void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^base(d, g, d);
    }
    data[i] = d;
  }
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^(*g)(d);
    }
    data[i] = d;
  }
}

void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d);
    }
    data[i] = d;
  }
}

vector<double> f_dist(vector<unsigned char>& in)
{
  vector<double> fdist;
  fdist.resize(256);
  for(unsigned i = 0; i<in.size(); i++)
  {
    fdist[in[i]]++;
  }

  for(unsigned i=0; i<fdist.size(); i++)
  {
    fdist[i] = (fdist[i] / in.size()) * 100;
  }

  return fdist;
}

double s_entropy(vector<double> v)
{
  double entropy = 0;
  double p;

  for(unsigned i = 0; i < v.size(); i++)
  {
    p = v[i] / 100;
    if (p == 0) continue;
    entropy += p * std::log(p) / std::log(2);
  }
  return -entropy;
}
void rms(const string& s, string& r)
{
  for(unsigned int i=0; i<s.size(); i++)
  {
    if(::isspace(s[i])) continue;
    r+= s[i];
  }
}

double sw(double weight, int i, int j, int (*inv)(int, int))
{
  return weight*(*inv)(i, j);
}
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))
{
  if(s == 1)
  {
    (*p)(n);
    return;
  }
  for(int i=0; i< s; i++)
  {
    hPerm(s-1, n, p, inv);
    if(s%2 == 1)
      (*inv)(0, s-1);
    else
      (*inv)(i, s-1);
  }
}

double ic(const string& t)
{
  string text; rms(t, text);
  vector<double> freq(256,0);
  for(unsigned int i=0; i<text.size(); i++)
  {
    if(text[i] == ' ') continue;
    freq[text[i]] ++;
  }
  double sum=0;
  for(unsigned int i=0; i<freq.size(); i++)
  {
    if(freq[i] != 0)
    {
      double c = freq[i];
      if(c != 0)
        sum += c * (c - 1);
    }
  }
  double ic = 26 * sum / (text.size() * (text.size() - 1));
  return ic;
}

void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
  //test seq
  (*p)(transition_seq[ENTRY_LINK__], m);
  (*p)(transition_seq[ENTRY_LINK__TEST], m);
}
<|endoftext|>