<commit_before>#include <iostream>
#include "Exceptions.h"
#include "UniversalInterface.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
void help_print()
{
	cout << endl << "--help                      - Помощь по утилите" << endl;
	cout << "--sid id1@Node1,id2,..,idXX@NodeXX  - Аналоговые датчики (AI,AO)" << endl;
	cout << endl;
	cout << "--min val       - Нижняя граница датчика. По умолчанию 0" << endl;
	cout << "--max val       - Верхняя граница датчика. По умолчанию 100 " << endl;
	cout << "--step val      - Шаг датчика. По умолчанию 1" << endl;
	cout << "--pause msec    - Пауза. По умолчанию 200 мсек" << endl << endl;
}
// -----------------------------------------------------------------------------
struct ExtInfo:
	public UniSetTypes::ParamSInfo
{
	UniversalIO::IOTypes iotype;
};
// -----------------------------------------------------------------------------
int main( int argc, char **argv )
{
	try
	{
		// help
		// -------------------------------------
		if( argc>1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
		{
			help_print();
			return 0;
		}
		// -------------------------------------

		uniset_init(argc, argv, "configure.xml" );
		UniversalInterface ui;

		string sid(conf->getArgParam("--sid"));
		if( sid.empty() )
		{
			cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
			return 1;
		}

		std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid,UniSetTypes::conf);

		if( lst.empty() )
		{
			cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
			return 1;
		}

		std::list<ExtInfo> l;
		for( std::list<UniSetTypes::ParamSInfo>::iterator it = lst.begin(); it!=lst.end(); ++it )
		{
			UniversalIO::IOTypes t = conf->getIOType( it->si.id );
			if( t != UniversalIO::AnalogInput && t != UniversalIO::AnalogOutput )
			{
				cerr << endl << "Неверный типа датчика '" << t << "' для id='" << it->fname << "'. Тип должен быть AI или AO." << endl << endl;
				return 1;
			}

			if( it->si.node == DefaultObjectId )
				it->si.node = conf->getLocalNode();

			ExtInfo i;
			i.si = it->si;
			i.iotype = t;
			l.push_back(i);
		}

		int amin = conf->getArgInt("--min", "0");
		int amax = conf->getArgInt("--max", "100");
		if( amin>amax )
		{
			int temp = amax;
			amax = amin;
			amin = temp;
		}

		int astep = conf->getArgInt("--step", "1");
		if( astep<=0 )
		{
			cerr << endl << "Ошибка, используйте --step val - любое положительное число" << endl << endl;
			return 1;
		}

		int amsec = conf->getArgInt("--pause", "200");
		if(amsec<=10)
		{
			cerr << endl << "Ошибка, используйте --pause val - любое положительное число > 10" << endl << endl;
			return 1;
		}

		cout << endl << "------------------------------" << endl;
		cout << " Вы ввели следующие параметры:" << endl;
		cout << "------------------------------" << endl;
		cout << "  sid = " << sid << endl;
		cout << "  min = " << amin << endl;
		cout << "  max = " << amax << endl;
		cout << "  step = " << astep << endl;
		cout << "  pause = " << amsec << endl;
		cout << "------------------------------" << endl << endl;

		int i = amin-astep, j = amax;

		while(1)
		{
		    if(i>=amax)
		    {
				j -= astep;
					if(j<amin)                 // Принудительная установка нижней границы датчика
						j = amin;
				cout << "\r" << " i = " << j <<"     "<< flush;

				for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it )
				{
				      try
				      {
						if( it->iotype == UniversalIO::AnalogInput )
						ui.saveValue(it->si, j, UniversalIO::AnalogInput, DefaultObjectId);
						else
							ui.setValue(it->si, j, DefaultObjectId);
				      }
				      catch( Exception& ex )
				      {
						  cerr << endl << "save id="<< it->fname << " " << ex << endl;
				  }
				}

				if(j<=amin)
				{
				    i = amin;
			    	j = amax;
				}
		    }
		    else
		    {
				i += astep;
					if(i>amax)                 // Принудительная установка верхней границы датчика
						i = amax;
			cout << "\r" << " i = " << i <<"     "<< flush;

				for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it )
				{
				      try
				      {
						if( it->iotype == UniversalIO::AnalogInput )
						ui.saveValue(it->si, i, UniversalIO::AnalogInput, DefaultObjectId);
						else
							ui.setValue(it->si, i, DefaultObjectId);
				      }
				      catch( Exception& ex )
				      {
						  cerr << endl << "save id="<< it->fname << " " << ex << endl;
				  }
				}
		    }
		    msleep(amsec);
		}

	}
	catch( Exception& ex )
	{
		cerr << endl << "(simitator): " << ex << endl;
		return 1;
	}
	catch( ... )
	{
		cerr << endl << "(simitator): catch..." << endl;
		return 1;
	}

	return 0;
}
// ------------------------------------------------------------------------------------------
<commit_msg>(simitator) - убрал лишнее в help<commit_after>#include <iostream>
#include "Exceptions.h"
#include "UniversalInterface.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
void help_print()
{
	cout << endl;
	cout << "--sid id1@Node1,id2,..,idXX@NodeXX  - Аналоговые датчики (AI,AO)" << endl;
	cout << endl;
	cout << "--min val       - Нижняя граница датчика. По умолчанию 0" << endl;
	cout << "--max val       - Верхняя граница датчика. По умолчанию 100 " << endl;
	cout << "--step val      - Шаг датчика. По умолчанию 1" << endl;
	cout << "--pause msec    - Пауза. По умолчанию 200 мсек" << endl << endl;
}
// -----------------------------------------------------------------------------
struct ExtInfo:
	public UniSetTypes::ParamSInfo
{
	UniversalIO::IOTypes iotype;
};
// -----------------------------------------------------------------------------
int main( int argc, char **argv )
{
	try
	{
		// help
		// -------------------------------------
		if( argc>1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
		{
			help_print();
			return 0;
		}
		// -------------------------------------

		uniset_init(argc, argv, "configure.xml" );
		UniversalInterface ui;

		string sid(conf->getArgParam("--sid"));
		if( sid.empty() )
		{
			cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
			return 1;
		}

		std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid,UniSetTypes::conf);

		if( lst.empty() )
		{
			cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
			return 1;
		}

		std::list<ExtInfo> l;
		for( std::list<UniSetTypes::ParamSInfo>::iterator it = lst.begin(); it!=lst.end(); ++it )
		{
			UniversalIO::IOTypes t = conf->getIOType( it->si.id );
			if( t != UniversalIO::AnalogInput && t != UniversalIO::AnalogOutput )
			{
				cerr << endl << "Неверный типа датчика '" << t << "' для id='" << it->fname << "'. Тип должен быть AI или AO." << endl << endl;
				return 1;
			}

			if( it->si.node == DefaultObjectId )
				it->si.node = conf->getLocalNode();

			ExtInfo i;
			i.si = it->si;
			i.iotype = t;
			l.push_back(i);
		}

		int amin = conf->getArgInt("--min", "0");
		int amax = conf->getArgInt("--max", "100");
		if( amin>amax )
		{
			int temp = amax;
			amax = amin;
			amin = temp;
		}

		int astep = conf->getArgInt("--step", "1");
		if( astep<=0 )
		{
			cerr << endl << "Ошибка, используйте --step val - любое положительное число" << endl << endl;
			return 1;
		}

		int amsec = conf->getArgInt("--pause", "200");
		if(amsec<=10)
		{
			cerr << endl << "Ошибка, используйте --pause val - любое положительное число > 10" << endl << endl;
			return 1;
		}

		cout << endl << "------------------------------" << endl;
		cout << " Вы ввели следующие параметры:" << endl;
		cout << "------------------------------" << endl;
		cout << "  sid = " << sid << endl;
		cout << "  min = " << amin << endl;
		cout << "  max = " << amax << endl;
		cout << "  step = " << astep << endl;
		cout << "  pause = " << amsec << endl;
		cout << "------------------------------" << endl << endl;

		int i = amin-astep, j = amax;

		while(1)
		{
		    if(i>=amax)
		    {
				j -= astep;
					if(j<amin)                 // Принудительная установка нижней границы датчика
						j = amin;
				cout << "\r" << " i = " << j <<"     "<< flush;

				for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it )
				{
				      try
				      {
						if( it->iotype == UniversalIO::AnalogInput )
						ui.saveValue(it->si, j, UniversalIO::AnalogInput, DefaultObjectId);
						else
							ui.setValue(it->si, j, DefaultObjectId);
				      }
				      catch( Exception& ex )
				      {
						  cerr << endl << "save id="<< it->fname << " " << ex << endl;
				  }
				}

				if(j<=amin)
				{
				    i = amin;
			    	j = amax;
				}
		    }
		    else
		    {
				i += astep;
					if(i>amax)                 // Принудительная установка верхней границы датчика
						i = amax;
			cout << "\r" << " i = " << i <<"     "<< flush;

				for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it )
				{
				      try
				      {
						if( it->iotype == UniversalIO::AnalogInput )
						ui.saveValue(it->si, i, UniversalIO::AnalogInput, DefaultObjectId);
						else
							ui.setValue(it->si, i, DefaultObjectId);
				      }
				      catch( Exception& ex )
				      {
						  cerr << endl << "save id="<< it->fname << " " << ex << endl;
				  }
				}
		    }
		    msleep(amsec);
		}

	}
	catch( Exception& ex )
	{
		cerr << endl << "(simitator): " << ex << endl;
		return 1;
	}
	catch( ... )
	{
		cerr << endl << "(simitator): catch..." << endl;
		return 1;
	}

	return 0;
}
// ------------------------------------------------------------------------------------------
<|endoftext|>


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

