<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 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/>.
 */
#include "XalanTransformerDefinitions.hpp"

#include <util/PlatformUtils.hpp>

#include <cassert>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <strstream.h>
#else
#include <strstream>
#endif

#if !defined(XALAN_NO_NAMESPACES)
using std::istrstream;
#endif

#include "XalanCAPI.h"
#include "XalanTransformer.hpp"

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanInitialize()
{
	// Call the static initializer for Xerces.
	XMLPlatformUtils::Initialize();

	// Initialize Xalan.
	XalanTransformer::initialize();
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanTerminate()
{
	// Terminate Xalan.
	XalanTransformer::terminate();

	// Call the static terminator for Xerces.
	XMLPlatformUtils::Terminate();
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(XalanHandle)
CreateXalanTransformer()
{
	// Create a XalanTransformer object.
	return new XalanTransformer();
}

inline XalanTransformer*
getTransformer(XalanHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (XalanTransformer*)theHandle;
#else
	return static_cast<XalanTransformer*>(theHandle);
#endif
}

inline const XalanCompiledStylesheet*
getStylesheet(XalanCSSHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (const XalanCompiledStylesheet*)theHandle;
#else
	return reinterpret_cast<const XalanCompiledStylesheet*>(theHandle);
#endif
}

inline const XalanParsedSource*
getParsedSource(XalanPSHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (const XalanParsedSource*)theHandle;
#else
	return reinterpret_cast<const XalanParsedSource*>(theHandle);
#endif
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
DeleteXalanTransformer(XalanHandle theXalanHandle)
{
	// Delete a XalanTransformer object.
	delete getTransformer(theXalanHandle);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToFile(
			const char*		theXMLFileName,
			const char*		theXSLFileName,
			const char*		theOutFileName,
			XalanHandle		theXalanHandle)
{
	if(theXSLFileName == 0)
	{
		return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theOutFileName);
	}
	else
	{
		return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutFileName);
	}
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToFilePrebuilt(
			XalanPSHandle	theParsedSource,
			XalanCSSHandle	theCSSHandle,
			const char*		theOutFileName,
			XalanHandle		theXalanHandle)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
				*getParsedSource(theParsedSource),
				getStylesheet(theCSSHandle),
				theOutFileName);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToData(
			const char*		theXMLFileName,
			const char*		theXSLFileName,
			char**			theOutput,
			XalanHandle		theXalanHandle)
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::ostrstream;
#endif

	int	status = 0;

	ostrstream	theOutputStream;

	if(theXSLFileName == 0)
	{
		status = getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theOutputStream);
	}
	else
	{
		status = getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutputStream);
	}

	if (status == 0)
	{
		// Null-terminate the data.
		theOutputStream << '\0';

		*theOutput = theOutputStream.str();
	}

	return status;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToDataPrebuilt(
			XalanPSHandle	theParsedSource,
			XalanCSSHandle	theCSSHandle,
			char**			theOutput,
			XalanHandle		theXalanHandle)
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::ostrstream;
#endif

	ostrstream	theOutputStream;

	// Do the transformation...
	const int	status =
		getTransformer(theXalanHandle)->transform(
			*getParsedSource(theParsedSource),
			getStylesheet(theCSSHandle),
			theOutputStream);

	if (status == 0)
	{
		// Null-terminate the data.
		theOutputStream << '\0';

		*theOutput = theOutputStream.str();
	}

	return status;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanFreeData(char*	theStream)
{
	// Delete the data.
	delete[] theStream;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToHandler(
			const char*				theXMLFileName,
			const char*				theXSLFileName,
			XalanHandle				theXalanHandle,
			void*					theOutputHandle,
			XalanOutputHandlerType	theOutputHandler,
			XalanFlushHandlerType	theFlushHandler)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutputHandle,
			theOutputHandler,
			theFlushHandler);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToHandlerPrebuilt(
			XalanPSHandle			theParsedSource,
			XalanCSSHandle			theCSSHandle,
			XalanHandle				theXalanHandle,
			void*					theOutputHandle,
			XalanOutputHandlerType	theOutputHandler,
			XalanFlushHandlerType	theFlushHandler)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
			*getParsedSource(theParsedSource),
			getStylesheet(theCSSHandle),
			theOutputHandle,
			theOutputHandler,
			theFlushHandler);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanCompileStylesheet(
			const char*			theXSLFileName,
			XalanHandle			theXalanHandle,
			XalanCSSHandle*		theCSSHandle)
{
	const XalanCompiledStylesheet*	theCompiledStylesheet = 0;

	const int	theResult =
		getTransformer(theXalanHandle)->compileStylesheet(
			theXSLFileName,
			theCompiledStylesheet);

	if (theResult == 0)
	{
		*theCSSHandle = theCompiledStylesheet;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanCompileStylesheetFromStream(
			const char*			theXSLStream,
			unsigned long		theXSLStreamLength,
			XalanHandle			theXalanHandle,
			XalanCSSHandle*		theCSSHandle)
{
	const XalanCompiledStylesheet*	theCompiledStylesheet = 0;

	istrstream	theInputStream(theXSLStream, theXSLStreamLength);

	const int	theResult =
		getTransformer(theXalanHandle)->compileStylesheet(
			&theInputStream,
			theCompiledStylesheet);

	if (theResult == 0)
	{
		*theCSSHandle = theCompiledStylesheet;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanDestroyCompiledStylesheet(
			XalanCSSHandle	theCSSHandle,
			XalanHandle		theXalanHandle)
{
	return getTransformer(theXalanHandle)->destroyStylesheet(getStylesheet(theCSSHandle));
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanParseSource(
			const char*		theXMLFileName,
			XalanHandle		theXalanHandle,
			XalanPSHandle*	thePSHandle)
{
	const XalanParsedSource*	theParsedSource = 0;

	const int	theResult =
		getTransformer(theXalanHandle)->parseSource(
			theXMLFileName,
			theParsedSource);

	if (theResult == 0)
	{
		*thePSHandle = theParsedSource;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanParseSourceFromStream(
			const char*		theXMLStream,
			unsigned long	theXMLStreamLength,
			XalanHandle		theXalanHandle,
			XalanPSHandle*	thePSHandle)
{
	const XalanParsedSource*	theParsedSource = 0;

	istrstream	theInputStream(theXMLStream, theXMLStreamLength);

	const int	theResult =
		getTransformer(theXalanHandle)->parseSource(
			&theInputStream,
			theParsedSource);

	if (theResult == 0)
	{
		*thePSHandle = theParsedSource;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanSetStylesheetParam(
			const char*		key,
			const char*		expression,
			XalanHandle		theXalanHandle)
{
	getTransformer(theXalanHandle)->setStylesheetParam(
		XalanDOMString(key),
		XalanDOMString(expression));
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(XalanCCharPtr)
XalanGetLastError(XalanHandle theXalanHandle)
{
	// Get the last error.
	return getTransformer(theXalanHandle)->getLastError();
}
<commit_msg>Added missing implementation.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 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/>.
 */
#include "XalanTransformerDefinitions.hpp"

#include <util/PlatformUtils.hpp>

#include <cassert>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <strstream.h>
#else
#include <strstream>
#endif

#if !defined(XALAN_NO_NAMESPACES)
using std::istrstream;
#endif

#include "XalanCAPI.h"
#include "XalanTransformer.hpp"

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanInitialize()
{
	// Call the static initializer for Xerces.
	XMLPlatformUtils::Initialize();

	// Initialize Xalan.
	XalanTransformer::initialize();
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanTerminate()
{
	// Terminate Xalan.
	XalanTransformer::terminate();

	// Call the static terminator for Xerces.
	XMLPlatformUtils::Terminate();
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(XalanHandle)
CreateXalanTransformer()
{
	// Create a XalanTransformer object.
	return new XalanTransformer();
}

inline XalanTransformer*
getTransformer(XalanHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (XalanTransformer*)theHandle;
#else
	return static_cast<XalanTransformer*>(theHandle);
#endif
}

inline const XalanCompiledStylesheet*
getStylesheet(XalanCSSHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (const XalanCompiledStylesheet*)theHandle;
#else
	return reinterpret_cast<const XalanCompiledStylesheet*>(theHandle);
#endif
}

inline const XalanParsedSource*
getParsedSource(XalanPSHandle	theHandle)
{
	assert(theHandle != 0);

#if defined(XALAN_OLD_STYLE_CASTS)
	return (const XalanParsedSource*)theHandle;
#else
	return reinterpret_cast<const XalanParsedSource*>(theHandle);
#endif
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
DeleteXalanTransformer(XalanHandle theXalanHandle)
{
	// Delete a XalanTransformer object.
	delete getTransformer(theXalanHandle);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToFile(
			const char*		theXMLFileName,
			const char*		theXSLFileName,
			const char*		theOutFileName,
			XalanHandle		theXalanHandle)
{
	if(theXSLFileName == 0)
	{
		return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theOutFileName);
	}
	else
	{
		return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutFileName);
	}
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToFilePrebuilt(
			XalanPSHandle	theParsedSource,
			XalanCSSHandle	theCSSHandle,
			const char*		theOutFileName,
			XalanHandle		theXalanHandle)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
				*getParsedSource(theParsedSource),
				getStylesheet(theCSSHandle),
				theOutFileName);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToData(
			const char*		theXMLFileName,
			const char*		theXSLFileName,
			char**			theOutput,
			XalanHandle		theXalanHandle)
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::ostrstream;
#endif

	int	status = 0;

	ostrstream	theOutputStream;

	if(theXSLFileName == 0)
	{
		status = getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theOutputStream);
	}
	else
	{
		status = getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutputStream);
	}

	if (status == 0)
	{
		// Null-terminate the data.
		theOutputStream << '\0';

		*theOutput = theOutputStream.str();
	}

	return status;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToDataPrebuilt(
			XalanPSHandle	theParsedSource,
			XalanCSSHandle	theCSSHandle,
			char**			theOutput,
			XalanHandle		theXalanHandle)
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::ostrstream;
#endif

	ostrstream	theOutputStream;

	// Do the transformation...
	const int	status =
		getTransformer(theXalanHandle)->transform(
			*getParsedSource(theParsedSource),
			getStylesheet(theCSSHandle),
			theOutputStream);

	if (status == 0)
	{
		// Null-terminate the data.
		theOutputStream << '\0';

		*theOutput = theOutputStream.str();
	}

	return status;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanFreeData(char*	theStream)
{
	// Delete the data.
	delete[] theStream;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToHandler(
			const char*				theXMLFileName,
			const char*				theXSLFileName,
			XalanHandle				theXalanHandle,
			void*					theOutputHandle,
			XalanOutputHandlerType	theOutputHandler,
			XalanFlushHandlerType	theFlushHandler)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
			theXMLFileName,
			theXSLFileName,
			theOutputHandle,
			theOutputHandler,
			theFlushHandler);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanTransformToHandlerPrebuilt(
			XalanPSHandle			theParsedSource,
			XalanCSSHandle			theCSSHandle,
			XalanHandle				theXalanHandle,
			void*					theOutputHandle,
			XalanOutputHandlerType	theOutputHandler,
			XalanFlushHandlerType	theFlushHandler)
{
	// Do the transformation...
	return getTransformer(theXalanHandle)->transform(
			*getParsedSource(theParsedSource),
			getStylesheet(theCSSHandle),
			theOutputHandle,
			theOutputHandler,
			theFlushHandler);
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanCompileStylesheet(
			const char*			theXSLFileName,
			XalanHandle			theXalanHandle,
			XalanCSSHandle*		theCSSHandle)
{
	const XalanCompiledStylesheet*	theCompiledStylesheet = 0;

	const int	theResult =
		getTransformer(theXalanHandle)->compileStylesheet(
			theXSLFileName,
			theCompiledStylesheet);

	if (theResult == 0)
	{
		*theCSSHandle = theCompiledStylesheet;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanCompileStylesheetFromStream(
			const char*			theXSLStream,
			unsigned long		theXSLStreamLength,
			XalanHandle			theXalanHandle,
			XalanCSSHandle*		theCSSHandle)
{
	const XalanCompiledStylesheet*	theCompiledStylesheet = 0;

	istrstream	theInputStream(theXSLStream, theXSLStreamLength);

	const int	theResult =
		getTransformer(theXalanHandle)->compileStylesheet(
			&theInputStream,
			theCompiledStylesheet);

	if (theResult == 0)
	{
		*theCSSHandle = theCompiledStylesheet;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanDestroyCompiledStylesheet(
			XalanCSSHandle	theCSSHandle,
			XalanHandle		theXalanHandle)
{
	return getTransformer(theXalanHandle)->destroyStylesheet(getStylesheet(theCSSHandle));
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanParseSource(
			const char*		theXMLFileName,
			XalanHandle		theXalanHandle,
			XalanPSHandle*	thePSHandle)
{
	const XalanParsedSource*	theParsedSource = 0;

	const int	theResult =
		getTransformer(theXalanHandle)->parseSource(
			theXMLFileName,
			theParsedSource);

	if (theResult == 0)
	{
		*thePSHandle = theParsedSource;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanParseSourceFromStream(
			const char*		theXMLStream,
			unsigned long	theXMLStreamLength,
			XalanHandle		theXalanHandle,
			XalanPSHandle*	thePSHandle)
{
	const XalanParsedSource*	theParsedSource = 0;

	istrstream	theInputStream(theXMLStream, theXMLStreamLength);

	const int	theResult =
		getTransformer(theXalanHandle)->parseSource(
			&theInputStream,
			theParsedSource);

	if (theResult == 0)
	{
		*thePSHandle = theParsedSource;
	}

	return theResult;
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(int)
XalanDestroyParsedSource(
			XalanPSHandle	thePSHandle,
			XalanHandle		theXalanHandle)
{
	return getTransformer(theXalanHandle)->destroyParsedSource(getParsedSource(thePSHandle));
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(void)
XalanSetStylesheetParam(
			const char*		key,
			const char*		expression,
			XalanHandle		theXalanHandle)
{
	getTransformer(theXalanHandle)->setStylesheetParam(
		XalanDOMString(key),
		XalanDOMString(expression));
}

XALAN_TRANSFORMER_EXPORT_FUNCTION(XalanCCharPtr)
XalanGetLastError(XalanHandle theXalanHandle)
{
	// Get the last error.
	return getTransformer(theXalanHandle)->getLastError();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include "linkedBinaryTree.h"

using namespace std;

void linkedBinaryTree :: consturctTree(int *in, int *post)
{

    // construct bst from inorder and postorder
    // http://www.programcreek.com/2013/01/construct-binary-tree-from-inorder-and-postorder-traversal/

}

int linkedBinaryTree :: maxHeightDifference()
{
//write your code here

    return 0;

}

void linkedBinaryTree :: preOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		visit(t);
		preOrder(t->leftChild);
		preOrder(t->rightChild);
	}
}

void linkedBinaryTree :: inOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		inOrder(t->leftChild);
		visit(t);
		inOrder(t->rightChild);
	}
}

void linkedBinaryTree :: postOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		postOrder(t->leftChild);
		postOrder(t->rightChild);
		visit(t);
	}
}

void linkedBinaryTree :: visit(binaryTreeNode *t)
{

	cout << t->element << " ";

}

int linkedBinaryTree :: height(binaryTreeNode *t)
{

	if(t == NULL)
		return 0;
	int hl = height(t->leftChild);
	int hr = height(t->rightChild);
	if (hl > hr)
		return ++hl;
	else
		return ++hr;

}

<commit_msg>part of construct<commit_after>#include <iostream>
#include <sstream>
#include "linkedBinaryTree.h"

using namespace std;

void linkedBinaryTree :: consturctTree(int *in, int *post)
{

	// from email:
	// In Assignment 4, in the construct tree method as the array length is not passed, you can assume it to be hardcoded as 17.

	// get root
	int newRoot = post[16];
	root = new binaryTreeNode(newRoot);

	// find position of root in inorder, derive left and right sub trees
	int rootPosition = 0;

	for (int i = 0; i < 17; i++) {
		if (in[i] == newRoot) {
			rootPosition = i + 1;
		}
	}

	// insert left side
	for (int j = 0; j < rootPosition; j++) {

	}

	// insert right side
	for (int k = 0; k < 17 - rootPosition; k++) {

	}
}

int linkedBinaryTree :: maxHeightDifference()
{
//write your code here

    return 0;

}

void linkedBinaryTree :: preOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		visit(t);
		preOrder(t->leftChild);
		preOrder(t->rightChild);
	}
}

void linkedBinaryTree :: inOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		inOrder(t->leftChild);
		visit(t);
		inOrder(t->rightChild);
	}
}

void linkedBinaryTree :: postOrder(binaryTreeNode *t)
{
	if(t != NULL)
	{
		postOrder(t->leftChild);
		postOrder(t->rightChild);
		visit(t);
	}
}

void linkedBinaryTree :: visit(binaryTreeNode *t)
{

	cout << t->element << " ";

}

int linkedBinaryTree :: height(binaryTreeNode *t)
{

	if(t == NULL)
		return 0;
	int hl = height(t->leftChild);
	int hr = height(t->rightChild);
	if (hl > hr)
		return ++hl;
	else
		return ++hr;

}

<|endoftext|>


<commit_before>/*  Copyright (C) 2009  Adenilson Cavalcanti <savagobr@yahoo.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; by version 2 of the License or (at your
 *  choice) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "gcalresource.h"
#include "settings.h"
#include "settingsadaptor.h"

#include <QtDBus/QDBusConnection>
#include <kabc/addressee.h>
#include <kabc/phonenumber.h>
#include <kabc/key.h>
#include <kabc/errorhandler.h>
#include <kcal/event.h>
#include <kdatetime.h>
#include <qstring.h>
#include <KWindowSystem>
#include <akonadi/changerecorder.h>
#include <akonadi/itemfetchscope.h>
#include <KUrl>

extern "C" {
#include <gcalendar.h>
#include <gcal_status.h>
}

using namespace Akonadi;

GCalResource::GCalResource( const QString &id )
	: ResourceBase(id)
{
	new SettingsAdaptor( Settings::self() );
	QDBusConnection::sessionBus().registerObject(
		QLatin1String( "/Settings" ), Settings::self(),
		QDBusConnection::ExportAdaptors );

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

    if (!(gcal = gcal_new(GCALENDAR)))
		exit(1);
    gcal_set_store_xml(gcal, 1);
    all_events.length = 0;
    all_events.entries = NULL;
}

GCalResource::~GCalResource()
{
    gcal_cleanup_events(&all_events);
    pending.clear();
    deleted.clear();
}

void GCalResource::retrieveTimestamp(QString &timestamp)
{
	timestamp = Settings::self()->timestamp();
}

void GCalResource::saveTimestamp(QString &timestamp)
{
    Settings::self()->setTimestamp(timestamp);
    Settings::self()->writeConfig();
}

void GCalResource::retrieveCollections()
{
    if(!authenticated) {
		kError() << "No authentication for Google Calendar available";
                const QString message = i18nc("@info: status",
					      "Not yet authenticated for "
					      "use of Google Calendar");

        emit error(message);

        emit status(Broken, message);
        return;
    }

    Collection c;
    c.setParent(Collection::root());
    c.setRemoteId("google-calendar");
    c.setName(name());

    QStringList mimeTypes;
    mimeTypes << "text/calendar";
    c.setContentMimeTypes(mimeTypes);

    Collection::List list;
    list << c;
    collectionsRetrieved(list);
}

void GCalResource::retrieveItems( const Akonadi::Collection &collection )
{
	Q_UNUSED(collection);
	Item::List items;
	int result;
	gcal_event_t event;
	QString timestamp;
	QByteArray t_byte;

	kError() << "\n............. retrieveItems ...........\n";
	if (!authenticated) {
		kError() << "No authentication for Google calendar available";
		const QString message = i18nc("@info:status",
					      "Not yet authenticated for"
					      " use of Google calendar");
		emit error(message);
		emit status(Broken, message);
		return;
	}

	/* Query by updated */
	retrieveTimestamp(timestamp);
	t_byte = timestamp.toLocal8Bit();
	if (t_byte.length() > TIMESTAMP_SIZE) {
		//TODO: implement getUpdated
		//result = getUpdated(t_byte.data());
		return;
	}
	kError() << "First retrieve";

	if ((result = gcal_get_events(gcal, &all_events)))
		exit(1);

	/* GCalendar returns last updated entry as first element */
	event = gcal_event_element(&all_events, 0);
	if (!event) {
		kError() << "Failed to retrieve last updated event.";
		const QString message = i18nc("@info:status",
					      "Failed getting last updated"
					      " event");
		emit error(message);
		emit status(Broken, message);
		return;

	}

	timestamp = gcal_event_get_updated(event);
	saveTimestamp(timestamp);

	/* Each google entry has a unique ID and edit_url */
	for (size_t i = 0; i < all_events.length; ++i) {
		Item item(QLatin1String("text/calendar"));
		KCal::Event kevent;
		QString temp;
		event = gcal_event_element(&all_events, i);

		temp = gcal_event_get_title(event);
		kevent.setSummary(temp);

		temp = gcal_event_get_where(event);
		kevent.setLocation(temp);

		KCal::Incidence::Status status;
		if (gcal_event_is_deleted(event))
			status = KCal::Incidence::StatusCanceled;
		else
			status = KCal::Incidence::StatusConfirmed;
		kevent.setStatus(status);

		temp = gcal_event_get_content(event);
		kevent.setDescription(temp);

		KDateTime start, end;
		temp = gcal_event_get_start(event);
		start.fromString(temp);
		temp = gcal_event_get_end(event);
		end.fromString(temp);
		kevent.setDtStart(start);
		kevent.setDtEnd(end);

		items << item;
	}

	itemsRetrieved(items);
}

bool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
	Q_UNUSED(parts);
	Q_UNUSED(item);
	return true;
}

void GCalResource::aboutToQuit()
{
	// TODO: any cleanup you need to do while there is still an active
	// event loop. The resource will terminate after this method returns
}

void GCalResource::doSetOnline(bool online)
{
	Q_UNUSED(online);
}

int GCalResource::getUpdated(char *timestamp)
{
	Q_UNUSED(timestamp);

	return -1;
}

void GCalResource::configure( WId windowId )
{
	int result = 0;
	if (windowId && dlgConf)
		KWindowSystem::setMainWindow(dlgConf, windowId);

	dlgConf->exec();
	if (!(result = authenticate(dlgConf->eAccount->text(),
				    dlgConf->ePass->text()))) {
		result = saveToWallet(dlgConf->eAccount->text(),
				      dlgConf->ePass->text(),
				      windowId);

		synchronize();
	}

	if (result) {
		kError() << "Failed configuring resource.";
		const QString message = i18nc("@info:status",
					      "Invalid password.");
		emit error(message);
		emit status(Broken, message);
		return;
	}
}

void GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
	Q_UNUSED(collection);

    gcal_event_t event;
    KCal::Event kevent;
    QByteArray t_byte;
    QString temp;

    if (!authenticated) {
        kError() << "No authentication for Google calendar available";
        const QString message = i18nc("@info:status",
                          "Not yet authenticated for"
                          " use of Google calendar");
        emit error(message);
        emit status(Broken, message);
        return;
    }

    if(item.hasPayload<KCal::Event>())
        kevent = item.payload<KCal::Event>();

    if (!(event = gcal_event_new(NULL))) {
        kError() << "Memory allocation error!";
        const QString message = i18nc("@info:status",
                      "Failed to create gcal_event");
        emit error(message);
        emit status(Broken, message);
        return;
    }

    temp = kevent.summary();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_title(event, t_byte);
    }

    temp = kevent.description();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_content(event, t_byte);
    }
    //TODO: event start, event end, status, url, id and etags

    temp = kevent.location();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_where(event, t_byte);
    }
}

void GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
	Q_UNUSED(parts);
	Q_UNUSED(item);
}

void GCalResource::itemRemoved( const Akonadi::Item &item )
{
	Q_UNUSED(item);
}

AKONADI_RESOURCE_MAIN( GCalResource )

#include "gcalresource.moc"
<commit_msg>Formating and commenting soon-to-be-used-code.<commit_after>/*  Copyright (C) 2009  Adenilson Cavalcanti <savagobr@yahoo.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; by version 2 of the License or (at your
 *  choice) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "gcalresource.h"
#include "settings.h"
#include "settingsadaptor.h"

#include <QtDBus/QDBusConnection>
#include <kabc/addressee.h>
#include <kabc/phonenumber.h>
#include <kabc/key.h>
#include <kabc/errorhandler.h>
#include <kcal/event.h>
#include <kdatetime.h>
#include <qstring.h>
#include <KWindowSystem>
#include <akonadi/changerecorder.h>
#include <akonadi/itemfetchscope.h>
#include <KUrl>

extern "C" {
#include <gcalendar.h>
#include <gcal_status.h>
}

using namespace Akonadi;

GCalResource::GCalResource( const QString &id )
	: ResourceBase(id)
{
	new SettingsAdaptor( Settings::self() );
	QDBusConnection::sessionBus().registerObject(
		QLatin1String( "/Settings" ), Settings::self(),
		QDBusConnection::ExportAdaptors );

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

	if (!(gcal = gcal_new(GCALENDAR)))
		exit(1);
	gcal_set_store_xml(gcal, 1);
	all_events.length = 0;
	all_events.entries = NULL;
}

GCalResource::~GCalResource()
{
	gcal_cleanup_events(&all_events);
	pending.clear();
	deleted.clear();
}

void GCalResource::retrieveTimestamp(QString &timestamp)
{
	timestamp = Settings::self()->timestamp();
}

void GCalResource::saveTimestamp(QString &timestamp)
{
	Settings::self()->setTimestamp(timestamp);
	Settings::self()->writeConfig();
}

void GCalResource::retrieveCollections()
{
    if (!authenticated) {
	    kError() << "No authentication for Google Calendar available";
	    const QString message = i18nc("@info: status",
					  "Not yet authenticated for "
					  "use of Google Calendar");

	    emit error(message);

	    emit status(Broken, message);
	    return;
    }

    Collection c;
    c.setParent(Collection::root());
    c.setRemoteId("google-calendar");
    c.setName(name());

    QStringList mimeTypes;
    mimeTypes << "text/calendar";
    c.setContentMimeTypes(mimeTypes);

    Collection::List list;
    list << c;
    collectionsRetrieved(list);
}

void GCalResource::retrieveItems( const Akonadi::Collection &collection )
{
	Q_UNUSED(collection);
	Item::List items;
	int result;
	gcal_event_t event;
	QString timestamp;
	QByteArray t_byte;

	kError() << "\n............. retrieveItems ...........\n";
	if (!authenticated) {
		kError() << "No authentication for Google calendar available";
		const QString message = i18nc("@info:status",
					      "Not yet authenticated for"
					      " use of Google calendar");
		emit error(message);
		emit status(Broken, message);
		return;
	}

	/* Query by updated */
// 	retrieveTimestamp(timestamp);
// 	t_byte = timestamp.toLocal8Bit();
// 	if (t_byte.length() > TIMESTAMP_SIZE) {
// 		//TODO: implement getUpdated
// 		//result = getUpdated(t_byte.data());
// 		return;
// 	}
	kError() << "First retrieve";

	if ((result = gcal_get_events(gcal, &all_events)))
		exit(1);

	/* GCalendar returns last updated entry as first element */
	event = gcal_event_element(&all_events, 0);
	if (!event) {
		kError() << "Failed to retrieve last updated event.";
		const QString message = i18nc("@info:status",
					      "Failed getting last updated"
					      " event");
		emit error(message);
		emit status(Broken, message);
		return;

	}

	timestamp = gcal_event_get_updated(event);
	saveTimestamp(timestamp);

	/* Each google entry has a unique ID and edit_url */
	for (size_t i = 0; i < all_events.length; ++i) {
		Item item(QLatin1String("text/calendar"));
		KCal::Event kevent;
		QString temp;
		event = gcal_event_element(&all_events, i);

		temp = gcal_event_get_title(event);
		kevent.setSummary(temp);

		temp = gcal_event_get_where(event);
		kevent.setLocation(temp);

		KCal::Incidence::Status status;
		if (gcal_event_is_deleted(event))
			status = KCal::Incidence::StatusCanceled;
		else
			status = KCal::Incidence::StatusConfirmed;
		kevent.setStatus(status);

		temp = gcal_event_get_content(event);
		kevent.setDescription(temp);

		KDateTime start, end;
		temp = gcal_event_get_start(event);
		start.fromString(temp);
		temp = gcal_event_get_end(event);
		end.fromString(temp);
		kevent.setDtStart(start);
		kevent.setDtEnd(end);

		items << item;
	}

	itemsRetrieved(items);
}

bool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
	Q_UNUSED(parts);
	Q_UNUSED(item);
	return true;
}

void GCalResource::aboutToQuit()
{
	// TODO: any cleanup you need to do while there is still an active
	// event loop. The resource will terminate after this method returns
}

void GCalResource::doSetOnline(bool online)
{
	Q_UNUSED(online);
}

int GCalResource::getUpdated(char *timestamp)
{
	Q_UNUSED(timestamp);

	return -1;
}

void GCalResource::configure( WId windowId )
{
	int result = 0;
	if (windowId && dlgConf)
		KWindowSystem::setMainWindow(dlgConf, windowId);

	dlgConf->exec();
	if (!(result = authenticate(dlgConf->eAccount->text(),
				    dlgConf->ePass->text()))) {
		result = saveToWallet(dlgConf->eAccount->text(),
				      dlgConf->ePass->text(),
				      windowId);

		synchronize();
	}

	if (result) {
		kError() << "Failed configuring resource.";
		const QString message = i18nc("@info:status",
					      "Invalid password.");
		emit error(message);
		emit status(Broken, message);
		return;
	}
}

void GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
	Q_UNUSED(collection);

    gcal_event_t event;
    KCal::Event kevent;
    QByteArray t_byte;
    QString temp;

    if (!authenticated) {
        kError() << "No authentication for Google calendar available";
        const QString message = i18nc("@info:status",
                          "Not yet authenticated for"
                          " use of Google calendar");
        emit error(message);
        emit status(Broken, message);
        return;
    }

    if(item.hasPayload<KCal::Event>())
        kevent = item.payload<KCal::Event>();

    if (!(event = gcal_event_new(NULL))) {
        kError() << "Memory allocation error!";
        const QString message = i18nc("@info:status",
                      "Failed to create gcal_event");
        emit error(message);
        emit status(Broken, message);
        return;
    }

    temp = kevent.summary();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_title(event, t_byte);
    }

    temp = kevent.description();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_content(event, t_byte);
    }
    //TODO: event start, event end, status, url, id and etags

    temp = kevent.location();
    if(!temp.length()) {
        t_byte = temp.toLocal8Bit();
        gcal_event_set_where(event, t_byte);
    }
}

void GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
	Q_UNUSED(parts);
	Q_UNUSED(item);
}

void GCalResource::itemRemoved( const Akonadi::Item &item )
{
	Q_UNUSED(item);
}

AKONADI_RESOURCE_MAIN( GCalResource )

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


<commit_before>/* cuda_wrapper/device.hpp
 *
 * Copyright (C) 2007  Peter Colberg
 *
 * This file is part of cuda-wrapper.
 *
 * This software may be modified and distributed under the terms of the
 * 3-clause BSD license.  See accompanying file LICENSE for details.
 */

#ifndef CUDA_DEVICE_HPP
#define CUDA_DEVICE_HPP

#include <cuda_runtime.h>
#include <string>

#include <cuda_wrapper/error.hpp>

namespace cuda {

/**
 * CUDA device management
 */
class device
{
public:
    /**
     * returns number of devices available for execution
     */
    static int count()
    {
        int count;
        CUDA_CALL(cudaGetDeviceCount(&count));
        return count;
    }

    /**
     * set device on which the active host thread executes device code
     */
    static void set(int dev)
    {
        CUDA_CALL(cudaSetDevice(dev));
    }

    /**
     * get device on which the active host thread executes device code
     */
    static int get()
    {
        int dev;
        CUDA_CALL(cudaGetDevice(&dev));
        return dev;
    }