#include "http_client_base.h"
#include "file_util.h"

#include <shlwapi.h>

bool WebmLive::FileUtil::file_exists(std::wstring path)
{
  return PathFileExists(path.c_str()) == TRUE;
}

uint64 WebmLive::FileUtil::get_file_size(std::wstring path)
{
  uint64 file_size = 0;
  WIN32_FILE_ATTRIBUTE_DATA attr = {0};
  if (GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &attr)) {
    file_size = (attr.nFileSizeHigh << 4) + attr.nFileSizeLow;
  }
  return file_size;
}
<commit_msg>file_util: add stat based implementation of get_file_size<commit_after>// Copyright (c) 2011 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include "http_client_base.h"
#include "file_util.h"

#include <sys/types.h>
#include <sys/stat.h>

#include <shlwapi.h>

bool WebmLive::FileUtil::file_exists(std::wstring path)
{
  return PathFileExists(path.c_str()) == TRUE;
}

uint64 WebmLive::FileUtil::get_file_size(std::wstring path)
{
  uint64 file_size = 0;
#if 0
  WIN32_FILE_ATTRIBUTE_DATA attr = {0};
  if (GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &attr)) {
    file_size = (attr.nFileSizeHigh << 4) + attr.nFileSizeLow;
  }
#else
  struct _stat statbuf = {0};
  int result = _wstat(path.c_str(), &statbuf);
  if (result == NO_ERROR) {
    file_size = statbuf.st_size;
  }
#endif
  return file_size;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2021 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS 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
 * FOUNDATION OR 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.
 */

#ifndef BENG_PROXY_STICKY_HASH_HXX
#define BENG_PROXY_STICKY_HASH_HXX

#include <stdint.h>

/**
 * A type which can store a hash for choosing a cluster member.  Zero
 * is a special value for "sticky disabled"
 */
typedef uint32_t sticky_hash_t;

#endif
<commit_msg>cluster/StickyHash: use C++ header<commit_after>/*
 * Copyright 2007-2021 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS 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
 * FOUNDATION OR 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.
 */

#pragma once

#include <cstdint>

/**
 * A type which can store a hash for choosing a cluster member.  Zero
 * is a special value for "sticky disabled"
 */
typedef uint32_t sticky_hash_t;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: plctrl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2008-01-14 14:51:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#ifndef _COM_SUN_STAR_AWT_XADJUSTMENTLISTENER_HPP_
#include <com/sun/star/awt/XAdjustmentListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XACTIONLISTENER_HPP_
#include <com/sun/star/awt/XActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTEXTLISTENER_HPP_
#include <com/sun/star/awt/XTextListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XSPINLISTENER_HPP_
#include <com/sun/star/awt/XSpinListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XVCLCONTAINERLISTENER_HPP_
#include <com/sun/star/awt/XVclContainerListener.hpp>
#endif

#include <plugin/plctrl.hxx>
#include <vcl/syschild.hxx>
#include <toolkit/helper/vclunohelper.hxx>

//--------------------------------------------------------------------------------------------------
PluginControl_Impl::PluginControl_Impl() :
    _pMultiplexer( NULL )
    , _nX( 0 )
    , _nY( 0 )
    , _nWidth( 100 )
    , _nHeight( 100 )
    , _nFlags( WINDOW_POSSIZE_ALL )
    , _bVisible( sal_False )
    , _bInDesignMode( sal_False )
    , _bEnable( sal_True )
{
}

//--------------------------------------------------------------------------------------------------
PluginControl_Impl::~PluginControl_Impl()
{
}

MRCListenerMultiplexerHelper* PluginControl_Impl::getMultiplexer()
{
    if( ! _pMultiplexer )
        _pMultiplexer = new MRCListenerMultiplexerHelper( this, _xPeerWindow );
    return _pMultiplexer;
}
//==================================================================================================

void PluginControl_Impl::addEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l )
    throw( RuntimeException )
{
    _aDisposeListeners.push_back( l );
}

//---- ::com::sun::star::lang::XComponent ----------------------------------------------------------------------------------
void PluginControl_Impl::removeEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l )
    throw( RuntimeException )
{
    _aDisposeListeners.remove( l );
}

//---- ::com::sun::star::lang::XComponent ----------------------------------------------------------------------------------
void PluginControl_Impl::dispose(void)
    throw( RuntimeException )
{
    // send disposing events
    ::com::sun::star::lang::EventObject aEvt;
    if( getMultiplexer() )
        getMultiplexer()->disposeAndClear();

    // release context
    _xContext = Reference< XInterface > ();
    releasePeer();
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setPosSize( sal_Int32 nX_, sal_Int32 nY_, sal_Int32 nWidth_, sal_Int32 nHeight_, sal_Int16 nFlags )
    throw( RuntimeException )
{
    _nX         = nX_ >=0 ? nX_ : 0;
    _nY         = nY_ >=0 ? nY_ : 0;
    _nWidth     = nWidth_ >=0 ? nWidth_ : 0;
    _nHeight    = nHeight_ >=0 ? nHeight_ : 0;
    _nFlags     = nFlags;

    if (_xPeerWindow.is())
        _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, nFlags );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
::com::sun::star::awt::Rectangle PluginControl_Impl::getPosSize(void)
    throw( RuntimeException )
{
    return _xPeerWindow->getPosSize();
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setVisible( sal_Bool bVisible )
    throw( RuntimeException )
{
    _bVisible = bVisible;
    if (_xPeerWindow.is())
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setEnable( sal_Bool bEnable )
    throw( RuntimeException )
{
    _bEnable = bEnable;
    if (_xPeerWindow.is())
        _xPeerWindow->setEnable( _bEnable );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setFocus(void) throw( RuntimeException )
{
    if (_xPeerWindow.is())
        _xPeerWindow->setFocus();
}

//--------------------------------------------------------------------------------------------------
void PluginControl_Impl::releasePeer()
{
    if (_xPeer.is())
    {
        _xParentWindow->removeFocusListener( this );
        _xPeerWindow->dispose();
        _pSysChild      = NULL;
        _xPeerWindow    = Reference< ::com::sun::star::awt::XWindow > ();
        _xPeer          = Reference< ::com::sun::star::awt::XWindowPeer > ();
        getMultiplexer()->setPeer( Reference< ::com::sun::star::awt::XWindow > () );
    }
}

//---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------
void PluginControl_Impl::createPeer( const Reference< ::com::sun::star::awt::XToolkit > & /*xToolkit*/, const Reference< ::com::sun::star::awt::XWindowPeer >  & xParentPeer )
    throw( RuntimeException )
{
    if (_xPeer.is())
    {
        DBG_ERROR( "### Peer is already set!" );
        return;
    }

    _xParentPeer = xParentPeer;
    _xParentWindow = Reference< ::com::sun::star::awt::XWindow > ( xParentPeer, UNO_QUERY );
    DBG_ASSERT( _xParentWindow.is(), "### no parent peer window!" );

    Window* pImpl = VCLUnoHelper::GetWindow( xParentPeer );
    if (pImpl)
    {
        _pSysChild = new SystemChildWindow( pImpl, WB_CLIPCHILDREN );
        if (pImpl->HasFocus())
            _pSysChild->GrabFocus();

        // get peer
        _xPeer          = Reference< ::com::sun::star::awt::XWindowPeer > ( _pSysChild->GetComponentInterface() );
        _xPeerWindow    = Reference< ::com::sun::star::awt::XWindow > ( _xPeer, UNO_QUERY );
        // !_BOTH_ MUST BE VALID!
        DBG_ASSERT( (_xPeer.is() && _xPeerWindow.is()), "### no peer!" );

        _xParentWindow->addFocusListener( this );
        _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, _nFlags );
        _xPeerWindow->setEnable( _bEnable );
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
    }
    else
    {
        DBG_ERROR( "### cannot get implementation of parent peer!" );
    }

    getMultiplexer()->setPeer( _xPeerWindow );
}

//---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------
void PluginControl_Impl::setDesignMode( sal_Bool bOn )
    throw( RuntimeException )
{
    _bInDesignMode = bOn;
    if (_xPeerWindow.is())
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addPaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removePaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l );
}

//---- ::com::sun::star::awt::XView ---------------------------------------------------------------------------------------
void PluginControl_Impl::draw( sal_Int32 /*x*/, sal_Int32 /*y*/ )
    throw( RuntimeException )
{
    // has to be done by further implementation of control
}

//---- ::com::sun::star::awt::XView ---------------------------------------------------------------------------------------
void PluginControl_Impl::setZoom( float /*ZoomX*/, float /*ZoomY*/ )
    throw( RuntimeException )
{
    // has to be done by further implementation of control
}

//---- ::com::sun::star::lang::XEventListener ------------------------------------------------------------------------------
void PluginControl_Impl::disposing( const ::com::sun::star::lang::EventObject & /*rSource*/ )
    throw( RuntimeException )
{
}
//---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------
void PluginControl_Impl::focusGained( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ )
    throw( RuntimeException )
{
    if (_xPeerWindow.is())
        _xPeerWindow->setFocus();
}
//---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------
void PluginControl_Impl::focusLost( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ )
    throw( RuntimeException )
{
}

<commit_msg>INTEGRATION: CWS changefileheader (1.6.48); FILE MERGED 2008/04/01 12:29:46 thb 1.6.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:35 rt 1.6.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: plctrl.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include <com/sun/star/awt/XAdjustmentListener.hpp>
#include <com/sun/star/awt/XActionListener.hpp>
#include <com/sun/star/awt/XTextListener.hpp>
#include <com/sun/star/awt/XSpinListener.hpp>
#include <com/sun/star/awt/XItemListener.hpp>
#include <com/sun/star/awt/XVclContainerListener.hpp>

#include <plugin/plctrl.hxx>
#include <vcl/syschild.hxx>
#include <toolkit/helper/vclunohelper.hxx>

//--------------------------------------------------------------------------------------------------
PluginControl_Impl::PluginControl_Impl() :
    _pMultiplexer( NULL )
    , _nX( 0 )
    , _nY( 0 )
    , _nWidth( 100 )
    , _nHeight( 100 )
    , _nFlags( WINDOW_POSSIZE_ALL )
    , _bVisible( sal_False )
    , _bInDesignMode( sal_False )
    , _bEnable( sal_True )
{
}

//--------------------------------------------------------------------------------------------------
PluginControl_Impl::~PluginControl_Impl()
{
}

MRCListenerMultiplexerHelper* PluginControl_Impl::getMultiplexer()
{
    if( ! _pMultiplexer )
        _pMultiplexer = new MRCListenerMultiplexerHelper( this, _xPeerWindow );
    return _pMultiplexer;
}
//==================================================================================================

void PluginControl_Impl::addEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l )
    throw( RuntimeException )
{
    _aDisposeListeners.push_back( l );
}

//---- ::com::sun::star::lang::XComponent ----------------------------------------------------------------------------------
void PluginControl_Impl::removeEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l )
    throw( RuntimeException )
{
    _aDisposeListeners.remove( l );
}