    /**
     * CUDA device properties
     */
    class properties
    {
    private:
        cudaDeviceProp prop;

    public:
        /**
         * empty initializer
         */
        properties() {}

        /**
         * retrieve properties of given device
         */
        properties(int dev)
        {
            CUDA_CALL(cudaGetDeviceProperties(&prop, dev));
        }

        /**
         * ASCII string identifying the device
         */
        std::string name() const
        {
            return prop.name;
        }

        /**
         * total amount of global memory available on the device in bytes
         */
        size_t total_global_mem() const
        {
            return prop.totalGlobalMem;
        }

        /**
         * total amount of shared memory available per block in bytes
         */
        size_t shared_mem_per_block() const
        {
            return prop.sharedMemPerBlock;
        }

        /**
         * total number of registers available per block
         */
        size_t regs_per_block() const
        {
            return prop.regsPerBlock;
        }

        /**
         * wrap size
         */
        size_t warp_size() const
        {
            return prop.warpSize;
        }

        /**
         * maximum allowed memory allocation pitch
         */
        size_t mem_pitch() const
        {
            return prop.memPitch;
        }

        /**
         * maximum number of threads per block
         */
        unsigned int max_threads_per_block() const
        {
            return prop.maxThreadsPerBlock;
        }

        /**
         * maximum sizes of each dimension of a block
         */
        dim3 max_threads_dim() const
        {
            return dim3(prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
        }

        /**
         * maximum sizes of each dimension of a grid
         */
        dim3 max_grid_size() const
        {
            return dim3(prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
        }

        /**
         * total amount of constant memory available on the device in bytes
         */
        size_t total_const_mem() const
        {
            return prop.totalConstMem;
        }

        /**
         * major revision number of device's compute capatibility
         */
        unsigned int major() const
        {
            return prop.major;
        }

        /**
         * minor revision number of device's compute capatibility
         */
        unsigned int minor() const
        {
            return prop.minor;
        }

        /**
         * clock frequency in kHz
         */
        unsigned int clock_rate() const
        {
            return prop.clockRate;
        }

        /**
         * texture alignment requirement
         */
        size_t texture_alignment() const
        {
            return prop.textureAlignment;
        }

#if (CUDART_VERSION >= 2000)
        /**
         * asynchronous kernel and memory operations capability
         */
        int device_overlap() const
        {
            return prop.deviceOverlap;
        }

        /**
         * number of multiprocessors
         */
        int multi_processor_count() const
        {
            return prop.multiProcessorCount;
        }
#endif /* CUDART_VERSION >= 2000 */
    };
};

} // namespace cuda

#endif /* ! CUDA_DEVICE_HPP */
<commit_msg>device: add max_threads_per_multi_processor() member<commit_after>/* cuda_wrapper/device.hpp
 *
 * Copyright (C) 2007  Peter Colberg
 *
 * This file is part of cuda-wrapper.
 *
 * This software may be modified and distributed under the terms of the
 * 3-clause BSD license.  See accompanying file LICENSE for details.
 */

#ifndef CUDA_DEVICE_HPP
#define CUDA_DEVICE_HPP

#include <cuda_runtime.h>
#include <string>

#include <cuda_wrapper/error.hpp>

namespace cuda {

/**
 * CUDA device management
 */
class device
{
public:
    /**
     * returns number of devices available for execution
     */
    static int count()
    {
        int count;
        CUDA_CALL(cudaGetDeviceCount(&count));
        return count;
    }