//---- ::com::sun::star::lang::XComponent ----------------------------------------------------------------------------------
void PluginControl_Impl::dispose(void)
    throw( RuntimeException )
{
    // send disposing events
    ::com::sun::star::lang::EventObject aEvt;
    if( getMultiplexer() )
        getMultiplexer()->disposeAndClear();

    // release context
    _xContext = Reference< XInterface > ();
    releasePeer();
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setPosSize( sal_Int32 nX_, sal_Int32 nY_, sal_Int32 nWidth_, sal_Int32 nHeight_, sal_Int16 nFlags )
    throw( RuntimeException )
{
    _nX         = nX_ >=0 ? nX_ : 0;
    _nY         = nY_ >=0 ? nY_ : 0;
    _nWidth     = nWidth_ >=0 ? nWidth_ : 0;
    _nHeight    = nHeight_ >=0 ? nHeight_ : 0;
    _nFlags     = nFlags;

    if (_xPeerWindow.is())
        _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, nFlags );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
::com::sun::star::awt::Rectangle PluginControl_Impl::getPosSize(void)
    throw( RuntimeException )
{
    return _xPeerWindow->getPosSize();
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setVisible( sal_Bool bVisible )
    throw( RuntimeException )
{
    _bVisible = bVisible;
    if (_xPeerWindow.is())
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setEnable( sal_Bool bEnable )
    throw( RuntimeException )
{
    _bEnable = bEnable;
    if (_xPeerWindow.is())
        _xPeerWindow->setEnable( _bEnable );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::setFocus(void) throw( RuntimeException )
{
    if (_xPeerWindow.is())
        _xPeerWindow->setFocus();
}

//--------------------------------------------------------------------------------------------------
void PluginControl_Impl::releasePeer()
{
    if (_xPeer.is())
    {
        _xParentWindow->removeFocusListener( this );
        _xPeerWindow->dispose();
        _pSysChild      = NULL;
        _xPeerWindow    = Reference< ::com::sun::star::awt::XWindow > ();
        _xPeer          = Reference< ::com::sun::star::awt::XWindowPeer > ();
        getMultiplexer()->setPeer( Reference< ::com::sun::star::awt::XWindow > () );
    }
}

//---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------
void PluginControl_Impl::createPeer( const Reference< ::com::sun::star::awt::XToolkit > & /*xToolkit*/, const Reference< ::com::sun::star::awt::XWindowPeer >  & xParentPeer )
    throw( RuntimeException )
{
    if (_xPeer.is())
    {
        DBG_ERROR( "### Peer is already set!" );
        return;
    }

    _xParentPeer = xParentPeer;
    _xParentWindow = Reference< ::com::sun::star::awt::XWindow > ( xParentPeer, UNO_QUERY );
    DBG_ASSERT( _xParentWindow.is(), "### no parent peer window!" );

    Window* pImpl = VCLUnoHelper::GetWindow( xParentPeer );
    if (pImpl)
    {
        _pSysChild = new SystemChildWindow( pImpl, WB_CLIPCHILDREN );
        if (pImpl->HasFocus())
            _pSysChild->GrabFocus();

        // get peer
        _xPeer          = Reference< ::com::sun::star::awt::XWindowPeer > ( _pSysChild->GetComponentInterface() );
        _xPeerWindow    = Reference< ::com::sun::star::awt::XWindow > ( _xPeer, UNO_QUERY );
        // !_BOTH_ MUST BE VALID!
        DBG_ASSERT( (_xPeer.is() && _xPeerWindow.is()), "### no peer!" );

        _xParentWindow->addFocusListener( this );
        _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, _nFlags );
        _xPeerWindow->setEnable( _bEnable );
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
    }
    else
    {
        DBG_ERROR( "### cannot get implementation of parent peer!" );
    }

    getMultiplexer()->setPeer( _xPeerWindow );
}

//---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------
void PluginControl_Impl::setDesignMode( sal_Bool bOn )
    throw( RuntimeException )
{
    _bInDesignMode = bOn;
    if (_xPeerWindow.is())
        _xPeerWindow->setVisible( _bVisible && !_bInDesignMode );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addPaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removePaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::addMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l );
}

//---- ::com::sun::star::awt::XWindow -------------------------------------------------------------------------------------
void PluginControl_Impl::removeMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l )
    throw( RuntimeException )
{
    getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l );
}

//---- ::com::sun::star::awt::XView ---------------------------------------------------------------------------------------
void PluginControl_Impl::draw( sal_Int32 /*x*/, sal_Int32 /*y*/ )
    throw( RuntimeException )
{
    // has to be done by further implementation of control
}

//---- ::com::sun::star::awt::XView ---------------------------------------------------------------------------------------
void PluginControl_Impl::setZoom( float /*ZoomX*/, float /*ZoomY*/ )
    throw( RuntimeException )
{
    // has to be done by further implementation of control
}

//---- ::com::sun::star::lang::XEventListener ------------------------------------------------------------------------------
void PluginControl_Impl::disposing( const ::com::sun::star::lang::EventObject & /*rSource*/ )
    throw( RuntimeException )
{
}
//---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------
void PluginControl_Impl::focusGained( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ )
    throw( RuntimeException )
{
    if (_xPeerWindow.is())
        _xPeerWindow->setFocus();
}
//---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------
void PluginControl_Impl::focusLost( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ )
    throw( RuntimeException )
{
}

<|endoftext|>


<commit_before>/****************************************************************************
*
* NAME: smbPitchShift.cpp
* VERSION: 1.2
* HOME URL: http://blogs.zynaptiq.com/bernsee
* KNOWN BUGS: none
*
* SYNOPSIS: Routine for doing pitch shifting while maintaining
* duration using the Short Time Fourier Transform.
*
* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
* the pitch. numSampsToProcess tells the routine how many samples in indata[0...
* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
* data in-place). fftFrameSize defines the FFT frame size used for the
* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
* MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT
* oversampling factor which also determines the overlap between adjacent STFT
* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
* recommended for best quality. sampleRate takes the sample rate for the signal
* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
* indata[] should be in the range [-1.0, 1.0), which is also the output range
* for the data, make sure you scale the data accordingly (for 16bit signed integers
* you would have to divide (and multiply) by 32768).
*
* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*
* 						The Wide Open License (WOL)
*
* Permission to use, copy, modify, distribute and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice and this license appear in all source copies.
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
* ANY KIND. See http://www.dspguru.com/wol.htm for more information.
*
*****************************************************************************/