    /**
     * set device on which the active host thread executes device code
     */
    static void set(int dev)
    {
        CUDA_CALL(cudaSetDevice(dev));
    }

    /**
     * get device on which the active host thread executes device code
     */
    static int get()
    {
        int dev;
        CUDA_CALL(cudaGetDevice(&dev));
        return dev;
    }

    /**
     * CUDA device properties
     */
    class properties
    {
    private:
        cudaDeviceProp prop;

    public:
        /**
         * empty initializer
         */
        properties() {}

        /**
         * retrieve properties of given device
         */
        properties(int dev)
        {
            CUDA_CALL(cudaGetDeviceProperties(&prop, dev));
        }

        /**
         * ASCII string identifying the device
         */
        std::string name() const
        {
            return prop.name;
        }

        /**
         * total amount of global memory available on the device in bytes
         */
        size_t total_global_mem() const
        {
            return prop.totalGlobalMem;
        }

        /**
         * total amount of shared memory available per block in bytes
         */
        size_t shared_mem_per_block() const
        {
            return prop.sharedMemPerBlock;
        }

        /**
         * total number of registers available per block
         */
        size_t regs_per_block() const
        {
            return prop.regsPerBlock;
        }

        /**
         * wrap size
         */
        size_t warp_size() const
        {
            return prop.warpSize;
        }

        /**
         * maximum allowed memory allocation pitch
         */
        size_t mem_pitch() const
        {
            return prop.memPitch;
        }

        /**
         * maximum number of threads per block
         */
        unsigned int max_threads_per_block() const
        {
            return prop.maxThreadsPerBlock;
        }

        /**
         * maximum sizes of each dimension of a block
         */
        dim3 max_threads_dim() const
        {
            return dim3(prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
        }

        /**
         * maximum sizes of each dimension of a grid
         */
        dim3 max_grid_size() const
        {
            return dim3(prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
        }

        /**
         * total amount of constant memory available on the device in bytes
         */
        size_t total_const_mem() const
        {
            return prop.totalConstMem;
        }

        /**
         * major revision number of device's compute capatibility
         */
        unsigned int major() const
        {
            return prop.major;
        }

        /**
         * minor revision number of device's compute capatibility
         */
        unsigned int minor() const
        {
            return prop.minor;
        }

        /**
         * clock frequency in kHz
         */
        unsigned int clock_rate() const
        {
            return prop.clockRate;
        }

        /**
         * texture alignment requirement
         */
        size_t texture_alignment() const
        {
            return prop.textureAlignment;
        }

#if (CUDART_VERSION >= 2000)
        /**
         * asynchronous kernel and memory operations capability
         */
        int device_overlap() const
        {
            return prop.deviceOverlap;
        }

        /**
         * number of multiprocessors
         */
        int multi_processor_count() const
        {
            return prop.multiProcessorCount;
        }
#endif /* CUDART_VERSION >= 2000 */
#if (CUDART_VERSION >= 4000)
        /**
         * maximum resident threads per multiprocessor
         */
        int max_threads_per_multi_processor() const
        {
            return prop.maxThreadsPerMultiProcessor;
        }
#endif /* CUDART_VERSION >= 4000 */
    };
};

} // namespace cuda

#endif /* ! CUDA_DEVICE_HPP */
<|endoftext|>


<commit_before>// Copyright 2022 Michael Fisher <mfisher@lvtk.org>
// SPDX-License-Identifier: ISC

#include <vector>

#include <lvtk/ui/font.hpp>

#include "gl.hpp"

#include "../nanovg/nanovg.h"
#include "../nanovg/nanovg_gl.h"
#include "Roboto-Bold.ttf.h"
#include "Roboto-Regular.ttf.h"
#include "nanovg.hpp"

namespace lvtk {
namespace nvg {
namespace detail {

static constexpr const char* default_font_face      = "Roboto-Normal";
static constexpr const char* default_font_face_bold = "Roboto-Bold";

#if defined(NANOVG_GL2)
static constexpr auto create  = nvgCreateGL2;
static constexpr auto destroy = nvgDeleteGL2;
#elif defined(NANOVG_GL3)
static constexpr auto create  = nvgCreateGL3;
static constexpr auto destroy = nvgDeleteGL3;
#else
#    error "No GL version specified for NanoVG"
#endif

} // namespace detail

namespace convert {
static int alignment (Alignment align) {
    uint32_t flags = 0;

    if ((align.flags() & Alignment::LEFT) != 0)
        flags |= NVG_ALIGN_LEFT;
    if ((align.flags() & Alignment::RIGHT) != 0)
        flags |= NVG_ALIGN_RIGHT;
    if ((align.flags() & Alignment::CENTER) != 0)
        flags |= NVG_ALIGN_CENTER;
    if ((align.flags() & Alignment::TOP) != 0)
        flags |= NVG_ALIGN_TOP;
    if ((align.flags() & Alignment::BOTTOM) != 0)
        flags |= NVG_ALIGN_BOTTOM;
    if ((align.flags() & Alignment::MIDDLE) != 0)
        flags |= NVG_ALIGN_MIDDLE;

    return static_cast<int> (flags);
};

} // namespace convert

class Context::Ctx {
    int _font_normal = 0;
    int _font_bold   = 0;

public:
    Ctx() : ctx (detail::create (NVG_ANTIALIAS | NVG_STENCIL_STROKES)) {
        _font_normal = nvgCreateFontMem (ctx,
                                         detail::default_font_face,
                                         (uint8_t*) Roboto_Regular_ttf,
                                         Roboto_Regular_ttf_size,
                                         0);
        _font_bold = nvgCreateFontMem (ctx,
                                         detail::default_font_face_bold,
                                         (uint8_t*) Roboto_Bold_ttf,
                                         Roboto_Bold_ttf_size,
                                         0);
    }

    ~Ctx() {
        if (ctx)
            detail::destroy (ctx);
    }

    void save() {
        stack.push_back (state);
        nvgSave (ctx);
    }

    void restore() {
        if (stack.empty())
            return;
        state = stack.back();
        stack.pop_back();
        nvgRestore (ctx);
    }

private:
    friend class nvg::Context;
    NVGcontext* ctx { nullptr };
    struct State {
        NVGcolor color;
        Rectangle<float> clip;
        Font font;
        int font_id = 0;

        State& operator= (const State& o) {
            color = o.color;
            clip  = o.clip;
            font  = o.font;
            font_id = o.font_id;
            return *this;
        }
    };

    float internal_scale = 1.f;
    State state;
    std::vector<State> stack;
};

Context::Context()
    : ctx (std::make_unique<Ctx>()) {
    set_fill (Color (0.f, 0.f, 0.f, 1.f));
}

Context::~Context() {
    ctx.reset();
}

float Context::scale_factor() const noexcept {
    return ctx->internal_scale;
}

void Context::translate (const Point<int>& pt) {
    nvgTranslate (ctx->ctx, (float) pt.x, (float) pt.y);
}

void Context::transform (const Transform& mat) {
    nvgTransform (ctx->ctx, mat.m00, mat.m01, mat.m02, mat.m10, mat.m11, mat.m12);
}

void Context::clip (const Rectangle<int>& r) {
    ctx->state.clip = r.as<float>();
    nvgScissor (ctx->ctx,
                ctx->state.clip.x,
                ctx->state.clip.y,
                ctx->state.clip.width,
                ctx->state.clip.height);
}

void Context::intersect_clip (const Rectangle<int>& r) {
    nvgIntersectScissor (ctx->ctx, r.x, r.y, r.width, r.height);
}

Rectangle<int> Context::last_clip() const {
    return (ctx->state.clip).as<int>();
}

Font Context::font() const noexcept { return ctx->state.font; }
void Context::set_font (const Font& font) {
    ctx->state.font = font;
    ctx->state.font_id = font.bold() ? ctx->_font_bold : ctx->_font_normal;
}

void Context::set_fill (const Fill& fill) {
    auto c      = fill.color();
    auto& color = ctx->state.color;
    color.r     = c.fred();
    color.g     = c.fgreen();
    color.b     = c.fblue();
    color.a     = c.falpha();
}

void Context::save() { ctx->save(); }
void Context::restore() { ctx->restore(); }

void Context::begin_frame (int width, int height, float scale) {
    ctx->internal_scale = scale;
    nvgBeginFrame (ctx->ctx,
                   (float) width,
                   (float) height,
                   ctx->internal_scale);
}

void Context::end_frame() {
    nvgEndFrame (ctx->ctx);
}

void Context::fill_rect (const Rectangle<float>& r) {
    nvgBeginPath (ctx->ctx);

    nvgRect (ctx->ctx,
             (r.x),
             (r.y),
             r.width,
             r.height);

    nvgFillColor (ctx->ctx, ctx->state.color);
    nvgFill (ctx->ctx);
}

bool Context::text (const std::string& text, float x, float y, Alignment align) {
    const auto& font = ctx->state.font;
    nvgFontSize (ctx->ctx, ctx->state.font.height());
    nvgFontFaceId (ctx->ctx, ctx->state.font_id);
    nvgTextAlign (ctx->ctx, convert::alignment (align));
    nvgFillColor (ctx->ctx, ctx->state.color);
    nvgText (ctx->ctx, x, y, text.c_str(), nullptr);
    return true;
}

} // namespace nvg
} // namespace lvtk
<commit_msg>remove unused variable<commit_after>// Copyright 2022 Michael Fisher <mfisher@lvtk.org>
// SPDX-License-Identifier: ISC

#include <vector>

#include <lvtk/ui/font.hpp>

#include "gl.hpp"

#include "../nanovg/nanovg.h"
#include "../nanovg/nanovg_gl.h"
#include "Roboto-Bold.ttf.h"
#include "Roboto-Regular.ttf.h"
#include "nanovg.hpp"

namespace lvtk {
namespace nvg {
namespace detail {

static constexpr const char* default_font_face      = "Roboto-Normal";
static constexpr const char* default_font_face_bold = "Roboto-Bold";

#if defined(NANOVG_GL2)
static constexpr auto create  = nvgCreateGL2;
static constexpr auto destroy = nvgDeleteGL2;
#elif defined(NANOVG_GL3)
static constexpr auto create  = nvgCreateGL3;
static constexpr auto destroy = nvgDeleteGL3;
#else
#    error "No GL version specified for NanoVG"
#endif

} // namespace detail

namespace convert {
static int alignment (Alignment align) {
    uint32_t flags = 0;

    if ((align.flags() & Alignment::LEFT) != 0)
        flags |= NVG_ALIGN_LEFT;
    if ((align.flags() & Alignment::RIGHT) != 0)
        flags |= NVG_ALIGN_RIGHT;
    if ((align.flags() & Alignment::CENTER) != 0)
        flags |= NVG_ALIGN_CENTER;
    if ((align.flags() & Alignment::TOP) != 0)
        flags |= NVG_ALIGN_TOP;
    if ((align.flags() & Alignment::BOTTOM) != 0)
        flags |= NVG_ALIGN_BOTTOM;
    if ((align.flags() & Alignment::MIDDLE) != 0)
        flags |= NVG_ALIGN_MIDDLE;

    return static_cast<int> (flags);
};

} // namespace convert

class Context::Ctx {
    int _font_normal = 0;
    int _font_bold   = 0;

public:
    Ctx() : ctx (detail::create (NVG_ANTIALIAS | NVG_STENCIL_STROKES)) {
        _font_normal = nvgCreateFontMem (ctx,
                                         detail::default_font_face,
                                         (uint8_t*) Roboto_Regular_ttf,
                                         Roboto_Regular_ttf_size,
                                         0);
        _font_bold = nvgCreateFontMem (ctx,
                                         detail::default_font_face_bold,
                                         (uint8_t*) Roboto_Bold_ttf,
                                         Roboto_Bold_ttf_size,
                                         0);
    }

    ~Ctx() {
        if (ctx)
            detail::destroy (ctx);
    }

    void save() {
        stack.push_back (state);
        nvgSave (ctx);
    }

    void restore() {
        if (stack.empty())
            return;
        state = stack.back();
        stack.pop_back();
        nvgRestore (ctx);
    }

private:
    friend class nvg::Context;
    NVGcontext* ctx { nullptr };
    struct State {
        NVGcolor color;
        Rectangle<float> clip;
        Font font;
        int font_id = 0;

        State& operator= (const State& o) {
            color = o.color;
            clip  = o.clip;
            font  = o.font;
            font_id = o.font_id;
            return *this;
        }
    };