#ifndef SMBPITCHSHIFT_HPP
#define SMBPITCHSHIFT_HPP

#include <algorithm>
#include <cmath>
#include <cstring>

namespace smb
{
    static const float PI = 3.14159265358979323846F;
    static const unsigned long MAX_FRAME_LENGTH = 8192;

    // don't use std::complex, because its arithmetic operations are slow
    template<class T>
    struct Complex
    {
        T real;
        T imag;
    };

    /*
        FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
        Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
        time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
        and returns the cosine and sine parts in an interleaved manner, ie.
        fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
        must be a power of 2. It expects a complex input signal (see footnote 2),
        ie. when working with 'common' audio signals our input signal has to be
        passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
        of the frequencies of interest is in fftBuffer[0...fftFrameSize].
    */
    static void fft(Complex<float>* fftBuffer, unsigned long fftFrameSize, long sign)
    {
        for (unsigned long i = 1; i < fftFrameSize - 1; i++)
        {
            unsigned long j = 0;

            for (unsigned long bitm = 1; bitm < fftFrameSize; bitm <<= 1)
            {
                if (i & bitm) j++;
                j <<= 1;
            }
            j >>= 1;

            if (i < j)
                std::swap(fftBuffer[i], fftBuffer[j]);
        }

        unsigned long step = 2;
        for (unsigned long i = 1; i < fftFrameSize; i <<= 1, step <<= 1)
        {
            unsigned long step2 = step >> 1;
            float arg = PI / step2;

            Complex<float> w{std::cos(arg), std::sin(arg) * sign};
            Complex<float> u{1.0, 0.0};
            for (unsigned long j = 0; j < step2; j++)
            {
                for (unsigned long k = j; k < fftFrameSize; k += step)
                {
                    // temp = fftBuffer[k + step2] * u
                    Complex<float> temp;
                    temp.real = fftBuffer[k + step2].real * u.real - fftBuffer[k + step2].imag * u.imag;
                    temp.imag = fftBuffer[k + step2].real * u.imag + fftBuffer[k + step2].imag * u.real;

                    // FFTBuffer[k + step2] = FFTBuffer[k] - temp
                    fftBuffer[k + step2].real = fftBuffer[k].real - temp.real;
                    fftBuffer[k + step2].imag = fftBuffer[k].imag - temp.imag;

                    // FFTBuffer[k] += temp
                    fftBuffer[k].real += temp.real;
                    fftBuffer[k].imag += temp.imag;
                }

                // u *= w;
                float tempReal = u.real;
                u.real = tempReal * w.real - u.imag * w.imag;
                u.imag = tempReal * w.imag + u.imag * w.real;

            }
        }
    }

    class PitchShift
    {
    public:
        PitchShift()
        {
            std::fill(std::begin(inFIFO), std::end(inFIFO), 0.0F);
            std::fill(std::begin(outFIFO), std::end(outFIFO), 0.0F);
            std::fill(std::begin(fftWorksp), std::end(fftWorksp), Complex<float>{0.0F, 0.0F});
            std::fill(std::begin(lastPhase), std::end(lastPhase), 0.0F);
            std::fill(std::begin(sumPhase), std::end(sumPhase), 0.0F);
            std::fill(std::begin(outputAccum), std::end(outputAccum), 0.0F);
            std::fill(std::begin(anaFreq), std::end(anaFreq), 0.0F);
            std::fill(std::begin(anaMagn), std::end(anaMagn), 0.0F);
        }

        /*
            Routine process(). See top of file for explanation
            Purpose: doing pitch shifting while maintaining duration using the Short
            Time Fourier Transform.
            Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
        */
        void process(float pitchShift, unsigned long numSampsToProcess, unsigned long fftFrameSize, unsigned long osamp, float sampleRate, float* indata, float* outdata)
        {
            // set up some handy variables
            unsigned long fftFrameSize2 = fftFrameSize / 2;
            unsigned long stepSize = fftFrameSize / osamp;
            float freqPerBin = sampleRate / static_cast<float>(fftFrameSize);
            float expct = 2.0F * PI * static_cast<float>(stepSize) / static_cast<float>(fftFrameSize);
            unsigned long inFifoLatency = fftFrameSize - stepSize;
            if (rover == 0) rover = inFifoLatency;

            // main processing loop
            for (unsigned long i = 0; i < numSampsToProcess; i++)
            {
                // As long as we have not yet collected enough data just read in
                inFIFO[rover] = indata[i];
                outdata[i] = outFIFO[rover - inFifoLatency];
                rover++;

                // now we have enough data for processing
                if (rover >= fftFrameSize)
                {
                    rover = inFifoLatency;

                    // do windowing and re,im interleave
                    for (unsigned long k = 0; k < fftFrameSize; k++)
                    {
                        float window = -0.5F * std::cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
                        fftWorksp[k].real = inFIFO[k] * window;
                        fftWorksp[k].imag = 0.0F;
                    }

                    // ***************** ANALYSIS *******************
                    // do transform
                    fft(fftWorksp, fftFrameSize, -1);

                    // this is the analysis step
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        // de-interlace FFT buffer
                        float real = fftWorksp[k].real;
                        float imag = fftWorksp[k].imag;

                        // compute magnitude and phase
                        float magn = 2.0F * sqrtf(real * real + imag * imag);

                        float phase;
                        float signx = (imag > 0.0F) ? 1.0F : -1.0F;
                        if (imag == 0.0F) phase = 0.0F;
                        else if (real == 0.0F) phase = signx * PI / 2.0F;
                        else phase = std::atan2(imag, real);

                        // compute phase difference
                        float tmp = phase - lastPhase[k];
                        lastPhase[k] = phase;

                        // subtract expected phase difference
                        tmp -= static_cast<float>(k) * expct;

                        // map delta phase into +/- Pi interval
                        long qpd = static_cast<long>(tmp / PI);
                        if (qpd >= 0) qpd += qpd & 1;
                        else qpd -= qpd & 1;
                        tmp -= PI * static_cast<float>(qpd);

                        // get deviation from bin frequency from the +/- Pi interval
                        tmp = osamp * tmp / (2.0F * PI);

                        // compute the k-th partials' true frequency
                        tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;

                        // store magnitude and true frequency in analysis arrays
                        anaMagn[k] = magn;
                        anaFreq[k] = tmp;
                    }

                    // ***************** PROCESSING *******************
                    // this does the actual pitch shifting
                    memset(synMagn, 0, fftFrameSize * sizeof(float));
                    memset(synFreq, 0, fftFrameSize * sizeof(float));
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        unsigned long index = static_cast<unsigned long>(k * pitchShift);
                        if (index <= fftFrameSize2)
                        {
                            synMagn[index] += anaMagn[k];
                            synFreq[index] = anaFreq[k] * pitchShift;
                        }
                    }

                    // ***************** SYNTHESIS *******************
                    // this is the synthesis step
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        // get magnitude and true frequency from synthesis arrays
                        float magn = synMagn[k];
                        float tmp = synFreq[k];

                        // subtract bin mid frequency
                        tmp -= static_cast<float>(k) * freqPerBin;

                        // get bin deviation from freq deviation
                        tmp /= freqPerBin;

                        // take osamp into account
                        tmp = 2.0F * PI * tmp / osamp;

                        // add the overlap phase advance back in
                        tmp += static_cast<float>(k) * expct;

                        // accumulate delta phase to get bin phase
                        sumPhase[k] += tmp;
                        float phase = sumPhase[k];

                        // get real and imag part and re-interleave
                        fftWorksp[k].real = magn * std::cos(phase);
                        fftWorksp[k].imag = magn * std::sin(phase);
                    }

                    // zero negative frequencies
                    for (unsigned long k = fftFrameSize + 1; k < fftFrameSize; k++) fftWorksp[k] = {0.0F, 0.0F};

                    // do inverse transform
                    fft(fftWorksp, fftFrameSize, 1);

                    // do windowing and add to output accumulator
                    for (unsigned long k = 0; k < fftFrameSize; k++)
                    {
                        float window = -0.5F * cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
                        outputAccum[k] += 2.0F * window * fftWorksp[k].real / (fftFrameSize2 * osamp);
                    }
                    for (unsigned long k = 0; k < stepSize; k++) outFIFO[k] = outputAccum[k];

                    // shift accumulator
                    memmove(outputAccum, outputAccum + stepSize, fftFrameSize * sizeof(float));