    float internal_scale = 1.f;
    State state;
    std::vector<State> stack;
};

Context::Context()
    : ctx (std::make_unique<Ctx>()) {
    set_fill (Color (0.f, 0.f, 0.f, 1.f));
}

Context::~Context() {
    ctx.reset();
}

float Context::scale_factor() const noexcept {
    return ctx->internal_scale;
}

void Context::translate (const Point<int>& pt) {
    nvgTranslate (ctx->ctx, (float) pt.x, (float) pt.y);
}

void Context::transform (const Transform& mat) {
    nvgTransform (ctx->ctx, mat.m00, mat.m01, mat.m02, mat.m10, mat.m11, mat.m12);
}

void Context::clip (const Rectangle<int>& r) {
    ctx->state.clip = r.as<float>();
    nvgScissor (ctx->ctx,
                ctx->state.clip.x,
                ctx->state.clip.y,
                ctx->state.clip.width,
                ctx->state.clip.height);
}

void Context::intersect_clip (const Rectangle<int>& r) {
    nvgIntersectScissor (ctx->ctx, r.x, r.y, r.width, r.height);
}

Rectangle<int> Context::last_clip() const {
    return (ctx->state.clip).as<int>();
}

Font Context::font() const noexcept { return ctx->state.font; }
void Context::set_font (const Font& font) {
    ctx->state.font = font;
    ctx->state.font_id = font.bold() ? ctx->_font_bold : ctx->_font_normal;
}

void Context::set_fill (const Fill& fill) {
    auto c      = fill.color();
    auto& color = ctx->state.color;
    color.r     = c.fred();
    color.g     = c.fgreen();
    color.b     = c.fblue();
    color.a     = c.falpha();
}

void Context::save() { ctx->save(); }
void Context::restore() { ctx->restore(); }

void Context::begin_frame (int width, int height, float scale) {
    ctx->internal_scale = scale;
    nvgBeginFrame (ctx->ctx,
                   (float) width,
                   (float) height,
                   ctx->internal_scale);
}

void Context::end_frame() {
    nvgEndFrame (ctx->ctx);
}

void Context::fill_rect (const Rectangle<float>& r) {
    nvgBeginPath (ctx->ctx);

    nvgRect (ctx->ctx,
             (r.x),
             (r.y),
             r.width,
             r.height);

    nvgFillColor (ctx->ctx, ctx->state.color);
    nvgFill (ctx->ctx);
}

bool Context::text (const std::string& text, float x, float y, Alignment align) {
    nvgFontSize (ctx->ctx, ctx->state.font.height());
    nvgFontFaceId (ctx->ctx, ctx->state.font_id);
    nvgTextAlign (ctx->ctx, convert::alignment (align));
    nvgFillColor (ctx->ctx, ctx->state.color);
    nvgText (ctx->ctx, x, y, text.c_str(), nullptr);
    return true;
}

} // namespace nvg
} // namespace lvtk
<|endoftext|>


<commit_before>/*
 * Restructuring Shogun's statistical hypothesis testing framework.
 * Copyright (C) 2016  Soumyajit De
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the selfied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <algorithm>
#include <shogun/lib/SGVector.h>
#include <shogun/mathematics/Math.h>
#include <shogun/statistical_testing/HypothesisTest.h>
#include <shogun/statistical_testing/internals/TestTypes.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/KernelManager.h>

using namespace shogun;
using namespace internal;

struct CHypothesisTest::Self
{
	Self(index_t num_distributions, index_t num_kernels)
	: data_manager(num_distributions), kernel_manager(num_kernels)
	{
	}
	DataManager data_manager;
	KernelManager kernel_manager;
};

CHypothesisTest::CHypothesisTest(index_t num_distributions, index_t num_kernels) : CSGObject()
{
	self = std::unique_ptr<Self>(new CHypothesisTest::Self(num_distributions, num_kernels));
}

CHypothesisTest::~CHypothesisTest()
{
}

DataManager& CHypothesisTest::get_data_manager()
{
	return self->data_manager;
}

const DataManager& CHypothesisTest::get_data_manager() const
{
	return self->data_manager;
}

KernelManager& CHypothesisTest::get_kernel_manager()
{
	return self->kernel_manager;
}

const KernelManager& CHypothesisTest::get_kernel_manager() const
{
	return self->kernel_manager;
}

float64_t CHypothesisTest::compute_p_value(float64_t statistic)
{
	SGVector<float64_t> values = sample_null();

	std::sort(values.vector, values.vector + values.vlen);
	float64_t i = values.find_position_to_insert(statistic);

	return 1.0 - i / values.vlen;
}

float64_t CHypothesisTest::compute_threshold(float64_t alpha)
{
	float64_t result = 0;
	SGVector<float64_t> values = sample_null();

	std::sort(values.vector, values.vector + values.vlen);
	return values[index_t(CMath::floor(values.vlen * (1 - alpha)))];
}

const char* CHypothesisTest::get_name() const
{
	return "HypothesisTest";
}
<commit_msg>removed unused variable result<commit_after>/*
 * Restructuring Shogun's statistical hypothesis testing framework.
 * Copyright (C) 2016  Soumyajit De
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the selfied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <algorithm>
#include <shogun/lib/SGVector.h>
#include <shogun/mathematics/Math.h>
#include <shogun/statistical_testing/HypothesisTest.h>
#include <shogun/statistical_testing/internals/TestTypes.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/KernelManager.h>

using namespace shogun;
using namespace internal;

struct CHypothesisTest::Self
{
	Self(index_t num_distributions, index_t num_kernels)
	: data_manager(num_distributions), kernel_manager(num_kernels)
	{
	}
	DataManager data_manager;
	KernelManager kernel_manager;
};

CHypothesisTest::CHypothesisTest(index_t num_distributions, index_t num_kernels) : CSGObject()
{
	self = std::unique_ptr<Self>(new CHypothesisTest::Self(num_distributions, num_kernels));
}

CHypothesisTest::~CHypothesisTest()
{
}

DataManager& CHypothesisTest::get_data_manager()
{
	return self->data_manager;
}

const DataManager& CHypothesisTest::get_data_manager() const
{
	return self->data_manager;
}

KernelManager& CHypothesisTest::get_kernel_manager()
{
	return self->kernel_manager;
}

const KernelManager& CHypothesisTest::get_kernel_manager() const
{
	return self->kernel_manager;
}

float64_t CHypothesisTest::compute_p_value(float64_t statistic)
{
	SGVector<float64_t> values = sample_null();

	std::sort(values.vector, values.vector + values.vlen);
	float64_t i = values.find_position_to_insert(statistic);

	return 1.0 - i / values.vlen;
}

float64_t CHypothesisTest::compute_threshold(float64_t alpha)
{
	SGVector<float64_t> values = sample_null();
	std::sort(values.vector, values.vector + values.vlen);
	return values[index_t(CMath::floor(values.vlen * (1 - alpha)))];
}

const char* CHypothesisTest::get_name() const
{
	return "HypothesisTest";
}
<|endoftext|>


<commit_before>#ifndef STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP
#define STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP

#include <stan/lang/grammars/expression_grammar.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <sstream>
#include <string>
#include <vector>

BOOST_FUSION_ADAPT_STRUCT(stan::lang::conditional_op,
                          (stan::lang::expression, cond_)
                          (stan::lang::expression, true_val_)
                          (stan::lang::expression, false_val_) )

namespace stan {

  namespace lang {

    template <typename Iterator>
    expression_grammar<Iterator>::expression_grammar(variable_map& var_map,
                                             std::stringstream& error_msgs)
      : expression_grammar::base_type(expression_r),
        var_map_(var_map),
        error_msgs_(error_msgs),
        expression07_g(var_map, error_msgs, *this) {
      using boost::spirit::qi::char_;
      using boost::spirit::qi::eps;
      using boost::spirit::qi::lit;
      using boost::spirit::qi::no_skip;
      using boost::spirit::qi::_1;
      using boost::spirit::qi::_pass;
      using boost::spirit::qi::_val;
      using boost::spirit::qi::labels::_r1;

      // expression_r.name("expression");
      // expression_r
      //   %= conditional_op_r(_r1)
      //   | expression15_r(_r1);

      // conditional_op_r.name("conditional op expression, cond ? t_val : f_val ");
      // conditional_op_r
      //   %= expression15_r(_r1)
      //   >> lit("?")
      //   >> expression_r(_r1)
      //   >> lit(":")
      //   >> expression_r(_r1)[validate_conditional_op_f(_val, _pass,
      //                                boost::phoenix::ref(error_msgs))];

      // expression_r
      //   %= expression15_r(_r1)
      //   >> -(lit('?')
      //        >> expression_r(_r1)
      //        >> lit("'")
      //        >> expression_r(_r1)
      //           [validate_conditional_op_f(_val, _pass,
      //                                      boost::phoenix::ref(error_msgs))]);

      expression_r.name("expression");
      expression_r
        %= (expression15_r(_r1) >> no_skip[!char_('?')] > eps)
        | conditional_op_r(_r1);

      conditional_op_r.name("conditional op expression, cond ? t_val : f_val ");
      conditional_op_r
        %= expression15_r(_r1)
        >> lit("?")
        >> expression_r(_r1)
        >> lit(":")
        >> expression_r(_r1)[validate_conditional_op_f(_val, _pass,
                                     boost::phoenix::ref(error_msgs))];

      expression15_r.name("expression");
      expression15_r
        = expression14_r(_r1)[assign_lhs_f(_val, _1)]
        > *(lit("||")
            > expression14_r(_r1)
              [binary_op_f(_val, _1, "||", "logical_or",
                           boost::phoenix::ref(error_msgs))]);

      expression14_r.name("expression");
      expression14_r
        = expression10_r(_r1)[assign_lhs_f(_val, _1)]
        > *(lit("&&")
            > expression10_r(_r1)
              [binary_op_f(_val, _1, "&&", "logical_and",
                           boost::phoenix::ref(error_msgs))]);

      expression10_r.name("expression");
      expression10_r
        = expression09_r(_r1)[assign_lhs_f(_val, _1)]
        > *((lit("==")
             > expression09_r(_r1)
               [binary_op_f(_val, _1, "==", "logical_eq",
                            boost::phoenix::ref(error_msgs))])
              |
              (lit("!=")
               > expression09_r(_r1)
                 [binary_op_f(_val, _1, "!=", "logical_neq",
                              boost::phoenix::ref(error_msgs))]));

      expression09_r.name("expression");
      expression09_r
        = expression07_g(_r1)[assign_lhs_f(_val, _1)]
        > *((lit("<=")
             > expression07_g(_r1)
               [binary_op_f(_val, _1, "<", "logical_lte",
                            boost::phoenix::ref(error_msgs))])
            | (lit("<")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, "<=", "logical_lt",
                              boost::phoenix::ref(error_msgs))])
            | (lit(">=")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, ">", "logical_gte",
                              boost::phoenix::ref(error_msgs))])
            | (lit(">")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, ">=", "logical_gt",
                              boost::phoenix::ref(error_msgs))]));
    }
  }
}
#endif
<commit_msg>fix cpplint errors<commit_after>#ifndef STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP
#define STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP

#include <stan/lang/grammars/expression_grammar.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <sstream>
#include <string>
#include <vector>

BOOST_FUSION_ADAPT_STRUCT(stan::lang::conditional_op,
                          (stan::lang::expression, cond_)
                          (stan::lang::expression, true_val_)
                          (stan::lang::expression, false_val_) )

namespace stan {

  namespace lang {

    template <typename Iterator>
    expression_grammar<Iterator>::expression_grammar(variable_map& var_map,
                                             std::stringstream& error_msgs)
      : expression_grammar::base_type(expression_r),
        var_map_(var_map),
        error_msgs_(error_msgs),
        expression07_g(var_map, error_msgs, *this) {
      using boost::spirit::qi::char_;
      using boost::spirit::qi::eps;
      using boost::spirit::qi::lit;
      using boost::spirit::qi::no_skip;
      using boost::spirit::qi::_1;
      using boost::spirit::qi::_pass;
      using boost::spirit::qi::_val;
      using boost::spirit::qi::labels::_r1;

      expression_r.name("expression");
      expression_r
        %= (expression15_r(_r1) >> no_skip[!char_('?')] > eps)
        | conditional_op_r(_r1);

      conditional_op_r.name("conditional op expression, cond ? t_val : f_val ");
      conditional_op_r
        %= expression15_r(_r1)
        >> lit("?")
        >> expression_r(_r1)
        >> lit(":")
        >> expression_r(_r1)[validate_conditional_op_f(_val, _pass,
                                     boost::phoenix::ref(error_msgs))];

      expression15_r.name("expression");
      expression15_r
        = expression14_r(_r1)[assign_lhs_f(_val, _1)]
        > *(lit("||")
            > expression14_r(_r1)
              [binary_op_f(_val, _1, "||", "logical_or",
                           boost::phoenix::ref(error_msgs))]);

      expression14_r.name("expression");
      expression14_r
        = expression10_r(_r1)[assign_lhs_f(_val, _1)]
        > *(lit("&&")
            > expression10_r(_r1)
              [binary_op_f(_val, _1, "&&", "logical_and",
                           boost::phoenix::ref(error_msgs))]);

      expression10_r.name("expression");
      expression10_r
        = expression09_r(_r1)[assign_lhs_f(_val, _1)]
        > *((lit("==")
             > expression09_r(_r1)
               [binary_op_f(_val, _1, "==", "logical_eq",
                            boost::phoenix::ref(error_msgs))])
              |
              (lit("!=")
               > expression09_r(_r1)
                 [binary_op_f(_val, _1, "!=", "logical_neq",
                              boost::phoenix::ref(error_msgs))]));

      expression09_r.name("expression");
      expression09_r
        = expression07_g(_r1)[assign_lhs_f(_val, _1)]
        > *((lit("<=")
             > expression07_g(_r1)
               [binary_op_f(_val, _1, "<", "logical_lte",
                            boost::phoenix::ref(error_msgs))])
            | (lit("<")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, "<=", "logical_lt",
                              boost::phoenix::ref(error_msgs))])
            | (lit(">=")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, ">", "logical_gte",
                              boost::phoenix::ref(error_msgs))])
            | (lit(">")
               > expression07_g(_r1)
                 [binary_op_f(_val, _1, ">=", "logical_gt",
                              boost::phoenix::ref(error_msgs))]));
    }
  }
}
#endif
<|endoftext|>


<commit_before>/**
 * \file extract_extending_graph.cpp
 *
 * Implementation for the extract_extending_graph algorithm.
 */

#include "extract_extending_graph.hpp"

//#define debug_vg_algorithms

namespace vg {
namespace algorithms {