                    // move input FIFO
                    for (unsigned long k = 0; k < inFifoLatency; k++) inFIFO[k] = inFIFO[k + stepSize];
                }
            }
        }

    private:
        float inFIFO[MAX_FRAME_LENGTH];
        float outFIFO[MAX_FRAME_LENGTH];
        Complex<float> fftWorksp[MAX_FRAME_LENGTH];
        float lastPhase[MAX_FRAME_LENGTH / 2 + 1];
        float sumPhase[MAX_FRAME_LENGTH / 2 + 1];
        float outputAccum[2 * MAX_FRAME_LENGTH];
        float anaFreq[MAX_FRAME_LENGTH];
        float anaMagn[MAX_FRAME_LENGTH];
        float synFreq[MAX_FRAME_LENGTH];
        float synMagn[MAX_FRAME_LENGTH];
        unsigned long rover = 0;
    };
}

#endif
<commit_msg>Use std::fill instead of memset<commit_after>/****************************************************************************
*
* NAME: smbPitchShift.cpp
* VERSION: 1.2
* HOME URL: http://blogs.zynaptiq.com/bernsee
* KNOWN BUGS: none
*
* SYNOPSIS: Routine for doing pitch shifting while maintaining
* duration using the Short Time Fourier Transform.
*
* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
* the pitch. numSampsToProcess tells the routine how many samples in indata[0...
* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
* data in-place). fftFrameSize defines the FFT frame size used for the
* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
* MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT
* oversampling factor which also determines the overlap between adjacent STFT
* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
* recommended for best quality. sampleRate takes the sample rate for the signal
* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
* indata[] should be in the range [-1.0, 1.0), which is also the output range
* for the data, make sure you scale the data accordingly (for 16bit signed integers
* you would have to divide (and multiply) by 32768).
*
* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*
* 						The Wide Open License (WOL)
*
* Permission to use, copy, modify, distribute and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice and this license appear in all source copies.
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
* ANY KIND. See http://www.dspguru.com/wol.htm for more information.
*
*****************************************************************************/

#ifndef SMBPITCHSHIFT_HPP
#define SMBPITCHSHIFT_HPP

#include <algorithm>
#include <cmath>
#include <cstring>

namespace smb
{
    static const float PI = 3.14159265358979323846F;
    static const unsigned long MAX_FRAME_LENGTH = 8192;

    // don't use std::complex, because its arithmetic operations are slow
    template<class T>
    struct Complex
    {
        T real;
        T imag;
    };

    /*
        FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
        Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
        time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
        and returns the cosine and sine parts in an interleaved manner, ie.
        fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
        must be a power of 2. It expects a complex input signal (see footnote 2),
        ie. when working with 'common' audio signals our input signal has to be
        passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
        of the frequencies of interest is in fftBuffer[0...fftFrameSize].
    */
    static void fft(Complex<float>* fftBuffer, unsigned long fftFrameSize, long sign)
    {
        for (unsigned long i = 1; i < fftFrameSize - 1; i++)
        {
            unsigned long j = 0;

            for (unsigned long bitm = 1; bitm < fftFrameSize; bitm <<= 1)
            {
                if (i & bitm) j++;
                j <<= 1;
            }
            j >>= 1;

            if (i < j)
                std::swap(fftBuffer[i], fftBuffer[j]);
        }

        unsigned long step = 2;
        for (unsigned long i = 1; i < fftFrameSize; i <<= 1, step <<= 1)
        {
            unsigned long step2 = step >> 1;
            float arg = PI / step2;

            Complex<float> w{std::cos(arg), std::sin(arg) * sign};
            Complex<float> u{1.0, 0.0};
            for (unsigned long j = 0; j < step2; j++)
            {
                for (unsigned long k = j; k < fftFrameSize; k += step)
                {
                    // temp = fftBuffer[k + step2] * u
                    Complex<float> temp;
                    temp.real = fftBuffer[k + step2].real * u.real - fftBuffer[k + step2].imag * u.imag;
                    temp.imag = fftBuffer[k + step2].real * u.imag + fftBuffer[k + step2].imag * u.real;

                    // FFTBuffer[k + step2] = FFTBuffer[k] - temp
                    fftBuffer[k + step2].real = fftBuffer[k].real - temp.real;
                    fftBuffer[k + step2].imag = fftBuffer[k].imag - temp.imag;

                    // FFTBuffer[k] += temp
                    fftBuffer[k].real += temp.real;
                    fftBuffer[k].imag += temp.imag;
                }

                // u *= w;
                float tempReal = u.real;
                u.real = tempReal * w.real - u.imag * w.imag;
                u.imag = tempReal * w.imag + u.imag * w.real;

            }
        }
    }

    class PitchShift
    {
    public:
        PitchShift()
        {
            std::fill(std::begin(inFIFO), std::end(inFIFO), 0.0F);
            std::fill(std::begin(outFIFO), std::end(outFIFO), 0.0F);
            std::fill(std::begin(fftWorksp), std::end(fftWorksp), Complex<float>{0.0F, 0.0F});
            std::fill(std::begin(lastPhase), std::end(lastPhase), 0.0F);
            std::fill(std::begin(sumPhase), std::end(sumPhase), 0.0F);
            std::fill(std::begin(outputAccum), std::end(outputAccum), 0.0F);
            std::fill(std::begin(anaFreq), std::end(anaFreq), 0.0F);
            std::fill(std::begin(anaMagn), std::end(anaMagn), 0.0F);
        }

        /*
            Routine process(). See top of file for explanation
            Purpose: doing pitch shifting while maintaining duration using the Short
            Time Fourier Transform.
            Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
        */
        void process(float pitchShift, unsigned long numSampsToProcess, unsigned long fftFrameSize, unsigned long osamp, float sampleRate, float* indata, float* outdata)
        {
            // set up some handy variables
            unsigned long fftFrameSize2 = fftFrameSize / 2;
            unsigned long stepSize = fftFrameSize / osamp;
            float freqPerBin = sampleRate / static_cast<float>(fftFrameSize);
            float expct = 2.0F * PI * static_cast<float>(stepSize) / static_cast<float>(fftFrameSize);
            unsigned long inFifoLatency = fftFrameSize - stepSize;
            if (rover == 0) rover = inFifoLatency;

            // main processing loop
            for (unsigned long i = 0; i < numSampsToProcess; i++)
            {
                // As long as we have not yet collected enough data just read in
                inFIFO[rover] = indata[i];
                outdata[i] = outFIFO[rover - inFifoLatency];
                rover++;

                // now we have enough data for processing
                if (rover >= fftFrameSize)
                {
                    rover = inFifoLatency;

                    // do windowing and re,im interleave
                    for (unsigned long k = 0; k < fftFrameSize; k++)
                    {
                        float window = -0.5F * std::cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
                        fftWorksp[k].real = inFIFO[k] * window;
                        fftWorksp[k].imag = 0.0F;
                    }

                    // ***************** ANALYSIS *******************
                    // do transform
                    fft(fftWorksp, fftFrameSize, -1);

                    // this is the analysis step
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        // de-interlace FFT buffer
                        float real = fftWorksp[k].real;
                        float imag = fftWorksp[k].imag;

                        // compute magnitude and phase
                        float magn = 2.0F * sqrtf(real * real + imag * imag);

                        float phase;
                        float signx = (imag > 0.0F) ? 1.0F : -1.0F;
                        if (imag == 0.0F) phase = 0.0F;
                        else if (real == 0.0F) phase = signx * PI / 2.0F;
                        else phase = std::atan2(imag, real);

                        // compute phase difference
                        float tmp = phase - lastPhase[k];
                        lastPhase[k] = phase;

                        // subtract expected phase difference
                        tmp -= static_cast<float>(k) * expct;

                        // map delta phase into +/- Pi interval
                        long qpd = static_cast<long>(tmp / PI);
                        if (qpd >= 0) qpd += qpd & 1;
                        else qpd -= qpd & 1;
                        tmp -= PI * static_cast<float>(qpd);

                        // get deviation from bin frequency from the +/- Pi interval
                        tmp = osamp * tmp / (2.0F * PI);

                        // compute the k-th partials' true frequency
                        tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;

                        // store magnitude and true frequency in analysis arrays
                        anaMagn[k] = magn;
                        anaFreq[k] = tmp;
                    }

                    // ***************** PROCESSING *******************
                    // this does the actual pitch shifting
                    std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);
                    std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        unsigned long index = static_cast<unsigned long>(k * pitchShift);
                        if (index <= fftFrameSize2)
                        {
                            synMagn[index] += anaMagn[k];
                            synFreq[index] = anaFreq[k] * pitchShift;
                        }
                    }

                    // ***************** SYNTHESIS *******************
                    // this is the synthesis step
                    for (unsigned long k = 0; k <= fftFrameSize2; k++)
                    {
                        // get magnitude and true frequency from synthesis arrays
                        float magn = synMagn[k];
                        float tmp = synFreq[k];

                        // subtract bin mid frequency
                        tmp -= static_cast<float>(k) * freqPerBin;

                        // get bin deviation from freq deviation
                        tmp /= freqPerBin;

                        // take osamp into account
                        tmp = 2.0F * PI * tmp / osamp;

                        // add the overlap phase advance back in
                        tmp += static_cast<float>(k) * expct;

                        // accumulate delta phase to get bin phase
                        sumPhase[k] += tmp;
                        float phase = sumPhase[k];

                        // get real and imag part and re-interleave
                        fftWorksp[k].real = magn * std::cos(phase);
                        fftWorksp[k].imag = magn * std::sin(phase);
                    }

                    // zero negative frequencies
                    for (unsigned long k = fftFrameSize + 1; k < fftFrameSize; k++) fftWorksp[k] = {0.0F, 0.0F};

                    // do inverse transform
                    fft(fftWorksp, fftFrameSize, 1);

                    // do windowing and add to output accumulator
                    for (unsigned long k = 0; k < fftFrameSize; k++)
                    {
                        float window = -0.5F * cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
                        outputAccum[k] += 2.0F * window * fftWorksp[k].real / (fftFrameSize2 * osamp);
                    }
                    for (unsigned long k = 0; k < stepSize; k++) outFIFO[k] = outputAccum[k];

                    // shift accumulator
                    memmove(outputAccum, outputAccum + stepSize, fftFrameSize * sizeof(float));

                    // move input FIFO
                    for (unsigned long k = 0; k < inFifoLatency; k++) inFIFO[k] = inFIFO[k + stepSize];
                }
            }
        }

    private:
        float inFIFO[MAX_FRAME_LENGTH];
        float outFIFO[MAX_FRAME_LENGTH];
        Complex<float> fftWorksp[MAX_FRAME_LENGTH];
        float lastPhase[MAX_FRAME_LENGTH / 2 + 1];
        float sumPhase[MAX_FRAME_LENGTH / 2 + 1];
        float outputAccum[2 * MAX_FRAME_LENGTH];
        float anaFreq[MAX_FRAME_LENGTH];
        float anaMagn[MAX_FRAME_LENGTH];
        float synFreq[MAX_FRAME_LENGTH];
        float synMagn[MAX_FRAME_LENGTH];
        unsigned long rover = 0;
    };
}

#endif
<|endoftext|>


<commit_before>#include <gflags/gflags.h>
#include <gtest/gtest.h>

#include <cstdlib>
#include <fstream>
#include <sstream>

#include "pmlc/util/logging.h"

DEFINE_string(skip_test_file, "", "A file containing a list of test patterns to skip");