    unordered_map<id_t, id_t> extract_extending_graph(const HandleGraph* source, Graph& g, int64_t max_dist, pos_t pos,
                                                      bool backward, bool preserve_cycles_on_src) {

        if (g.node_size() || g.edge_size()) {
            cerr << "error:[extract_extending_graph] must extract into an empty graph" << endl;
            assert(false);
        }

#ifdef debug_vg_algorithms
        cerr << "[extract_extending_graph] extracting exending graph from " << pos << " in " << (backward ? "backward" : "forward") << " direction with max search dist " << max_dist << endl;
#endif

        // TODO: these structs are duplicative with extract_connecting_graph

        // a local struct that packages a handle with its distance from the first position
        struct Traversal {
            Traversal(handle_t handle, int64_t dist) : handle(handle), dist(dist) {}
            int64_t dist; // distance from pos to the right side of this node
            handle_t handle; // Oriented node traversal
            inline bool operator<(const Traversal& other) const {
                return dist > other.dist; // opposite order so priority queue selects minimum
            }
        };

        // a map from node ids in the extracted graph to the node ids in the original graph
        unordered_map<id_t, id_t> id_trans;

        // a graph index that we will maintain as we extract the subgraph
        unordered_map<id_t, Node*> graph;
        Node* src_node = g.add_node();
        src_node->set_sequence(source->get_sequence(source->get_handle(id(pos))));
        src_node->set_id(id(pos));
        graph[id(pos)] = src_node;
        id_trans[id(pos)] = id(pos);

        // Keep a handle to where we start from.
        // If the queue stays empty and we do no searching, the handle will be
        // uninitialized.
        handle_t start_handle;

        // initialize the queue
        priority_queue<Traversal> queue;
        if (backward) {
            int64_t dist = offset(pos);
            if (dist < max_dist) {
                // We need to leave the node to get enough sequence
                start_handle = source->get_handle(id(pos), !is_rev(pos));
                queue.emplace(start_handle, dist);
            }
        }
        else {
            int64_t dist = g.node(0).sequence().size() - offset(pos);
            if (dist < max_dist) {
                // We need to leave the node to get enough sequence
                start_handle = source->get_handle(id(pos), is_rev(pos));
                queue.emplace(start_handle, dist);
            }
        }

        id_t max_id = id(pos);
        bool cycled_to_source = false;
        unordered_set<handle_t> traversed;
        unordered_set<pair<handle_t, handle_t>> observed_edges;

        while (!queue.empty()) {
            // get the next shortest distance traversal from either the init
            Traversal trav = queue.top();
            queue.pop();

#ifdef debug_vg_algorithms
            cerr << "[extract_extending_graph] traversing " << source->get_id(trav.handle)
                << (source->get_is_reverse(trav.handle) ? "-" : "+") << " at dist " << trav.dist << endl;
#endif

            // make sure we haven't traversed this node already
            if (traversed.count(trav.handle)) {
                continue;
            }
            // mark the node as traversed
            traversed.emplace(trav.handle);

            // Now go out the right local side
            source->follow_edges(trav.handle, false, [&](const handle_t& next) {
                // For each next handle...

#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] checking edge " << source->get_id(trav.handle)
                << (source->get_is_reverse(trav.handle) ? "-" : "+") << " -> " << source->get_id(next)
                << (source->get_is_reverse(next) ? "-" : "+") << endl;
#endif

                // Get the ID of where we're going.
                auto next_id = source->get_id(next);

                // do we ever return to the source node?
                cycled_to_source = cycled_to_source || next_id == id(pos);

                // record the edge
                observed_edges.insert(source->edge_handle(trav.handle, next));

                // make sure the node is in the graph
                if (!graph.count(next_id)) {
                    Node* node = g.add_node();
                    // Grab the sequence in its local forward orientation.
                    node->set_sequence(source->get_sequence(source->forward(next)));
                    node->set_id(next_id);
                    graph[next_id] = node;
                    id_trans[next_id] = next_id;
                    max_id = std::max(next_id, max_id);
                }

                // distance to the end of this node
                int64_t dist_thru = trav.dist + graph[next_id]->sequence().size();
                if (!traversed.count(next) && dist_thru < max_dist) {
                    // we can add more nodes along same path without going over the max length
                    queue.emplace(next, dist_thru);
#ifdef debug_vg_algorithms
                    cerr << "[extract_extending_graph] enqueuing " << source->get_id(next)
                        << (source->get_is_reverse(next) ? "-" : "+") << " at dist " << dist_thru << endl;
#endif
                }
            });
        }

        vector<pair<handle_t, handle_t>> src_edges;

        // add the edges to the graph
        for (const pair<handle_t, handle_t>& edge : observed_edges) {
            // This loop will never run unless we actually ran the search, so it is safe to use start_handle here.
            bool add_edge;
            if (source->forward(edge.first) == source->forward(start_handle) ||
                source->forward(edge.second) == source->forward(start_handle)) {
                // record the edges that touch the source in case we need to duplicate them
                src_edges.push_back(edge);
                // does the edge only touch the side of the source node that's not going to be cut?
                // That means it must touch only the right side of our starting handle.
                // We know it touches one side, so make sure it *doesn't* touch the left side.
                // Which means we need the reverse of our starting handle to not
                // be the left handle, and our handle to not be the right
                // handle.
                add_edge = !(edge.first == source->flip(start_handle) || edge.second == start_handle);
#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << (add_edge ? "" : "not ") << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " that touches source node" << endl;
#endif
            }
            else {
                // the edge doesn't touch the source node, so it will certainly survive the cut
                add_edge = true;
#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " that does not touch source node" << endl;
#endif
            }

            if (add_edge) {
                Edge* e = g.add_edge();
                e->set_from(source->get_id(edge.first));
                e->set_from_start(source->get_is_reverse(edge.first));
                e->set_to(source->get_id(edge.second));
                e->set_to_end(source->get_is_reverse(edge.second));
            }
        }

        if (cycled_to_source && preserve_cycles_on_src) {
            // we need to duplicate the source node to ensure that cycles on it will be preserved
            // after we cut it

            // choose an ID that hasn't been used yet
            id_t dup_id = max_id + 1;

            // duplicate the node
            Node* dup_node = g.add_node();
            dup_node->set_id(dup_id);
            dup_node->set_sequence(graph[id(pos)]->sequence());

            // record the ID translation
            id_trans[dup_id] = id(pos);

            for (const pair<handle_t, handle_t>& edge : src_edges) {
                Edge* e = g.add_edge();
                e->set_from_start(source->get_is_reverse(edge.first));
                e->set_to_end(source->get_is_reverse(edge.second));

                // Load the IDs for this edge
                auto from_id = source->get_id(edge.first);
                auto to_id = source->get_id(edge.second);

#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " to source node copy" << endl;
#endif

                if (from_id == id(pos) && to_id == id(pos)) {
                    // this edge is a self loop, always make a copy on the duplicated node
                    e->set_from(dup_id);
                    e->set_to(dup_id);

                    // if one of the ends of the edge is on the non-cut side of the source, also make a copy
                    // between the original and the duplicated node
                    if (from_id == id(pos) && source->get_is_reverse(edge.first) == (backward != is_rev(pos))) {
                        e = g.add_edge();
                        e->set_from(id(pos));
                        e->set_to(dup_id);
                        e->set_from_start(source->get_is_reverse(edge.first));
                        e->set_to_end(source->get_is_reverse(edge.second));
                    }
                    else if (to_id == id(pos) && source->get_is_reverse(edge.second) != (backward != is_rev(pos))) {
                        e = g.add_edge();
                        e->set_from(dup_id);
                        e->set_to(id(pos));
                        e->set_from_start(source->get_is_reverse(edge.first));
                        e->set_to_end(source->get_is_reverse(edge.second));
                    }
                }
                else if (from_id == id(pos)) {
                    // add a copy of the edge from the other node to the duplicated node
                    e->set_from(dup_id);
                    e->set_to(to_id);
                }
                else {
                    // add a copy of the edge from the other node to the duplicated node
                    e->set_from(from_id);
                    e->set_to(dup_id);
                }
            }
        }

        // cut the source node at the starting position
        if (is_rev(pos) && backward) {
            src_node->set_sequence(src_node->sequence().substr(src_node->sequence().size() - offset(pos), offset(pos)));
        }
        else if (is_rev(pos)) {
            src_node->set_sequence(src_node->sequence().substr(0, src_node->sequence().size() - offset(pos)));
        }
        else if (backward) {
            src_node->set_sequence(src_node->sequence().substr(0, offset(pos)));
        }
        else {
            src_node->set_sequence(src_node->sequence().substr(offset(pos), src_node->sequence().size() - offset(pos)));
        }

        return id_trans;
    }
}
}
<commit_msg>Make extract_extending_graph use easy Dijkstra<commit_after>/**
 * \file extract_extending_graph.cpp
 *
 * Implementation for the extract_extending_graph algorithm.
 */

#include "extract_extending_graph.hpp"

//#define debug_vg_algorithms

namespace vg {
namespace algorithms {

    unordered_map<id_t, id_t> extract_extending_graph(const HandleGraph* source, Graph& g, int64_t max_dist, pos_t pos,
                                                      bool backward, bool preserve_cycles_on_src) {

        if (g.node_size() || g.edge_size()) {
            cerr << "error:[extract_extending_graph] must extract into an empty graph" << endl;
            assert(false);
        }

#ifdef debug_vg_algorithms
        cerr << "[extract_extending_graph] extracting exending graph from " << pos << " in " << (backward ? "backward" : "forward") << " direction with max search dist " << max_dist << endl;
#endif

        // TODO: these structs are duplicative with extract_connecting_graph

        // a local struct that packages a handle with its distance from the first position
        struct Traversal {
            Traversal(handle_t handle, int64_t dist) : handle(handle), dist(dist) {}
            int64_t dist; // distance from pos to the right side of this node
            handle_t handle; // Oriented node traversal
            inline bool operator<(const Traversal& other) const {
                return dist > other.dist; // opposite order so priority queue selects minimum
            }
        };

        // a map from node ids in the extracted graph to the node ids in the original graph
        unordered_map<id_t, id_t> id_trans;

        // a graph index that we will maintain as we extract the subgraph
        unordered_map<id_t, Node*> graph;
        Node* src_node = g.add_node();
        src_node->set_sequence(source->get_sequence(source->get_handle(id(pos))));
        src_node->set_id(id(pos));
        graph[id(pos)] = src_node;
        id_trans[id(pos)] = id(pos);

        // Keep a handle to where we start from.
        // If the queue stays empty and we do no searching, the handle will be
        // uninitialized.
        handle_t start_handle;

        // initialize the queue for Dijkstra traversal.
        FilteredPriorityQueue<Traversal, handle_t> queue([](const Traversal& item) {
            return item.handle;
        });

        if (backward) {
            int64_t dist = offset(pos);
            if (dist < max_dist) {
                // We need to leave the node to get enough sequence
                start_handle = source->get_handle(id(pos), !is_rev(pos));
                queue.emplace(start_handle, dist);
            }
        }
        else {
            int64_t dist = g.node(0).sequence().size() - offset(pos);
            if (dist < max_dist) {
                // We need to leave the node to get enough sequence
                start_handle = source->get_handle(id(pos), is_rev(pos));
                queue.emplace(start_handle, dist);
            }
        }

        id_t max_id = id(pos);
        bool cycled_to_source = false;
        unordered_set<pair<handle_t, handle_t>> observed_edges;

        while (!queue.empty()) {
            // get the next shortest distance traversal from either the init
            Traversal trav = queue.top();
            queue.pop();

#ifdef debug_vg_algorithms
            cerr << "[extract_extending_graph] traversing " << source->get_id(trav.handle)
                << (source->get_is_reverse(trav.handle) ? "-" : "+") << " at dist " << trav.dist << endl;
#endif

            // Now go out the right local side
            source->follow_edges(trav.handle, false, [&](const handle_t& next) {
                // For each next handle...

#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] checking edge " << source->get_id(trav.handle)
                << (source->get_is_reverse(trav.handle) ? "-" : "+") << " -> " << source->get_id(next)
                << (source->get_is_reverse(next) ? "-" : "+") << endl;
#endif

                // Get the ID of where we're going.
                auto next_id = source->get_id(next);

                // do we ever return to the source node?
                cycled_to_source = cycled_to_source || next_id == id(pos);

                // record the edge
                observed_edges.insert(source->edge_handle(trav.handle, next));

                // make sure the node is in the graph
                if (!graph.count(next_id)) {
                    Node* node = g.add_node();
                    // Grab the sequence in its local forward orientation.
                    node->set_sequence(source->get_sequence(source->forward(next)));
                    node->set_id(next_id);
                    graph[next_id] = node;
                    id_trans[next_id] = next_id;
                    max_id = std::max(next_id, max_id);
                }

                // distance to the end of this node
                int64_t dist_thru = trav.dist + graph[next_id]->sequence().size();
                if (dist_thru < max_dist) {
                    // we can add more nodes along same path without going over the max length
                    queue.emplace(next, dist_thru);
#ifdef debug_vg_algorithms
                    cerr << "[extract_extending_graph] enqueuing " << source->get_id(next)
                        << (source->get_is_reverse(next) ? "-" : "+") << " at dist " << dist_thru << endl;
#endif
                }
            });
        }

        vector<pair<handle_t, handle_t>> src_edges;

        // add the edges to the graph
        for (const pair<handle_t, handle_t>& edge : observed_edges) {
            // This loop will never run unless we actually ran the search, so it is safe to use start_handle here.
            bool add_edge;
            if (source->forward(edge.first) == source->forward(start_handle) ||
                source->forward(edge.second) == source->forward(start_handle)) {
                // record the edges that touch the source in case we need to duplicate them
                src_edges.push_back(edge);
                // does the edge only touch the side of the source node that's not going to be cut?
                // That means it must touch only the right side of our starting handle.
                // We know it touches one side, so make sure it *doesn't* touch the left side.
                // Which means we need the reverse of our starting handle to not
                // be the left handle, and our handle to not be the right
                // handle.
                add_edge = !(edge.first == source->flip(start_handle) || edge.second == start_handle);
#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << (add_edge ? "" : "not ") << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " that touches source node" << endl;
#endif
            }
            else {
                // the edge doesn't touch the source node, so it will certainly survive the cut
                add_edge = true;
#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " that does not touch source node" << endl;
#endif
            }

            if (add_edge) {
                Edge* e = g.add_edge();
                e->set_from(source->get_id(edge.first));
                e->set_from_start(source->get_is_reverse(edge.first));
                e->set_to(source->get_id(edge.second));
                e->set_to_end(source->get_is_reverse(edge.second));
            }
        }

        if (cycled_to_source && preserve_cycles_on_src) {
            // we need to duplicate the source node to ensure that cycles on it will be preserved
            // after we cut it

            // choose an ID that hasn't been used yet
            id_t dup_id = max_id + 1;

            // duplicate the node
            Node* dup_node = g.add_node();
            dup_node->set_id(dup_id);
            dup_node->set_sequence(graph[id(pos)]->sequence());

            // record the ID translation
            id_trans[dup_id] = id(pos);

            for (const pair<handle_t, handle_t>& edge : src_edges) {
                Edge* e = g.add_edge();
                e->set_from_start(source->get_is_reverse(edge.first));
                e->set_to_end(source->get_is_reverse(edge.second));

                // Load the IDs for this edge
                auto from_id = source->get_id(edge.first);
                auto to_id = source->get_id(edge.second);

#ifdef debug_vg_algorithms
                cerr << "[extract_extending_graph] " << "adding edge " << source->get_id(edge.first) << (source->get_is_reverse(edge.first) ? "-" : "+") << " -> " << source->get_id(edge.second) << (source->get_is_reverse(edge.second) ? "-" : "+") << " to source node copy" << endl;
#endif

                if (from_id == id(pos) && to_id == id(pos)) {
                    // this edge is a self loop, always make a copy on the duplicated node
                    e->set_from(dup_id);
                    e->set_to(dup_id);

                    // if one of the ends of the edge is on the non-cut side of the source, also make a copy
                    // between the original and the duplicated node
                    if (from_id == id(pos) && source->get_is_reverse(edge.first) == (backward != is_rev(pos))) {
                        e = g.add_edge();
                        e->set_from(id(pos));
                        e->set_to(dup_id);
                        e->set_from_start(source->get_is_reverse(edge.first));
                        e->set_to_end(source->get_is_reverse(edge.second));
                    }
                    else if (to_id == id(pos) && source->get_is_reverse(edge.second) != (backward != is_rev(pos))) {
                        e = g.add_edge();
                        e->set_from(dup_id);
                        e->set_to(id(pos));
                        e->set_from_start(source->get_is_reverse(edge.first));
                        e->set_to_end(source->get_is_reverse(edge.second));
                    }
                }
                else if (from_id == id(pos)) {
                    // add a copy of the edge from the other node to the duplicated node
                    e->set_from(dup_id);
                    e->set_to(to_id);
                }
                else {
                    // add a copy of the edge from the other node to the duplicated node
                    e->set_from(from_id);
                    e->set_to(dup_id);
                }
            }
        }

        // cut the source node at the starting position
        if (is_rev(pos) && backward) {
            src_node->set_sequence(src_node->sequence().substr(src_node->sequence().size() - offset(pos), offset(pos)));
        }
        else if (is_rev(pos)) {
            src_node->set_sequence(src_node->sequence().substr(0, src_node->sequence().size() - offset(pos)));
        }
        else if (backward) {
            src_node->set_sequence(src_node->sequence().substr(0, offset(pos)));
        }
        else {
            src_node->set_sequence(src_node->sequence().substr(offset(pos), src_node->sequence().size() - offset(pos)));
        }

        return id_trans;
    }
}
}
<|endoftext|>