int main(int argc, char *argv[]) {
  gflags::SetUsageMessage(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  START_EASYLOGGINGPP(argc, argv);

  gflags::ParseCommandLineFlags(&argc, &argv, true);

  if (argc != 1) {
    gflags::ShowUsageWithFlags(argv[0]);
    return EXIT_FAILURE;
  }

  if (FLAGS_skip_test_file.size()) {
    // If there's a skip test file, we're going to take each pattern it contains,
    // and add those patterns to gtest's filter's negative pattern list.

    // To start, see whether there's a '-' in the existing filter.  If
    // there isn't, we'll need to add one (to indicate that these are
    // negative tests); if there is, we should use ':'.  Regardless,
    // each subsequent added pattern is separated by ':'.
    char sep = ':';
    if (testing::FLAGS_gtest_filter.find('-') == std::string::npos) {
      sep = '-';
    }

    // Process the skip pattern file, building the flags pattern.
    std::ifstream fs{FLAGS_skip_test_file};
    if (!fs) {
      std::cerr << "Unable to open skip test file '" << FLAGS_skip_test_file << "'\n";
      return EXIT_FAILURE;
    }

    std::ostringstream ss{testing::FLAGS_gtest_filter};

    for (std::string line; std::getline(fs >> std::ws, line);) {
      // Erase trailing whitespace
      line.erase(std::find_if_not(line.rbegin(), line.rend(), [](int c) -> bool { return std::isspace(c); }).base(), line.end());
      ss << sep << line;
      sep = ':';
    }

    testing::FLAGS_gtest_filter = ss.str();
  }

  try {
    return RUN_ALL_TESTS();
  } catch (const std::exception &ex) {
    std::cerr << "Caught unhandled exception: " << ex.what() << std::endl;
    return EXIT_FAILURE;
  } catch (...) {
    std::cerr << "Caught unhandled exception" << std::endl;
    return EXIT_FAILURE;
  }
}
<commit_msg>Fix gtest_filter with skip_test_file on intel_gen target. (#1292)<commit_after>#include <gflags/gflags.h>
#include <gtest/gtest.h>

#include <cstdlib>
#include <fstream>
#include <sstream>

#include "pmlc/util/logging.h"

DEFINE_string(skip_test_file, "", "A file containing a list of test patterns to skip");

int main(int argc, char *argv[]) {
  gflags::SetUsageMessage(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  START_EASYLOGGINGPP(argc, argv);

  gflags::ParseCommandLineFlags(&argc, &argv, true);

  if (argc != 1) {
    gflags::ShowUsageWithFlags(argv[0]);
    return EXIT_FAILURE;
  }

  if (FLAGS_skip_test_file.size()) {
    // If there's a skip test file, we're going to take each pattern it contains,
    // and add those patterns to gtest's filter's negative pattern list.

    // To start, see whether there's a '-' in the existing filter.  If
    // there isn't, we'll need to add one (to indicate that these are
    // negative tests); if there is, we should use ':'.  Regardless,
    // each subsequent added pattern is separated by ':'.
    char sep = ':';
    if (testing::FLAGS_gtest_filter.find('-') == std::string::npos) {
      sep = '-';
    }

    // Process the skip pattern file, building the flags pattern.
    std::ifstream fs{FLAGS_skip_test_file};
    if (!fs) {
      std::cerr << "Unable to open skip test file '" << FLAGS_skip_test_file << "'\n";
      return EXIT_FAILURE;
    }

    std::ostringstream ss{testing::FLAGS_gtest_filter};

    for (std::string line; std::getline(fs >> std::ws, line);) {
      // Erase trailing whitespace
      line.erase(std::find_if_not(line.rbegin(), line.rend(), [](int c) -> bool { return std::isspace(c); }).base(), line.end());
      ss << sep << line;
      sep = ':';
    }

    testing::FLAGS_gtest_filter += ss.str();
  }

  try {
    return RUN_ALL_TESTS();
  } catch (const std::exception &ex) {
    std::cerr << "Caught unhandled exception: " << ex.what() << std::endl;
    return EXIT_FAILURE;
  } catch (...) {
    std::cerr << "Caught unhandled exception" << std::endl;
    return EXIT_FAILURE;
  }
}
<|endoftext|>


<commit_before>
#ifndef HOBBES_UTIL_STR_HPP_INCLUDED
#define HOBBES_UTIL_STR_HPP_INCLUDED

#include <hobbes/util/array.H>
#include <string>
#include <sstream>
#include <vector>
#include <cxxabi.h>
#include <stdlib.h>
#include <set>
#include <map>

namespace hobbes { namespace str {

std::string env(const std::string& varname);
void env(const std::string& varname, const std::string& value);

typedef std::vector<std::string>  seq;
typedef std::vector<seq>          seqs;
typedef std::vector<unsigned int> lengths;

void repeat(unsigned int n, const std::string& s, seq* out);
seq repeat(unsigned int n, const std::string& s);

template <typename C>
  unsigned int maxSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::max<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

template <typename C>
  unsigned int minSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::min<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

unsigned int tableCols(const seqs& tbl);
unsigned int tableRows(const seqs& tbl);
unsigned int maxStrLen(const seq&  col);
lengths maxStrLen(const seqs& tbl);
std::string pad(size_t n);
std::string leftAlign(size_t w, const std::string& x);
std::string rightAlign(size_t w, const std::string& x);
seq leftAlign(const seq& col);
seq rightAlign(const seq& col);
seqs leftAlign(const seqs& tbl);
seqs rightAlign(const seqs& tbl);
void printLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printRightAlignedTable(std::ostream& out, const seqs& tbl);
std::string showLeftAlignedTable(const seqs& tbl);
std::string showRightAlignedTable(const seqs& tbl);
void printHeadlessLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printHeadlessRightAlignedTable(std::ostream& out, const seqs& tbl);

template <typename T>
  bool is(const std::string& x) {
    std::istringstream ss(x);
    T dummy;
    ss >> dummy;
    return bool(ss);
  }

template <typename T>
  T to(const std::string& x) {
    std::istringstream ss(x);
    T r = T();
    ss >> r;
    return r;
  }

template <typename T>
  bool to(const std::string& x, T& out) {
    std::istringstream ss(x);
    ss >> out;
    return bool(ss);
  }

template <typename T>
  bool to(const char* b, const char* e, T* out) {
    std::istringstream ss(std::string(b, e));
    ss >> *out;
    return bool(ss);
  }

template <typename T>
  std::string from(const T& x) {
    std::ostringstream ss;
    ss << x;
    return ss.str();
  }

std::string demangle(const char* tn);
std::string demangle(const std::type_info& ti);

template <typename T>
  std::string demangle() {
    return demangle(typeid(T));
  }

template <typename Char>
  std::basic_string<Char> trim(const std::basic_string<Char>& s) {
    if (s.empty()) return s;

    size_t begin = 0;
    size_t end   = 0;

    for (size_t i = 0; i < s.size(); ++i) {
      int c = (int)s[i];
      if (!std::isspace(c) && c != 0) {
        begin = i;
        break;
      }
    }

    // finally, find the last non-whitespace character
    for (size_t i = s.size() - 1; i >= 0; --i) {
      int c = (int)s[i];
      if (!std::isspace(c) && c != 0) {
        end = i + 1;
        break;
      }
    }

    if (begin == end) {
      return "";
    } else {
      return s.substr(begin, end - begin);
    }
  }

template <typename Char>
  std::pair< std::basic_string<Char>, std::basic_string<Char> > trim(const std::pair< std::basic_string<Char>, std::basic_string<Char> >& p) {
    return std::pair< std::basic_string<Char>, std::basic_string<Char> >(trim<Char>(p.first), trim<Char>(p.second));
  }

template <typename Char>
  std::vector< std::basic_string<Char> > trim(const std::vector< std::basic_string<Char> >& ss) {
    std::vector< std::basic_string<Char> > result;
    for (typename std::vector< std::basic_string<Char> >::const_iterator s = ss.begin(); s != ss.end(); ++s) {
      result.push_back(trim<Char>(*s));
    }
    return result;
  }

template <typename Char>
  std::basic_string<Char> trimq(const std::basic_string<Char>& s, Char q = (Char)'"') {
    if (s.size() == 0) {
      return s;
    } else if (s.size() == 1) {
      return (s[0] == q) ? std::basic_string<Char>() : s;
    } else {
      const Char* b = s.c_str();
      const Char* e = b + s.size() - 1;
      if (*b == q) {
        ++b;
      }
      if (*e == q) {
        --e;
      }
      return std::basic_string<Char>(b, e + 1);
    }
  }

// replace [a b c b] [b c] [e] -> [a e b]
template <typename Char>
  std::basic_string<Char> replace(const std::basic_string<Char>& src, const std::basic_string<Char>& old_substr, const std::basic_string<Char>& new_substr) {
    if (old_substr.empty()) {
      return src;
    }

    typedef typename std::basic_string<Char>::size_type SZT;
    std::basic_string<Char> result;
    SZT                     sz     = src.find(old_substr);
    SZT                     lsz    = 0;

    while (sz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.begin() + sz);
      result += new_substr;

      lsz = sz + old_substr.size();
      sz  = src.find(old_substr, lsz);
    }

    if (lsz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.end());
    }

    return result;
  }

bool isNyb(char);
char denyb(char);
unsigned char dehex(const std::string&);
std::vector<unsigned char> dehexs(const std::string&);
char nyb(unsigned char x);
std::string hex(unsigned char);
std::string hex(const std::vector<unsigned char>&);
std::string hex(const unsigned char*, size_t);

std::string escape(const std::string&);
std::string unescape(const std::string&);

bool endsWith(const std::string& s, const std::string& sfx);

typedef std::pair<std::string, std::string> pair;

inline pair trim(const pair& p) {
  return pair(trim(p.first), trim(p.second));
}

pair splitAt(const std::string& s, unsigned int i);
pair lsplit(const std::string& s, const std::string& ss);
pair rsplit(const std::string& s, const std::string& ss);
seq csplit(const std::string& s, const std::string& ss);
pair readWhile(bool (*P)(char), const std::string& s);

bool isDigit(char c);
bool isNotDigit(char c);

unsigned int firstFailIndex(bool (*P)(char), const std::string& s);

// reverse csplit
std::string cdelim(const seq& ss, const std::string& d);

// common containers for strings
typedef std::set<std::string> set;
std::string show(const set&);

typedef std::map<std::string, std::string> named_strings;
std::string show(const named_strings&);

// process a string by 'expanding' embedded variables/expressions and unescaping sequences
template <typename T>
  T foldWithFormat(const std::string& str, const T& s, T (*constF)(const T&, const std::string&), T (*expF)(const T&, const std::string&)) {
    T r = s;

    std::ostringstream b;
    int x = 0;
    int bc = 0;

    for (size_t i = 0; i < str.size(); ++i) {
      char c = str[i];

      switch (x) {
      // process unformatted text (decide whether to start variables or unescape)
      case 0: {
          switch (c) {
          case '\\':
            x = 1;
            break;

          case '$':
            r = constF(r, b.str());
            b.str("");
            x = 2;
            break;

          default:
            b << c;
            break;
          }
          break;
        }
      // unescape
      case 1: {
          b << c;
          x = 0;
          break;
        }
      // process variables
      case 2: {
          if (c != '{') {
            b << c;
            x = 3;
          } else {
            bc = 1;
            x = 4;
          }
          break;
        }
      // process variable short-names (may only be alphanumeric)
      case 3: {
          if (std::isalnum(c) != 0 || c == '_') {
            b << c;
          } else {
            --i;
            r = expF(r, b.str());
            b.str("");
            x = 0;
          }
          break;
        }
      // process variable 'expressions' (may be anything delimited by braces)
      case 4: {
          if (c == '}') {
            if (bc == 1) {
              r = expF(r, b.str());
              b.str("");
              x = 0;
            } else {
              --bc;
              b << '}';
            }
          } else {
            if (c == '{') {
              ++bc;
            }
            b << c;
          }
          break;
        }
      }
    }

    if (x < 3) {
      r = constF(r, b.str());
    } else if (x == 3) {
      r = expF(r, b.str());
    }

    return r;
  }

// slurp the entire contents of an input stream into a string
inline std::string slurp(std::istream& in) {
  std::ostringstream ss;
  ss << in.rdbuf();
  return ss.str();
}

// generate?
inline seq strings() { return seq(); }
inline seq strings(const std::string& a0) { seq r; r.push_back(a0); return r; }
inline seq strings(const std::string& a0, const std::string& a1) { seq r; r.push_back(a0); r.push_back(a1); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4, const std::string& a5) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); r.push_back(a5); return r; }

// read a char definition like 'c' or 'd' or '\0'
char readCharDef(const std::string&);

// convenience functions for expanding environment variable references in strings and paths
std::string expandVars(const std::string&);
std::string expandPath(const std::string&); // same as 'expandVars' but expand '~' to home directory

// display a byte count in typical units
std::string showDataSize(size_t bytes);

// char set utilities
inline std::string charRange(char low, char high) {
  std::ostringstream ss;
  if (low < high) {
    for (char c = low; c <= high; ++c) {
      ss << c;
    }
  } else {
    for (char c = low; c >= high; --c) {
      ss << c;
    }
  }
  return ss.str();
}

inline std::string printableChars() {
  return charRange(0x20, 0x7e);
}

inline std::string difference(const std::string& x, const std::string& y) {
  return fromSet<std::string>(setDifference(toSet(x), toSet(y)));
}

// a set of strings represented as a prefix tree
class ptnode;

class prefix_tree {
public:
  prefix_tree(const seq&);
  prefix_tree(const set&);
  ~prefix_tree();

  std::map<size_t, seq> rankedMatches(const std::string&, size_t maxDist) const;
  seq closestMatches(const std::string&, size_t maxDist) const;
private:
  ptnode* root;
};

// how far is one string from another string?
size_t editDistance(const std::string&, const std::string&);

// find the strings out of a set that are at most the given edit distance away from an input string
seq closestMatches(const std::string&, const set&, size_t maxDist);
seq closestMatches(const std::string&, const seq&, size_t maxDist);

// ensure that a string has a given suffix (add it if it's not there)
std::string mustEndWith(const std::string&, const std::string&);

// get a set of filesystem objects matching a pattern
str::seq paths(const std::string& p);

}}

#endif
<commit_msg>signed to unsigned rep logic change<commit_after>
#ifndef HOBBES_UTIL_STR_HPP_INCLUDED
#define HOBBES_UTIL_STR_HPP_INCLUDED

#include <hobbes/util/array.H>
#include <string>
#include <sstream>
#include <vector>
#include <cxxabi.h>
#include <stdlib.h>
#include <set>
#include <map>

namespace hobbes { namespace str {

std::string env(const std::string& varname);
void env(const std::string& varname, const std::string& value);

typedef std::vector<std::string>  seq;
typedef std::vector<seq>          seqs;
typedef std::vector<unsigned int> lengths;

void repeat(unsigned int n, const std::string& s, seq* out);
seq repeat(unsigned int n, const std::string& s);

template <typename C>
  unsigned int maxSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::max<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

template <typename C>
  unsigned int minSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::min<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

unsigned int tableCols(const seqs& tbl);
unsigned int tableRows(const seqs& tbl);
unsigned int maxStrLen(const seq&  col);
lengths maxStrLen(const seqs& tbl);
std::string pad(size_t n);
std::string leftAlign(size_t w, const std::string& x);
std::string rightAlign(size_t w, const std::string& x);
seq leftAlign(const seq& col);
seq rightAlign(const seq& col);
seqs leftAlign(const seqs& tbl);
seqs rightAlign(const seqs& tbl);
void printLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printRightAlignedTable(std::ostream& out, const seqs& tbl);
std::string showLeftAlignedTable(const seqs& tbl);
std::string showRightAlignedTable(const seqs& tbl);
void printHeadlessLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printHeadlessRightAlignedTable(std::ostream& out, const seqs& tbl);

template <typename T>
  bool is(const std::string& x) {
    std::istringstream ss(x);
    T dummy;
    ss >> dummy;
    return bool(ss);
  }

template <typename T>
  T to(const std::string& x) {
    std::istringstream ss(x);
    T r = T();
    ss >> r;
    return r;
  }

template <typename T>
  bool to(const std::string& x, T& out) {
    std::istringstream ss(x);
    ss >> out;
    return bool(ss);
  }

template <typename T>
  bool to(const char* b, const char* e, T* out) {
    std::istringstream ss(std::string(b, e));
    ss >> *out;
    return bool(ss);
  }

template <typename T>
  std::string from(const T& x) {
    std::ostringstream ss;
    ss << x;
    return ss.str();
  }

std::string demangle(const char* tn);
std::string demangle(const std::type_info& ti);

template <typename T>
  std::string demangle() {
    return demangle(typeid(T));
  }

template <typename Char>
  std::basic_string<Char> trim(const std::basic_string<Char>& s) {
    if (s.empty()) return s;

    size_t begin = 0;
    size_t end   = 0;

    for (size_t i = 0; i < s.size(); ++i) {
      int c = (int)s[i];
      if (!std::isspace(c) && c != 0) {
        begin = i;
        break;
      }
    }

    // finally, find the last non-whitespace character
    for (size_t i = s.size(); i > 0; --i) {
      int c = (int)s[i-1];
      if (!std::isspace(c) && c != 0) {
        end = i;
        break;
      }
    }

    if (begin == end) {
      return "";
    } else {
      return s.substr(begin, end - begin);
    }
  }

template <typename Char>
  std::pair< std::basic_string<Char>, std::basic_string<Char> > trim(const std::pair< std::basic_string<Char>, std::basic_string<Char> >& p) {
    return std::pair< std::basic_string<Char>, std::basic_string<Char> >(trim<Char>(p.first), trim<Char>(p.second));
  }

template <typename Char>
  std::vector< std::basic_string<Char> > trim(const std::vector< std::basic_string<Char> >& ss) {
    std::vector< std::basic_string<Char> > result;
    for (typename std::vector< std::basic_string<Char> >::const_iterator s = ss.begin(); s != ss.end(); ++s) {
      result.push_back(trim<Char>(*s));
    }
    return result;
  }

template <typename Char>
  std::basic_string<Char> trimq(const std::basic_string<Char>& s, Char q = (Char)'"') {
    if (s.size() == 0) {
      return s;
    } else if (s.size() == 1) {
      return (s[0] == q) ? std::basic_string<Char>() : s;
    } else {
      const Char* b = s.c_str();
      const Char* e = b + s.size() - 1;
      if (*b == q) {
        ++b;
      }
      if (*e == q) {
        --e;
      }
      return std::basic_string<Char>(b, e + 1);
    }
  }

// replace [a b c b] [b c] [e] -> [a e b]
template <typename Char>
  std::basic_string<Char> replace(const std::basic_string<Char>& src, const std::basic_string<Char>& old_substr, const std::basic_string<Char>& new_substr) {
    if (old_substr.empty()) {
      return src;
    }

    typedef typename std::basic_string<Char>::size_type SZT;
    std::basic_string<Char> result;
    SZT                     sz     = src.find(old_substr);
    SZT                     lsz    = 0;

    while (sz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.begin() + sz);
      result += new_substr;

      lsz = sz + old_substr.size();
      sz  = src.find(old_substr, lsz);
    }

    if (lsz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.end());
    }

    return result;
  }

bool isNyb(char);
char denyb(char);
unsigned char dehex(const std::string&);
std::vector<unsigned char> dehexs(const std::string&);
char nyb(unsigned char x);
std::string hex(unsigned char);
std::string hex(const std::vector<unsigned char>&);
std::string hex(const unsigned char*, size_t);

std::string escape(const std::string&);
std::string unescape(const std::string&);

bool endsWith(const std::string& s, const std::string& sfx);

typedef std::pair<std::string, std::string> pair;

inline pair trim(const pair& p) {
  return pair(trim(p.first), trim(p.second));
}

pair splitAt(const std::string& s, unsigned int i);
pair lsplit(const std::string& s, const std::string& ss);
pair rsplit(const std::string& s, const std::string& ss);
seq csplit(const std::string& s, const std::string& ss);
pair readWhile(bool (*P)(char), const std::string& s);

bool isDigit(char c);
bool isNotDigit(char c);

unsigned int firstFailIndex(bool (*P)(char), const std::string& s);

// reverse csplit
std::string cdelim(const seq& ss, const std::string& d);

// common containers for strings
typedef std::set<std::string> set;
std::string show(const set&);

typedef std::map<std::string, std::string> named_strings;
std::string show(const named_strings&);

// process a string by 'expanding' embedded variables/expressions and unescaping sequences
template <typename T>
  T foldWithFormat(const std::string& str, const T& s, T (*constF)(const T&, const std::string&), T (*expF)(const T&, const std::string&)) {
    T r = s;

    std::ostringstream b;
    int x = 0;
    int bc = 0;

    for (size_t i = 0; i < str.size(); ++i) {
      char c = str[i];

      switch (x) {
      // process unformatted text (decide whether to start variables or unescape)
      case 0: {
          switch (c) {
          case '\\':
            x = 1;
            break;

          case '$':
            r = constF(r, b.str());
            b.str("");
            x = 2;
            break;

          default:
            b << c;
            break;
          }
          break;
        }
      // unescape
      case 1: {
          b << c;
          x = 0;
          break;
        }
      // process variables
      case 2: {
          if (c != '{') {
            b << c;
            x = 3;
          } else {
            bc = 1;
            x = 4;
          }
          break;
        }
      // process variable short-names (may only be alphanumeric)
      case 3: {
          if (std::isalnum(c) != 0 || c == '_') {
            b << c;
          } else {
            --i;
            r = expF(r, b.str());
            b.str("");
            x = 0;
          }
          break;
        }
      // process variable 'expressions' (may be anything delimited by braces)
      case 4: {
          if (c == '}') {
            if (bc == 1) {
              r = expF(r, b.str());
              b.str("");
              x = 0;
            } else {
              --bc;
              b << '}';
            }
          } else {
            if (c == '{') {
              ++bc;
            }
            b << c;
          }
          break;
        }
      }
    }

    if (x < 3) {
      r = constF(r, b.str());
    } else if (x == 3) {
      r = expF(r, b.str());
    }

    return r;
  }

// slurp the entire contents of an input stream into a string
inline std::string slurp(std::istream& in) {
  std::ostringstream ss;
  ss << in.rdbuf();
  return ss.str();
}

// generate?
inline seq strings() { return seq(); }
inline seq strings(const std::string& a0) { seq r; r.push_back(a0); return r; }
inline seq strings(const std::string& a0, const std::string& a1) { seq r; r.push_back(a0); r.push_back(a1); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4, const std::string& a5) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); r.push_back(a5); return r; }

// read a char definition like 'c' or 'd' or '\0'
char readCharDef(const std::string&);

// convenience functions for expanding environment variable references in strings and paths
std::string expandVars(const std::string&);
std::string expandPath(const std::string&); // same as 'expandVars' but expand '~' to home directory

// display a byte count in typical units
std::string showDataSize(size_t bytes);

// char set utilities
inline std::string charRange(char low, char high) {
  std::ostringstream ss;
  if (low < high) {
    for (char c = low; c <= high; ++c) {
      ss << c;
    }
  } else {
    for (char c = low; c >= high; --c) {
      ss << c;
    }
  }
  return ss.str();
}

inline std::string printableChars() {
  return charRange(0x20, 0x7e);
}

inline std::string difference(const std::string& x, const std::string& y) {
  return fromSet<std::string>(setDifference(toSet(x), toSet(y)));
}

// a set of strings represented as a prefix tree
class ptnode;

class prefix_tree {
public:
  prefix_tree(const seq&);
  prefix_tree(const set&);
  ~prefix_tree();

  std::map<size_t, seq> rankedMatches(const std::string&, size_t maxDist) const;
  seq closestMatches(const std::string&, size_t maxDist) const;
private:
  ptnode* root;
};

// how far is one string from another string?
size_t editDistance(const std::string&, const std::string&);

// find the strings out of a set that are at most the given edit distance away from an input string
seq closestMatches(const std::string&, const set&, size_t maxDist);
seq closestMatches(const std::string&, const seq&, size_t maxDist);

// ensure that a string has a given suffix (add it if it's not there)
std::string mustEndWith(const std::string&, const std::string&);

// get a set of filesystem objects matching a pattern
str::seq paths(const std::string& p);

}}

#endif
<|endoftext|>