<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Evgeniy Andreev (gsomix)
 */

#include <shogun/io/CSVFile.h>

#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>

using namespace shogun;

CCSVFile::CCSVFile()
{
	init();
}

CCSVFile::CCSVFile(FILE* f, const char* name) :
	CFile(f, name)
{
	init();
	init_with_defaults();
}

CCSVFile::CCSVFile(const char* fname, char rw, const char* name) :
	CFile(fname, rw, name)
{
	init();
	init_with_defaults();
}

CCSVFile::~CCSVFile()
{
	SG_UNREF(m_tokenizer);
	SG_UNREF(m_line_tokenizer);
	SG_UNREF(m_parser);
	SG_UNREF(m_line_reader);
}

void CCSVFile::set_order(csv_data_order order)
{
	m_order=order;
}

void CCSVFile::set_delimiter(char delimiter)
{
	m_tokenizer->delimiters[m_delimiter]=0;

	m_delimiter=delimiter;
	m_tokenizer->delimiters[m_delimiter]=1;
}

void CCSVFile::skip_lines(int32_t num_lines)
{
	for (int32_t i=0; i<num_lines; i++)
		m_line_reader->skip_line();
}

void CCSVFile::init()
{
	m_order=FORTRAN_ORDER;
	m_delimiter=0;

	m_tokenizer=NULL;
	m_line_tokenizer=NULL;
	m_parser=NULL;
	m_line_reader=NULL;
}

void CCSVFile::init_with_defaults()
{
	m_order=FORTRAN_ORDER;
	m_delimiter=',';

	m_tokenizer=new CDelimiterTokenizer(true);
	m_tokenizer->delimiters[m_delimiter]=1;
	m_tokenizer->delimiters[' ']=1;
	SG_REF(m_tokenizer);

	m_line_tokenizer=new CDelimiterTokenizer(true);
	m_line_tokenizer->delimiters['\n']=1;
	SG_REF(m_line_tokenizer);

	m_parser=new CParser();
	m_parser->set_tokenizer(m_tokenizer);

	m_line_reader=new CLineReader(file, m_line_tokenizer);
}

#define GET_VECTOR(fname, read_func, sg_type) \
void CCSVFile::fname(sg_type*& vector, int32_t& len) \
{ \
	if (!m_line_reader->has_next()) \
		return; \
	\
	SGVector<char> line=m_line_reader->read_line(); \
	m_tokenizer->set_text(line); \
	\
	len=0; \
	while (m_tokenizer->has_next()) \
	{ \
		index_t temp_start=0; \
		m_tokenizer->next_token_idx(temp_start); \
	\
		len++; \
	} \
	\
	m_parser->set_text(line); \
	vector=SG_MALLOC(sg_type, len); \
	for (int32_t i=0; i<len; i++) \
	{ \
		vector[i]=m_parser->read_func(); \
	} \
}

GET_VECTOR(get_vector, read_char, int8_t)
GET_VECTOR(get_vector, read_byte, uint8_t)
GET_VECTOR(get_vector, read_char, char)
GET_VECTOR(get_vector, read_int, int32_t)
GET_VECTOR(get_vector, read_uint, uint32_t)
GET_VECTOR(get_vector, read_short_real, float32_t)
GET_VECTOR(get_vector, read_real, float64_t)
GET_VECTOR(get_vector, read_long_real, floatmax_t)
GET_VECTOR(get_vector, read_short, int16_t)
GET_VECTOR(get_vector, read_word, uint16_t)
GET_VECTOR(get_vector, read_long, int64_t)
GET_VECTOR(get_vector, read_ulong, uint64_t)
#undef GET_VECTOR

#define GET_MATRIX(fname, read_func, sg_type) \
void CCSVFile::fname(sg_type*& matrix, int32_t& num_feat, int32_t& num_vec) \
{ \
	\
	int32_t nlines=0; \
	int32_t ntokens=-1; \
	\
	int32_t last_idx=0; \
	SGVector<sg_type> line_memory(true); \
	SGVector<sg_type> temp(true); \
	while(m_line_reader->has_next()) \
	{ \
		read_func(temp.vector, temp.vlen); \
		if (ntokens<0) \
			ntokens=temp.vlen; \
		\
		if (ntokens!=temp.vlen) \
			return; \
		\
		line_memory.resize_vector(last_idx+temp.vlen); \
		for (int32_t i=0; i<temp.vlen; i++) \
		{ \
			line_memory[i+last_idx]=temp[i]; \
		} \
		last_idx+=temp.vlen; \
		\
		nlines++; \
	} \
	\
	if (m_order==FORTRAN_ORDER) \
	{ \
		num_feat=nlines; \
		num_vec=ntokens; \
		SGVector<sg_type>::convert_to_matrix(matrix, num_vec, num_feat, line_memory.vector, line_memory.vlen, true); \
	} \
	else \
	{ \
		num_feat=ntokens; \
		num_vec=nlines; \
		SGVector<sg_type>::convert_to_matrix(matrix, num_vec, num_feat, line_memory.vector, line_memory.vlen, false); \
	} \
} \

GET_MATRIX(get_matrix, get_vector, int8_t)
GET_MATRIX(get_matrix, get_vector, uint8_t)
GET_MATRIX(get_matrix, get_vector, char)
GET_MATRIX(get_matrix, get_vector, int32_t)
GET_MATRIX(get_matrix, get_vector, uint32_t)
GET_MATRIX(get_matrix, get_vector, int64_t)
GET_MATRIX(get_matrix, get_vector, uint64_t)
GET_MATRIX(get_matrix, get_vector, float32_t)
GET_MATRIX(get_matrix, get_vector, float64_t)
GET_MATRIX(get_matrix, get_vector, floatmax_t)
GET_MATRIX(get_matrix, get_vector, int16_t)
GET_MATRIX(get_matrix, get_vector, uint16_t)
#undef GET_MATRIX

#define SET_VECTOR(fname, format, sg_type) \
void CCSVFile::fname(const sg_type* vector, int32_t len) \
{ \
	for (int32_t i=0; i<len; i++) \
	{ \
		fprintf(file, "%" format "%c", vector[i], m_delimiter); \
	} \
	fprintf(file, "\n"); \
}

SET_VECTOR(set_vector, SCNi8, int8_t)
SET_VECTOR(set_vector, SCNu8, uint8_t)
SET_VECTOR(set_vector, SCNu8, char)
SET_VECTOR(set_vector, SCNi32, int32_t)
SET_VECTOR(set_vector, SCNu32, uint32_t)
SET_VECTOR(set_vector, SCNi64, int64_t)
SET_VECTOR(set_vector, SCNu64, uint64_t)
SET_VECTOR(set_vector, "g", float32_t)
SET_VECTOR(set_vector, "lg", float64_t)
SET_VECTOR(set_vector, "Lg", floatmax_t)
SET_VECTOR(set_vector, SCNi16, int16_t)
SET_VECTOR(set_vector, SCNu16, uint16_t)
#undef SET_VECTOR

#define SET_MATRIX(fname, format, sg_type) \
void CCSVFile::fname(const sg_type* matrix, int32_t num_feat, int32_t num_vec) \
{ \
	if (m_order==FORTRAN_ORDER) \
	{ \
		for (int32_t i=0; i<num_feat; i++) \
		{ \
			for (int32_t j=0; j<num_vec; j++) \
				fprintf(file, "%" format "%c", matrix[j+i*num_vec], m_delimiter); \
			fprintf(file, "\n"); \
		} \
	} \
	else \
	{ \
		for (int32_t i=0; i<num_vec; i++) \
		{ \
			for (int32_t j=0; j<num_feat; j++) \
				fprintf(file, "%" format "%c", matrix[i+j*num_vec], m_delimiter); \
			fprintf(file, "\n"); \
		} \
	} \
}

SET_MATRIX(set_matrix, SCNi8, int8_t)
SET_MATRIX(set_matrix, SCNu8, uint8_t)
SET_MATRIX(set_matrix, SCNu8, char)
SET_MATRIX(set_matrix, SCNi32, int32_t)
SET_MATRIX(set_matrix, SCNu32, uint32_t)
SET_MATRIX(set_matrix, SCNi64, int64_t)
SET_MATRIX(set_matrix, SCNu64, uint64_t)
SET_MATRIX(set_matrix, "g", float32_t)
SET_MATRIX(set_matrix, "lg", float64_t)
SET_MATRIX(set_matrix, "Lg", floatmax_t)
SET_MATRIX(set_matrix, SCNi16, int16_t)
SET_MATRIX(set_matrix, SCNu16, uint16_t)
#undef SET_MATRIX
<commit_msg>switch to C_ORDER per default<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Evgeniy Andreev (gsomix)
 */

#include <shogun/io/CSVFile.h>

#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>

using namespace shogun;

CCSVFile::CCSVFile()
{
	init();
}

CCSVFile::CCSVFile(FILE* f, const char* name) :
	CFile(f, name)
{
	init();
	init_with_defaults();
}

CCSVFile::CCSVFile(const char* fname, char rw, const char* name) :
	CFile(fname, rw, name)
{
	init();
	init_with_defaults();
}

CCSVFile::~CCSVFile()
{
	SG_UNREF(m_tokenizer);
	SG_UNREF(m_line_tokenizer);
	SG_UNREF(m_parser);
	SG_UNREF(m_line_reader);
}

void CCSVFile::set_order(csv_data_order order)
{
	m_order=order;
}

void CCSVFile::set_delimiter(char delimiter)
{
	m_tokenizer->delimiters[m_delimiter]=0;

	m_delimiter=delimiter;
	m_tokenizer->delimiters[m_delimiter]=1;
}

void CCSVFile::skip_lines(int32_t num_lines)
{
	for (int32_t i=0; i<num_lines; i++)
		m_line_reader->skip_line();
}

void CCSVFile::init()
{
	m_order=C_ORDER;
	m_delimiter=0;

	m_tokenizer=NULL;
	m_line_tokenizer=NULL;
	m_parser=NULL;
	m_line_reader=NULL;
}

void CCSVFile::init_with_defaults()
{
	m_order=C_ORDER;
	m_delimiter=',';

	m_tokenizer=new CDelimiterTokenizer(true);
	m_tokenizer->delimiters[m_delimiter]=1;
	m_tokenizer->delimiters[' ']=1;
	SG_REF(m_tokenizer);

	m_line_tokenizer=new CDelimiterTokenizer(true);
	m_line_tokenizer->delimiters['\n']=1;
	SG_REF(m_line_tokenizer);

	m_parser=new CParser();
	m_parser->set_tokenizer(m_tokenizer);

	m_line_reader=new CLineReader(file, m_line_tokenizer);
}

#define GET_VECTOR(fname, read_func, sg_type) \
void CCSVFile::fname(sg_type*& vector, int32_t& len) \
{ \
	if (!m_line_reader->has_next()) \
		return; \
	\
	SGVector<char> line=m_line_reader->read_line(); \
	m_tokenizer->set_text(line); \
	\
	len=0; \
	while (m_tokenizer->has_next()) \
	{ \
		index_t temp_start=0; \
		m_tokenizer->next_token_idx(temp_start); \
	\
		len++; \
	} \
	\
	m_parser->set_text(line); \
	vector=SG_MALLOC(sg_type, len); \
	for (int32_t i=0; i<len; i++) \
	{ \
		vector[i]=m_parser->read_func(); \
	} \
}

GET_VECTOR(get_vector, read_char, int8_t)
GET_VECTOR(get_vector, read_byte, uint8_t)
GET_VECTOR(get_vector, read_char, char)
GET_VECTOR(get_vector, read_int, int32_t)
GET_VECTOR(get_vector, read_uint, uint32_t)
GET_VECTOR(get_vector, read_short_real, float32_t)
GET_VECTOR(get_vector, read_real, float64_t)
GET_VECTOR(get_vector, read_long_real, floatmax_t)
GET_VECTOR(get_vector, read_short, int16_t)
GET_VECTOR(get_vector, read_word, uint16_t)
GET_VECTOR(get_vector, read_long, int64_t)
GET_VECTOR(get_vector, read_ulong, uint64_t)
#undef GET_VECTOR

#define GET_MATRIX(fname, read_func, sg_type) \
void CCSVFile::fname(sg_type*& matrix, int32_t& num_feat, int32_t& num_vec) \
{ \
	\
	int32_t nlines=0; \
	int32_t ntokens=-1; \
	\
	int32_t last_idx=0; \
	SGVector<sg_type> line_memory(true); \
	SGVector<sg_type> temp(true); \
	while(m_line_reader->has_next()) \
	{ \
		read_func(temp.vector, temp.vlen); \
		if (ntokens<0) \
			ntokens=temp.vlen; \
		\
		if (ntokens!=temp.vlen) \
			return; \
		\
		line_memory.resize_vector(last_idx+temp.vlen); \
		for (int32_t i=0; i<temp.vlen; i++) \
		{ \
			line_memory[i+last_idx]=temp[i]; \
		} \
		last_idx+=temp.vlen; \
		\
		nlines++; \
	} \
	\
	if (m_order==FORTRAN_ORDER) \
	{ \
		num_feat=nlines; \
		num_vec=ntokens; \
		SGVector<sg_type>::convert_to_matrix(matrix, num_vec, num_feat, line_memory.vector, line_memory.vlen, true); \
	} \
	else \
	{ \
		num_feat=ntokens; \
		num_vec=nlines; \
		SGVector<sg_type>::convert_to_matrix(matrix, num_vec, num_feat, line_memory.vector, line_memory.vlen, false); \
	} \
} \

GET_MATRIX(get_matrix, get_vector, int8_t)
GET_MATRIX(get_matrix, get_vector, uint8_t)
GET_MATRIX(get_matrix, get_vector, char)
GET_MATRIX(get_matrix, get_vector, int32_t)
GET_MATRIX(get_matrix, get_vector, uint32_t)
GET_MATRIX(get_matrix, get_vector, int64_t)
GET_MATRIX(get_matrix, get_vector, uint64_t)
GET_MATRIX(get_matrix, get_vector, float32_t)
GET_MATRIX(get_matrix, get_vector, float64_t)
GET_MATRIX(get_matrix, get_vector, floatmax_t)
GET_MATRIX(get_matrix, get_vector, int16_t)
GET_MATRIX(get_matrix, get_vector, uint16_t)
#undef GET_MATRIX

#define SET_VECTOR(fname, format, sg_type) \
void CCSVFile::fname(const sg_type* vector, int32_t len) \
{ \
	for (int32_t i=0; i<len; i++) \
	{ \
		fprintf(file, "%" format "%c", vector[i], m_delimiter); \
	} \
	fprintf(file, "\n"); \
}

SET_VECTOR(set_vector, SCNi8, int8_t)
SET_VECTOR(set_vector, SCNu8, uint8_t)
SET_VECTOR(set_vector, SCNu8, char)
SET_VECTOR(set_vector, SCNi32, int32_t)
SET_VECTOR(set_vector, SCNu32, uint32_t)
SET_VECTOR(set_vector, SCNi64, int64_t)
SET_VECTOR(set_vector, SCNu64, uint64_t)
SET_VECTOR(set_vector, "g", float32_t)
SET_VECTOR(set_vector, "lg", float64_t)
SET_VECTOR(set_vector, "Lg", floatmax_t)
SET_VECTOR(set_vector, SCNi16, int16_t)
SET_VECTOR(set_vector, SCNu16, uint16_t)
#undef SET_VECTOR

#define SET_MATRIX(fname, format, sg_type) \
void CCSVFile::fname(const sg_type* matrix, int32_t num_feat, int32_t num_vec) \
{ \
	if (m_order==FORTRAN_ORDER) \
	{ \
		for (int32_t i=0; i<num_feat; i++) \
		{ \
			for (int32_t j=0; j<num_vec; j++) \
				fprintf(file, "%" format "%c", matrix[j+i*num_vec], m_delimiter); \
			fprintf(file, "\n"); \
		} \
	} \
	else \
	{ \
		for (int32_t i=0; i<num_vec; i++) \
		{ \
			for (int32_t j=0; j<num_feat; j++) \
				fprintf(file, "%" format "%c", matrix[i+j*num_vec], m_delimiter); \
			fprintf(file, "\n"); \
		} \
	} \
}

SET_MATRIX(set_matrix, SCNi8, int8_t)
SET_MATRIX(set_matrix, SCNu8, uint8_t)
SET_MATRIX(set_matrix, SCNu8, char)
SET_MATRIX(set_matrix, SCNi32, int32_t)
SET_MATRIX(set_matrix, SCNu32, uint32_t)
SET_MATRIX(set_matrix, SCNi64, int64_t)
SET_MATRIX(set_matrix, SCNu64, uint64_t)
SET_MATRIX(set_matrix, "g", float32_t)
SET_MATRIX(set_matrix, "lg", float64_t)
SET_MATRIX(set_matrix, "Lg", floatmax_t)
SET_MATRIX(set_matrix, SCNi16, int16_t)
SET_MATRIX(set_matrix, SCNu16, uint16_t)
#undef SET_MATRIX
<|endoftext|>


<commit_before><commit_msg>CID#705102 try and help coverity out re infinite loop<commit_after><|endoftext|>


<commit_before><commit_msg>OUString: avoid concatenated appends and temporaries<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tbxanchr.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 09:46:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <string> // HACK: prevent conflict between STLPORT and Workshop headers

#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _SFXMNUMGR_HXX //autogen
#include <sfx2/mnumgr.hxx>
#endif

#include "cmdid.h"
#include "docsh.hxx"
#include "swtypes.hxx"
#include "swmodule.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "viewopt.hxx"
#include "errhdl.hxx"
#include "ribbar.hrc"
#include "tbxanchr.hxx"

SFX_IMPL_TOOLBOX_CONTROL(SwTbxAnchor, SfxUInt16Item);

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

SwTbxAnchor::SwTbxAnchor(USHORT nId, ToolBox& rTbx, SfxBindings& rBind) :
    SfxToolBoxControl(nId, rTbx, rBind),
    nActAnchorId(0)
{
}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

 SwTbxAnchor::~SwTbxAnchor()
{
}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

void  SwTbxAnchor::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );

    if( eState == SFX_ITEM_AVAILABLE )
    {
        const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
        if(pItem)
            nActAnchorId = pItem->GetValue();
    }

}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

void  SwTbxAnchor::Click()
{
    PopupMenu aPopMenu(SW_RES(MN_ANCHOR_POPUP));

    SfxDispatcher* pDispatch = GetBindings().GetDispatcher();
    SfxViewFrame* pViewFrame = pDispatch ? pDispatch->GetFrame() : 0;
    SwView* pActiveView = 0;
    if(pViewFrame)
    {
        const TypeId aTypeId = TYPE(SwView);
        SwView* pView = (SwView*)SfxViewShell::GetFirst(&aTypeId);
        while( pView )
        {
            if(pView->GetViewFrame() == pViewFrame)
            {
                pActiveView = pView;
                break;
            }
            pView = (SwView*)SfxViewShell::GetNext(*pView, &aTypeId);
        }
    }
    if(!pActiveView)
    {
        DBG_ERROR("No active view could be found")
        return;
    }
    SwWrtShell* pWrtShell = pActiveView->GetWrtShellPtr();
    aPopMenu.EnableItem( FN_TOOL_ANKER_FRAME, 0 != pWrtShell->IsFlyInFly() );

    Rectangle aRect(GetToolBox().GetItemRect(FN_TOOL_ANKER));
    USHORT nHtmlMode = ::GetHtmlMode((SwDocShell*)SfxObjectShell::Current());
    BOOL bHtmlModeNoAnchor = ( nHtmlMode & HTMLMODE_ON) && 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS);

    if (bHtmlModeNoAnchor || pWrtShell->IsInHeaderFooter())
        aPopMenu.RemoveItem(aPopMenu.GetItemPos(FN_TOOL_ANKER_PAGE));

    if (!pWrtShell->IsFrmSelected())
        aPopMenu.RemoveItem(aPopMenu.GetItemPos(FN_TOOL_ANKER_AT_CHAR));

    if (nActAnchorId)
        aPopMenu.CheckItem(nActAnchorId);

    USHORT nSlotId = aPopMenu.Execute(&GetToolBox(), aRect.BottomLeft());
    GetToolBox().EndSelection();

    if (nSlotId)
        pDispatch->Execute(nSlotId, SFX_CALLMODE_ASYNCHRON|SFX_CALLMODE_RECORD);
}

<commit_msg>INTEGRATION: CWS swdrawpositioning (1.4.150); FILE MERGED 2004/04/14 11:34:26 os 1.4.150.1: #i26173# anchor context menu/drop down completed for drawings<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbxanchr.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-28 13:50:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <string> // HACK: prevent conflict between STLPORT and Workshop headers

#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _SFXMNUMGR_HXX //autogen
#include <sfx2/mnumgr.hxx>
#endif

#include "cmdid.h"
#include "docsh.hxx"
#include "swtypes.hxx"
#include "swmodule.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "viewopt.hxx"
#include "errhdl.hxx"
#include "ribbar.hrc"
#include "tbxanchr.hxx"

SFX_IMPL_TOOLBOX_CONTROL(SwTbxAnchor, SfxUInt16Item);

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

SwTbxAnchor::SwTbxAnchor(USHORT nId, ToolBox& rTbx, SfxBindings& rBind) :
    SfxToolBoxControl(nId, rTbx, rBind),
    nActAnchorId(0)
{
}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

 SwTbxAnchor::~SwTbxAnchor()
{
}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

void  SwTbxAnchor::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );

    if( eState == SFX_ITEM_AVAILABLE )
    {
        const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
        if(pItem)
            nActAnchorId = pItem->GetValue();
    }

}

/******************************************************************************
 *  Beschreibung:
 ******************************************************************************/

void  SwTbxAnchor::Click()
{
    PopupMenu aPopMenu(SW_RES(MN_ANCHOR_POPUP));

    SfxDispatcher* pDispatch = GetBindings().GetDispatcher();
    SfxViewFrame* pViewFrame = pDispatch ? pDispatch->GetFrame() : 0;
    SwView* pActiveView = 0;
    if(pViewFrame)
    {
        const TypeId aTypeId = TYPE(SwView);
        SwView* pView = (SwView*)SfxViewShell::GetFirst(&aTypeId);
        while( pView )
        {
            if(pView->GetViewFrame() == pViewFrame)
            {
                pActiveView = pView;
                break;
            }
            pView = (SwView*)SfxViewShell::GetNext(*pView, &aTypeId);
        }
    }
    if(!pActiveView)
    {
        DBG_ERROR("No active view could be found")
        return;
    }
    SwWrtShell* pWrtShell = pActiveView->GetWrtShellPtr();
    aPopMenu.EnableItem( FN_TOOL_ANKER_FRAME, 0 != pWrtShell->IsFlyInFly() );

    Rectangle aRect(GetToolBox().GetItemRect(FN_TOOL_ANKER));
    USHORT nHtmlMode = ::GetHtmlMode((SwDocShell*)SfxObjectShell::Current());
    BOOL bHtmlModeNoAnchor = ( nHtmlMode & HTMLMODE_ON) && 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS);

    if (bHtmlModeNoAnchor || pWrtShell->IsInHeaderFooter())
        aPopMenu.RemoveItem(aPopMenu.GetItemPos(FN_TOOL_ANKER_PAGE));

    if (nActAnchorId)
        aPopMenu.CheckItem(nActAnchorId);

    USHORT nSlotId = aPopMenu.Execute(&GetToolBox(), aRect.BottomLeft());
    GetToolBox().EndSelection();

    if (nSlotId)
        pDispatch->Execute(nSlotId, SFX_CALLMODE_ASYNCHRON|SFX_CALLMODE_RECORD);
}

<|endoftext|>


<commit_before><commit_msg>Correct way to do it.<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
//
//  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.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  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 COPYRIGHT OWNER 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.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferUI/DotNodeGadget.h"

#include "GafferUI/ConnectionGadget.h"
#include "GafferUI/GraphGadget.h"
#include "GafferUI/Nodule.h"
#include "GafferUI/SpacerGadget.h"
#include "GafferUI/Style.h"

#include "Gaffer/Dot.h"
#include "Gaffer/MetadataAlgo.h"
#include "Gaffer/ScriptNode.h"
#include "Gaffer/StringPlug.h"
#include "Gaffer/UndoScope.h"

#include "IECoreGL/GL.h"
#include "IECoreGL/Selector.h"

#include "boost/bind.hpp"

using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferUI;

IE_CORE_DEFINERUNTIMETYPED( DotNodeGadget );

DotNodeGadget::NodeGadgetTypeDescription<DotNodeGadget> DotNodeGadget::g_nodeGadgetTypeDescription( Gaffer::Dot::staticTypeId() );

DotNodeGadget::DotNodeGadget( Gaffer::NodePtr node )
	:	StandardNodeGadget( node )
{
	if( !runTimeCast<Dot>( node ) )
	{
		throw Exception( "DotNodeGadget requires a Dot" );
	}

	// Set the contents to have a small size, so the size of the Dot is controlled
	// largely by the nodeGadget:padding Metadata.
	setContents( new SpacerGadget( Box3f( V3f( -0.25 ), V3f( 0.25 ) ) ) );

	node->plugDirtiedSignal().connect( boost::bind( &DotNodeGadget::plugDirtied, this, ::_1 ) );
	node->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) );

	dragEnterSignal().connect( boost::bind( &DotNodeGadget::dragEnter, this, ::_2 ) );
	dropSignal().connect( boost::bind( &DotNodeGadget::drop, this, ::_2 ) );

	updateUpstreamNameChangedConnection();
	updateLabel();
}

DotNodeGadget::~DotNodeGadget()
{
}

void DotNodeGadget::doRenderLayer( Layer layer, const Style *style ) const
{
	if( layer != GraphLayer::Nodes )
	{
		return NodeGadget::doRenderLayer( layer, style );
	}

	Style::State state = getHighlighted() ? Style::HighlightedState : Style::NormalState;

	const Box3f b = bound();
	const V3f s = b.size();
	style->renderNodeFrame( Box2f( V2f( 0 ), V2f( 0 ) ), std::min( s.x, s.y ) / 2.0f, state, userColor() );

	if( !m_label.empty() && !IECoreGL::Selector::currentSelector() )
	{
		glPushMatrix();
		IECoreGL::glTranslate( m_labelPosition );
		style->renderText( Style::LabelText, m_label );
		glPopMatrix();
	}

	NodeGadget::doRenderLayer( layer, style );
}

Gaffer::Dot *DotNodeGadget::dotNode()
{
	return static_cast<Dot *>( node() );
}

const Gaffer::Dot *DotNodeGadget::dotNode() const
{
	return static_cast<const Dot *>( node() );
}

Gaffer::Node *DotNodeGadget::upstreamNode()
{
	Plug *plug = dotNode()->inPlug();
	while( plug && runTimeCast<Dot>( plug->node() ) )
	{
		plug = plug->getInput();
	}
	return plug ? plug->node() : nullptr;
}

void DotNodeGadget::plugDirtied( const Gaffer::Plug *plug )
{
	const Dot *dot = dotNode();
	if( plug == dot->labelTypePlug() || plug == dot->labelPlug() )
	{
		updateLabel();
	}
	else if( plug == dot->inPlug() )
	{
		updateUpstreamNameChangedConnection();
		updateLabel();
	}
}

void DotNodeGadget::nameChanged( const Gaffer::GraphComponent *graphComponent )
{
	updateLabel();
}

void DotNodeGadget::updateUpstreamNameChangedConnection()
{
	m_upstreamNameChangedConnection.disconnect();
	if( Node *n = upstreamNode() )
	{
		m_upstreamNameChangedConnection = n->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) );
	}
}

void DotNodeGadget::updateLabel()
{
	const Dot *dot = dotNode();

	const Dot::LabelType labelType = (Dot::LabelType)dot->labelTypePlug()->getValue();
	if( labelType == Dot::None )
	{
		m_label.clear();
	}
	else if( labelType == Dot::NodeName )
	{
		m_label = dot->getName();
	}
	else if( labelType == Dot::UpstreamNodeName )
	{
		const Node *n = upstreamNode();
		m_label = n ? n->getName() : "";
	}
	else
	{
		m_label = dot->labelPlug()->getValue();
	}

	Edge labelEdge = RightEdge;
	if( const Plug *p = dot->inPlug() )
	{
		if( noduleTangent( nodule( p ) ).x != 0 )
		{
			labelEdge = TopEdge;
		}
	}

	const Imath::Box3f thisBound = bound();
	if( labelEdge == TopEdge )
	{
		const Imath::Box3f labelBound = style()->textBound( Style::LabelText, m_label );
		m_labelPosition = V2f(
			-labelBound.size().x / 2.0,
			thisBound.max.y + 1.0
		);
	}
	else
	{
		const Imath::Box3f characterBound = style()->characterBound( Style::LabelText );
		m_labelPosition = V2f(
			thisBound.max.x,
			thisBound.center().y - characterBound.size().y / 2.0
		);
	}

	requestRender();
}

bool DotNodeGadget::dragEnter( const DragDropEvent &event )
{
	if( MetadataAlgo::readOnly( dotNode() ) )
	{
		return false;
	}

	if( dotNode()->inPlug() )
	{
		// We've already got our plugs set up - StandardNodeGadget
		// behaviour will take care of everything.
		return false;
	}

	const Plug *plug = runTimeCast<Plug>( event.data.get() );
	if( !plug )
	{
		return false;
	}

	const GraphGadget *graphGadget = ancestor<GraphGadget>();
	if( !graphGadget )
	{
		return false;
	}

	const NodeGadget *nodeGadget = graphGadget->nodeGadget( plug->node() );
	if( !nodeGadget )
	{
		return false;
	}

	const Nodule *nodule = nodeGadget->nodule( plug );
	if( !nodule )
	{
		return false;
	}

	V3f tangent = -nodeGadget->noduleTangent( nodule );
	V3f position = ( tangent * bound().size().x / 2.0f ) * fullTransform();
	position = position * event.sourceGadget->fullTransform().inverse();

	if( Nodule *sourceNodule = runTimeCast<Nodule>( event.sourceGadget.get() ) )
	{
		sourceNodule->updateDragEndPoint( position, tangent );
	}
	else if( ConnectionGadget *sourceConnection = runTimeCast<ConnectionGadget>( event.sourceGadget.get() ) )
	{
		sourceConnection->updateDragEndPoint( position, tangent );
	}

	return true;
}

bool DotNodeGadget::drop( const DragDropEvent &event )
{
	if( dotNode()->inPlug() )
	{
		// We've already got our plugs set up - StandardNodeGadget
		// behaviour will take care of everything.
		return false;
	}

	Plug *plug = runTimeCast<Plug>( event.data.get() );
	if( !plug )
	{
		return false;
	}

	Gaffer::UndoScope undoEnabler( node()->ancestor<ScriptNode>() );

	dotNode()->setup( plug );
	if( plug->direction() == Plug::In )
	{
		plug->setInput( dotNode()->outPlug() );
	}
	else
	{
		dotNode()->inPlug()->setInput( plug );
	}

	return true;
}
<commit_msg>DotNodeGadget : Simplify drag snapping<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
//
//  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.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  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 COPYRIGHT OWNER 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.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferUI/DotNodeGadget.h"

#include "GafferUI/ConnectionGadget.h"
#include "GafferUI/GraphGadget.h"
#include "GafferUI/Nodule.h"
#include "GafferUI/SpacerGadget.h"
#include "GafferUI/Style.h"

#include "Gaffer/Dot.h"
#include "Gaffer/MetadataAlgo.h"
#include "Gaffer/ScriptNode.h"
#include "Gaffer/StringPlug.h"
#include "Gaffer/UndoScope.h"

#include "IECoreGL/GL.h"
#include "IECoreGL/Selector.h"

#include "boost/bind.hpp"

using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferUI;

IE_CORE_DEFINERUNTIMETYPED( DotNodeGadget );

DotNodeGadget::NodeGadgetTypeDescription<DotNodeGadget> DotNodeGadget::g_nodeGadgetTypeDescription( Gaffer::Dot::staticTypeId() );

DotNodeGadget::DotNodeGadget( Gaffer::NodePtr node )
	:	StandardNodeGadget( node )
{
	if( !runTimeCast<Dot>( node ) )
	{
		throw Exception( "DotNodeGadget requires a Dot" );
	}

	// Set the contents to have a small size, so the size of the Dot is controlled
	// largely by the nodeGadget:padding Metadata.
	setContents( new SpacerGadget( Box3f( V3f( -0.25 ), V3f( 0.25 ) ) ) );

	node->plugDirtiedSignal().connect( boost::bind( &DotNodeGadget::plugDirtied, this, ::_1 ) );
	node->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) );

	dragEnterSignal().connect( boost::bind( &DotNodeGadget::dragEnter, this, ::_2 ) );
	dropSignal().connect( boost::bind( &DotNodeGadget::drop, this, ::_2 ) );

	updateUpstreamNameChangedConnection();
	updateLabel();
}

DotNodeGadget::~DotNodeGadget()
{
}

void DotNodeGadget::doRenderLayer( Layer layer, const Style *style ) const
{
	if( layer != GraphLayer::Nodes )
	{
		return NodeGadget::doRenderLayer( layer, style );
	}

	Style::State state = getHighlighted() ? Style::HighlightedState : Style::NormalState;

	const Box3f b = bound();
	const V3f s = b.size();
	style->renderNodeFrame( Box2f( V2f( 0 ), V2f( 0 ) ), std::min( s.x, s.y ) / 2.0f, state, userColor() );

	if( !m_label.empty() && !IECoreGL::Selector::currentSelector() )
	{
		glPushMatrix();
		IECoreGL::glTranslate( m_labelPosition );
		style->renderText( Style::LabelText, m_label );
		glPopMatrix();
	}

	NodeGadget::doRenderLayer( layer, style );
}

Gaffer::Dot *DotNodeGadget::dotNode()
{
	return static_cast<Dot *>( node() );
}

const Gaffer::Dot *DotNodeGadget::dotNode() const
{
	return static_cast<const Dot *>( node() );
}

Gaffer::Node *DotNodeGadget::upstreamNode()
{
	Plug *plug = dotNode()->inPlug();
	while( plug && runTimeCast<Dot>( plug->node() ) )
	{
		plug = plug->getInput();
	}
	return plug ? plug->node() : nullptr;
}

void DotNodeGadget::plugDirtied( const Gaffer::Plug *plug )
{
	const Dot *dot = dotNode();
	if( plug == dot->labelTypePlug() || plug == dot->labelPlug() )
	{
		updateLabel();
	}
	else if( plug == dot->inPlug() )
	{
		updateUpstreamNameChangedConnection();
		updateLabel();
	}
}

void DotNodeGadget::nameChanged( const Gaffer::GraphComponent *graphComponent )
{
	updateLabel();
}

void DotNodeGadget::updateUpstreamNameChangedConnection()
{
	m_upstreamNameChangedConnection.disconnect();
	if( Node *n = upstreamNode() )
	{
		m_upstreamNameChangedConnection = n->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) );
	}
}

void DotNodeGadget::updateLabel()
{
	const Dot *dot = dotNode();

	const Dot::LabelType labelType = (Dot::LabelType)dot->labelTypePlug()->getValue();
	if( labelType == Dot::None )
	{
		m_label.clear();
	}
	else if( labelType == Dot::NodeName )
	{
		m_label = dot->getName();
	}
	else if( labelType == Dot::UpstreamNodeName )
	{
		const Node *n = upstreamNode();
		m_label = n ? n->getName() : "";
	}
	else
	{
		m_label = dot->labelPlug()->getValue();
	}

	Edge labelEdge = RightEdge;
	if( const Plug *p = dot->inPlug() )
	{
		if( noduleTangent( nodule( p ) ).x != 0 )
		{
			labelEdge = TopEdge;
		}
	}

	const Imath::Box3f thisBound = bound();
	if( labelEdge == TopEdge )
	{
		const Imath::Box3f labelBound = style()->textBound( Style::LabelText, m_label );
		m_labelPosition = V2f(
			-labelBound.size().x / 2.0,
			thisBound.max.y + 1.0
		);
	}
	else
	{
		const Imath::Box3f characterBound = style()->characterBound( Style::LabelText );
		m_labelPosition = V2f(
			thisBound.max.x,
			thisBound.center().y - characterBound.size().y / 2.0
		);
	}

	requestRender();
}

bool DotNodeGadget::dragEnter( const DragDropEvent &event )
{
	if( MetadataAlgo::readOnly( dotNode() ) )
	{
		return false;
	}

	if( dotNode()->inPlug() )
	{
		// We've already got our plugs set up - StandardNodeGadget
		// behaviour will take care of everything.
		return false;
	}

	const Plug *plug = runTimeCast<Plug>( event.data.get() );
	if( !plug )
	{
		return false;
	}

	const GraphGadget *graphGadget = ancestor<GraphGadget>();
	if( !graphGadget )
	{
		return false;
	}

	const NodeGadget *nodeGadget = graphGadget->nodeGadget( plug->node() );
	if( !nodeGadget )
	{
		return false;
	}

	const Nodule *nodule = nodeGadget->nodule( plug );
	if( !nodule )
	{
		return false;
	}

	if( auto connectionCreator = runTimeCast<ConnectionCreator>( event.sourceGadget.get() ) )
	{
		V3f tangent = -nodeGadget->noduleTangent( nodule );
		V3f position = ( tangent * bound().size().x / 2.0f ) * fullTransform();
		position = position * connectionCreator->fullTransform().inverse();
		connectionCreator->updateDragEndPoint( position, tangent );
	}

	return true;
}

bool DotNodeGadget::drop( const DragDropEvent &event )
{
	if( dotNode()->inPlug() )
	{
		// We've already got our plugs set up - StandardNodeGadget
		// behaviour will take care of everything.
		return false;
	}

	Plug *plug = runTimeCast<Plug>( event.data.get() );
	if( !plug )
	{
		return false;
	}

	Gaffer::UndoScope undoEnabler( node()->ancestor<ScriptNode>() );

	dotNode()->setup( plug );
	if( plug->direction() == Plug::In )
	{
		plug->setInput( dotNode()->outPlug() );
	}
	else
	{
		dotNode()->inPlug()->setInput( plug );
	}

	return true;
}
<|endoftext|>


<commit_before>/************************************************************************/
/*                                                                      */
/*               Copyright 2008-2011 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    */
/*        vigra@informatik.uni-hamburg.de                               */
/*                                                                      */
/*    Permission is hereby granted, free of charge, to any person       */
/*    obtaining a copy of this software and associated documentation    */
/*    files (the "Software"), to deal in the Software without           */
/*    restriction, including without limitation the rights to use,      */
/*    copy, modify, merge, publish, distribute, sublicense, and/or      */
/*    sell copies of the Software, and to permit persons to whom the    */
/*    Software is furnished to do so, subject to the following          */
/*    conditions:                                                       */
/*                                                                      */
/*    The above copyright notice and this permission notice shall be    */
/*    included in all copies or substantial portions of the             */
/*    Software.                                                         */
/*                                                                      */
/*    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND    */
/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */
/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */
/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */
/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */
/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */
/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */
/*    OTHER DEALINGS IN THE SOFTWARE.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_TIMING_HXX
#define VIGRA_TIMING_HXX
#ifndef VIGRA_NO_TIMING

#include <iostream>
#include <sstream>
#include <vector>

// Usage:
//
// void time_it()
// {
//     USETICTOC
//
//     TIC
//      ... // code to be timed
//     TOC
//      ... // untimed code
//     TIC
//      ... // other code to be timed
//     TOC
// }
//
// Intead of TOC which outputs the time difference to std::cerr,
// you may use TOCN (the time difference in msec as a double)
// or TOCS (the time difference as a std::string).
//
// Alternatively, you can performe nested timing like so:
//
// void time_it()
// {
//     USE_NESTED_TICTOC
//
//     TICPUSH
//      ...      // code to be timed
//     TICPUSH
//      ...      // nested code to be timed
//     TOC       // print time for nested code
//      ...      // more code to be timed
//     TOC       // print total time
// }
//
// Timings below 1 msec are generally subject to round-off errors. Under
// LINUX, you can #define VIGRA_HIRES_TIMING to get better
// accuracy, but this requires linking against librt.

#ifdef WIN32

    #include "windows.h"

    namespace {

    inline double queryTimerUnit()
    {
        LARGE_INTEGER frequency;
        QueryPerformanceFrequency(&frequency);
        return 1000.0 / frequency.QuadPart;
    }

    inline double tic_toc_diff_num(LARGE_INTEGER const & tic)
    {
        LARGE_INTEGER toc;
        QueryPerformanceCounter(&toc);
        static double unit = queryTimerUnit();
        return ((toc.QuadPart - tic.QuadPart) * unit);
    }

    inline std::string tic_toc_diff_string(LARGE_INTEGER const & tic)
    {
        double diff = tic_toc_diff_num(tic);
        std::stringstream s;
        s << diff << " msec";
        return s.str();
    }

    inline void tic_toc_diff(LARGE_INTEGER const & tic)
    {
        std::cerr << tic_toc_diff_string(tic) <<std::endl;
    }

    inline double tic_toc_diff_num(std::vector<LARGE_INTEGER> & tic)
    {
        double res = tic_toc_diff_num(tic.back());
        tic.pop_back();
        return res;
    }

    inline std::string tic_toc_diff_string(std::vector<LARGE_INTEGER> & tic)
    {
        std::string res = tic_toc_diff_string(tic.back());
        tic.pop_back();
        return res;
    }

    inline void tic_toc_diff(std::vector<LARGE_INTEGER> & tic)
    {
        tic_toc_diff(tic.back());
        tic.pop_back();
    }

    } // unnamed namespace

    #define USETICTOC LARGE_INTEGER tic_timer;
    #define USE_NESTED_TICTOC std::vector<LARGE_INTEGER> tic_timer;
    #define TIC QueryPerformanceCounter(&tic_timer);
    #define TICPUSH tic_timer.push_back(LARGE_INTEGER());\
                    QueryPerformanceCounter(&(tic_timer.back()));
    #define TOC  tic_toc_diff       (tic_timer);
    #define TOCN tic_toc_diff_num   (tic_timer)
    #define TOCS tic_toc_diff_string(tic_timer)

#else

    #if defined(VIGRA_HIRES_TIMING) && !defined(__CYGWIN__)
        // requires linking against librt

        #include <time.h>

        namespace {

        inline double tic_toc_diff_num(timespec const & tic)
        {
            timespec toc;
            clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &toc);
            return ((toc.tv_sec*1000.0 + toc.tv_nsec/1000000.0) -
                  (tic.tv_sec*1000.0 + tic.tv_nsec/1000000.0));
        }

        inline std::string tic_toc_diff_string(timespec const & tic)
        {
            double diff = tic_toc_diff_num(tic);
            std::stringstream s;
            s << diff << " msec";
            return s.str();
        }

        inline void tic_toc_diff(timespec const & tic)
        {
            std::cerr << tic_toc_diff_string(tic) << std::endl;
        }

        inline double tic_toc_diff_num(std::vector<timespec> & tic)
        {
            double res = tic_toc_diff_num(tic.back());
            tic.pop_back();
            return res;
        }

        inline std::string tic_toc_diff_string(std::vector<timespec> & tic)
        {
            std::string res = tic_toc_diff_string(tic.back());
            tic.pop_back();
            return res;
        }

        inline void tic_toc_diff(std::vector<timespec> & tic)
        {
            tic_toc_diff(tic.back());
            tic.pop_back();
        }

        } // unnamed namespace

        #define USETICTOC timespec tic_timer;
        #define TIC clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tic_timer);
        #define TOC  tic_toc_diff       (tic_timer);
        #define TOCN tic_toc_diff_num   (tic_timer)
        #define TOCS tic_toc_diff_string(tic_timer)
        #define USE_NESTED_TICTOC std::vector<timespec> tic_timer;
        #define TICPUSH tic_timer.push_back(timespec());\
                        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(tic_timer.back()));

    #else

        #include <sys/time.h>

        namespace {

        inline double tic_toc_diff_num(timeval const & tic)
        {
            timeval toc;
            gettimeofday(&toc, NULL);
            return  ((toc.tv_sec*1000.0 + toc.tv_usec/1000.0) -
                        (tic.tv_sec*1000.0 + tic.tv_usec/1000.0));
        }

        inline std::string tic_toc_diff_string(timeval const & tic)
        {
            double diff = tic_toc_diff_num(tic);
            std::stringstream s;
            s << diff << " msec";
            return s.str();
        }

        inline void tic_toc_diff(timeval const & tic)
        {
            std::cerr << tic_toc_diff_string(tic)<< std::endl;
        }

        inline double tic_toc_diff_num(std::vector<timeval> & tic)
        {
            double res = tic_toc_diff_num(tic.back());
            tic.pop_back();
            return res;
        }

        inline std::string tic_toc_diff_string(std::vector<timeval> & tic)
        {
            std::string res = tic_toc_diff_string(tic.back());
            tic.pop_back();
            return res;
        }

        inline void tic_toc_diff(std::vector<timeval> & tic)
        {
            tic_toc_diff(tic.back());
            tic.pop_back();
        }

        } // unnamed namespace

        #define USETICTOC timeval tic_timer;
        #define TIC  gettimeofday       (&tic_timer, NULL);
        #define TOC  tic_toc_diff       (tic_timer);
        #define TOCN tic_toc_diff_num   (tic_timer)
        #define TOCS tic_toc_diff_string(tic_timer)
        #define USE_NESTED_TICTOC std::vector<timeval> tic_timer;
        #define TICPUSH tic_timer.push_back(timeval());\
                        gettimeofday(&(tic_timer.back()), NULL);

    #endif // VIGRA_HIRES_TIMING

#endif // WIN32

#else // NDEBUG

#define USETICTOC
#define TIC
#define TOC
#define TOCN 0.0
#define TICS ""
#define USE_NESTED_TICTOC
#define TICPUSH
#endif // NDEBUG

#endif // VIGRA_TIMING_HXX
<commit_msg>Timing macro for a executing a number of repetitions of some measurement, and taking the best of possibly several runs. (More advanced versions are of course possible, such as outputting some summary  statistics of the runs.)<commit_after>/************************************************************************/
/*                                                                      */
/*               Copyright 2008-2011 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    */
/*        vigra@informatik.uni-hamburg.de                               */
/*                                                                      */
/*    Permission is hereby granted, free of charge, to any person       */
/*    obtaining a copy of this software and associated documentation    */
/*    files (the "Software"), to deal in the Software without           */
/*    restriction, including without limitation the rights to use,      */
/*    copy, modify, merge, publish, distribute, sublicense, and/or      */
/*    sell copies of the Software, and to permit persons to whom the    */
/*    Software is furnished to do so, subject to the following          */
/*    conditions:                                                       */
/*                                                                      */
/*    The above copyright notice and this permission notice shall be    */
/*    included in all copies or substantial portions of the             */
/*    Software.                                                         */
/*                                                                      */
/*    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND    */
/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */
/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */
/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */
/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */
/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */
/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */
/*    OTHER DEALINGS IN THE SOFTWARE.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_TIMING_HXX
#define VIGRA_TIMING_HXX
#ifndef VIGRA_NO_TIMING

#include <iostream>
#include <sstream>
#include <vector>

// Usage:
//
// void time_it()
// {
//     USETICTOC
//
//     TIC
//      ... // code to be timed
//     TOC
//      ... // untimed code
//     TIC
//      ... // other code to be timed
//     TOC
// }
//
// Intead of TOC which outputs the time difference to std::cerr,
// you may use TOCN (the time difference in msec as a double)
// or TOCS (the time difference as a std::string).
//
// Alternatively, you can performe nested timing like so:
//
// void time_it()
// {
//     USE_NESTED_TICTOC
//
//     TICPUSH
//      ...      // code to be timed
//     TICPUSH
//      ...      // nested code to be timed
//     TOC       // print time for nested code
//      ...      // more code to be timed
//     TOC       // print total time
// }
//
// Timings below 1 msec are generally subject to round-off errors. Under
// LINUX, you can #define VIGRA_HIRES_TIMING to get better
// accuracy, but this requires linking against librt.

#ifdef WIN32

    #include "windows.h"

    namespace {

    inline double queryTimerUnit()
    {
        LARGE_INTEGER frequency;
        QueryPerformanceFrequency(&frequency);
        return 1000.0 / frequency.QuadPart;
    }

    inline double tic_toc_diff_num(LARGE_INTEGER const & tic)
    {
        LARGE_INTEGER toc;
        QueryPerformanceCounter(&toc);
        static double unit = queryTimerUnit();
        return ((toc.QuadPart - tic.QuadPart) * unit);
    }

    inline std::string tic_toc_diff_string(LARGE_INTEGER const & tic)
    {
        double diff = tic_toc_diff_num(tic);
        std::stringstream s;
        s << diff << " msec";
        return s.str();
    }

    inline void tic_toc_diff(LARGE_INTEGER const & tic)
    {
        std::cerr << tic_toc_diff_string(tic) <<std::endl;
    }

    inline double tic_toc_diff_num(std::vector<LARGE_INTEGER> & tic)
    {
        double res = tic_toc_diff_num(tic.back());
        tic.pop_back();
        return res;
    }

    inline std::string tic_toc_diff_string(std::vector<LARGE_INTEGER> & tic)
    {
        std::string res = tic_toc_diff_string(tic.back());
        tic.pop_back();
        return res;
    }

    inline void tic_toc_diff(std::vector<LARGE_INTEGER> & tic)
    {
        tic_toc_diff(tic.back());
        tic.pop_back();
    }

    } // unnamed namespace

    #define USETICTOC LARGE_INTEGER tic_timer;
    #define USE_NESTED_TICTOC std::vector<LARGE_INTEGER> tic_timer;
    #define TIC QueryPerformanceCounter(&tic_timer);
    #define TICPUSH tic_timer.push_back(LARGE_INTEGER());\
                    QueryPerformanceCounter(&(tic_timer.back()));
    #define TOC  tic_toc_diff       (tic_timer);
    #define TOCN tic_toc_diff_num   (tic_timer)
    #define TOCS tic_toc_diff_string(tic_timer)

#else

    #if defined(VIGRA_HIRES_TIMING) && !defined(__CYGWIN__)
        // requires linking against librt

        #include <time.h>

        namespace {

        inline double tic_toc_diff_num(timespec const & tic)
        {
            timespec toc;
            clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &toc);
            return ((toc.tv_sec*1000.0 + toc.tv_nsec/1000000.0) -
                  (tic.tv_sec*1000.0 + tic.tv_nsec/1000000.0));
        }

        inline std::string tic_toc_diff_string(timespec const & tic)
        {
            double diff = tic_toc_diff_num(tic);
            std::stringstream s;
            s << diff << " msec";
            return s.str();
        }

        inline void tic_toc_diff(timespec const & tic)
        {
            std::cerr << tic_toc_diff_string(tic) << std::endl;
        }

        inline double tic_toc_diff_num(std::vector<timespec> & tic)
        {
            double res = tic_toc_diff_num(tic.back());
            tic.pop_back();
            return res;
        }

        inline std::string tic_toc_diff_string(std::vector<timespec> & tic)
        {
            std::string res = tic_toc_diff_string(tic.back());
            tic.pop_back();
            return res;
        }

        inline void tic_toc_diff(std::vector<timespec> & tic)
        {
            tic_toc_diff(tic.back());
            tic.pop_back();
        }

        } // unnamed namespace

        #define USETICTOC timespec tic_timer;
        #define TIC clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tic_timer);
        #define TOC  tic_toc_diff       (tic_timer);
        #define TOCN tic_toc_diff_num   (tic_timer)
        #define TOCS tic_toc_diff_string(tic_timer)
        #define USE_NESTED_TICTOC std::vector<timespec> tic_timer;
        #define TICPUSH tic_timer.push_back(timespec());\
                        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(tic_timer.back()));

    #else

        #include <sys/time.h>

        namespace {

        inline double tic_toc_diff_num(timeval const & tic)
        {
            timeval toc;
            gettimeofday(&toc, NULL);
            return  ((toc.tv_sec*1000.0 + toc.tv_usec/1000.0) -
                        (tic.tv_sec*1000.0 + tic.tv_usec/1000.0));
        }

        inline std::string tic_toc_diff_string(timeval const & tic)
        {
            double diff = tic_toc_diff_num(tic);
            std::stringstream s;
            s << diff << " msec";
            return s.str();
        }

        inline void tic_toc_diff(timeval const & tic)
        {
            std::cerr << tic_toc_diff_string(tic)<< std::endl;
        }

        inline double tic_toc_diff_num(std::vector<timeval> & tic)
        {
            double res = tic_toc_diff_num(tic.back());
            tic.pop_back();
            return res;
        }

        inline std::string tic_toc_diff_string(std::vector<timeval> & tic)
        {
            std::string res = tic_toc_diff_string(tic.back());
            tic.pop_back();
            return res;
        }

        inline void tic_toc_diff(std::vector<timeval> & tic)
        {
            tic_toc_diff(tic.back());
            tic.pop_back();
        }

        } // unnamed namespace

        #define USETICTOC timeval tic_timer;
        #define TIC  gettimeofday       (&tic_timer, NULL);
        #define TOC  tic_toc_diff       (tic_timer);
        #define TOCN tic_toc_diff_num   (tic_timer)
        #define TOCS tic_toc_diff_string(tic_timer)
        #define USE_NESTED_TICTOC std::vector<timeval> tic_timer;
        #define TICPUSH tic_timer.push_back(timeval());\
                        gettimeofday(&(tic_timer.back()), NULL);

    #endif // VIGRA_HIRES_TIMING

#endif // WIN32

// TICTOCLOOP runs the body inner_repetitions times, and minimizes the result over a number of outer_repetitions runs,
//  outputting the final minimal average to std::cerr
#define TICTOCLOOP_BEGIN(inner_repetitions,outer_repetitions) \
    { \
	USETICTOC \
	    double tictoc_best_, tictoc_inner_repetitions_=inner_repetitions; size_t tictoc_outer_repetitions_=outer_repetitions; \
	    for (size_t tictoccounter_=0; tictoccounter_<tictoc_outer_repetitions_; ++tictoccounter_) { \
		TIC \
		for (size_t tictocinnercounter_=0; tictocinnercounter_<inner_repetitions; ++tictocinnercounter_) { \

#define TICTOCLOOP_END \
                } \
		const double tictoc_cur_ = TOCN; \
                if ((tictoccounter_==0) || (tictoc_cur_ < tictoc_best_)) \
		    tictoc_best_ = tictoc_cur_; \
	    } \
	    std::cerr << tictoc_best_/tictoc_inner_repetitions_ \
			 << " msec (best-of-" << tictoc_outer_repetitions_ << ")" << std::endl; \
    }\

#else // NDEBUG

#define USETICTOC
#define TIC
#define TOC
#define TOCN 0.0
#define TICS ""
#define USE_NESTED_TICTOC
#define TICPUSH
#define TICTOCLOOP_BEGIN {
#define TICTOCLOOP_END }
#endif // NDEBUG

#endif // VIGRA_TIMING_HXX
<|endoftext|>


<commit_before><commit_msg>MAINT-3553 Another checking is added to avoid possible crash.<commit_after><|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/jit/flags.h"

#include <mutex>  // NOLINT

#include "absl/base/call_once.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/compiler/xla/parse_flags_from_env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/command_line_flags.h"

namespace tensorflow {
namespace {

BuildXlaOpsPassFlags* build_ops_flags;
MarkForCompilationPassFlags* mark_for_compilation_flags;
XlaDeviceFlags* device_flags;
XlaOpsCommonFlags* ops_flags;
IntroduceFloatingPointJitterPassFlags* jitter_flags;

std::vector<Flag>* flag_list;
absl::once_flag flags_init;

bool SetterForXlaAutoJitFlag(const string& value) {
  int32 opt_level;
  // We need to use the mark_for_compilation_flags directly here instead of
  // going via GetMarkForCompilationPassFlags() to avoid infinite recursion. The
  // latter will try to setup and parse flags, which would bring us back to this
  // setter.
  if (absl::SimpleAtoi(value, &opt_level)) {
    mark_for_compilation_flags->xla_auto_jit_flag
        .optimization_level_single_gpu = opt_level;
    mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
        opt_level;
    return true;
  }

  if (value == "fusible") {
    mark_for_compilation_flags->xla_auto_jit_flag
        .optimization_level_single_gpu = 1;
    mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
        1;
    mark_for_compilation_flags->tf_xla_ops_to_cluster = "FUSIBLE";
    return true;
  }

  absl::string_view value_sv(value);
  if (!absl::ConsumePrefix(&value_sv, "single-gpu(") ||
      !absl::ConsumeSuffix(&value_sv, ")") ||
      !absl::SimpleAtoi(value_sv, &opt_level)) {
    return false;
  }

  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
      opt_level;
  return true;
}

void AppendMarkForCompilationPassFlagsInternal(std::vector<Flag>* flag_list) {
  std::vector<Flag> new_flags = {
      Flag("tf_xla_auto_jit", SetterForXlaAutoJitFlag, "0",
           "Control compilation of operators into XLA computations on CPU and "
           "GPU devices.  0 = use ConfigProto setting; -1 = off; 1 = on for "
           "things very likely to be improved; 2 = on for everything; "
           "(experimental) fusible = only for Tensorflow operations that XLA "
           "knows how to fuse.  "
           "If set to single-gpu(<N>) then this resolves to <N> for single-GPU "
           "graphs (graphs that have at least one node placed on a GPU and no "
           "more than one GPU is in use through the entire graph) and 0 "
           "otherwise.  Experimental."),
      Flag("tf_xla_min_cluster_size",
           &mark_for_compilation_flags->tf_xla_min_cluster_size,
           "Minimum number of operators in an XLA compilation. Ignored for "
           "operators placed on an XLA device or operators explicitly marked "
           "for compilation."),
      Flag("tf_xla_max_cluster_size",
           &mark_for_compilation_flags->tf_xla_max_cluster_size,
           "Maximum number of operators in an XLA compilation."),
      Flag(
          "tf_xla_ops_to_cluster",
          &mark_for_compilation_flags->tf_xla_ops_to_cluster,
          "(experimental) "
          "Limit the operations clustered by XLA to these operations. "
          "If multiple, separate them with commas. Shortcuts: "
          " PW: All point-wise operations."
          " RED: All reduction operations."
          " MISC: Mixed operations."
          " PWRED: TF operations that get converted to PW+RED operation in XLA."
          " REDUCEWINDOW: TF operations like MaxPool/AvgPool that get "
          "converted to ReduceWindow in XLA."
          " REDUCEWINDOWPW: Operation that get converted to ReduceWindow + PW "
          "(LRN, LRNGrad)."
          " BN: TF FusedBatchNorm* operations."
          " FUSIBLE: All TF operations that XLA can fuse (All the above). "
          "You can also put any TF operation name, e.g. 'FUSIBLE,Matmul'."),
      Flag("tf_xla_clustering_debug",
           &mark_for_compilation_flags->tf_xla_clustering_debug,
           "Dump graphs during XLA compilation."),
      Flag("tf_xla_cpu_global_jit",
           &mark_for_compilation_flags->tf_xla_cpu_global_jit,
           "Enables global JIT compilation for CPU via SessionOptions."),
      Flag("tf_xla_clustering_fuel",
           &mark_for_compilation_flags->tf_xla_clustering_fuel,
           "Places an artificial limit on the number of ops marked as "
           "eligible for clustering."),
      Flag("tf_xla_disable_deadness_safety_checks_for_debugging",
           &mark_for_compilation_flags
                ->tf_xla_disable_deadness_safety_checks_for_debugging,
           "Disable deadness related safety checks when clustering (this is "
           "unsound)."),
      Flag("tf_xla_disable_resource_variable_safety_checks_for_debugging",
           &mark_for_compilation_flags
                ->tf_xla_disable_resource_variable_safety_checks_for_debugging,
           "Disable resource variables related safety checks when clustering "
           "(this is unsound).")};
  flag_list->insert(flag_list->end(), new_flags.begin(), new_flags.end());
}

void AllocateAndParseFlags() {
  build_ops_flags = new BuildXlaOpsPassFlags;
  build_ops_flags->tf_xla_enable_lazy_compilation = true;
  build_ops_flags->tf_xla_print_cluster_outputs = false;
  build_ops_flags->tf_xla_check_cluster_input_numerics = false;
  build_ops_flags->tf_xla_check_cluster_output_numerics = false;
  build_ops_flags->tf_xla_disable_constant_folding = false;

  mark_for_compilation_flags = new MarkForCompilationPassFlags;
  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
      0;
  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general = 0;
  mark_for_compilation_flags->tf_xla_min_cluster_size = 4;
  mark_for_compilation_flags->tf_xla_max_cluster_size =
      std::numeric_limits<int32>::max();
  mark_for_compilation_flags->tf_xla_clustering_debug = false;
  mark_for_compilation_flags->tf_xla_cpu_global_jit = false;
  mark_for_compilation_flags->tf_xla_clustering_fuel =
      std::numeric_limits<int64>::max();
  mark_for_compilation_flags
      ->tf_xla_disable_deadness_safety_checks_for_debugging = false;
  mark_for_compilation_flags
      ->tf_xla_disable_resource_variable_safety_checks_for_debugging = false;

  device_flags = new XlaDeviceFlags;
  device_flags->tf_xla_compile_on_demand = false;
  device_flags->tf_xla_enable_xla_devices = true;

  ops_flags = new XlaOpsCommonFlags;
  ops_flags->tf_xla_always_defer_compilation = false;

  jitter_flags = new IntroduceFloatingPointJitterPassFlags;
  jitter_flags->jitter_amount = 1e-5;

  auto setter_for_jitter_tensor_names = [](string sequence) {
    jitter_flags->tensor_names = absl::StrSplit(sequence, ',');
    return true;
  };

  flag_list = new std::vector<Flag>(
      {Flag("tf_xla_enable_lazy_compilation",
            &build_ops_flags->tf_xla_enable_lazy_compilation, ""),
       Flag("tf_xla_print_cluster_outputs",
            &build_ops_flags->tf_xla_print_cluster_outputs,
            "If true then insert Print nodes to print out values produced by "
            "XLA clusters."),
       Flag("tf_xla_check_cluster_input_numerics",
            &build_ops_flags->tf_xla_check_cluster_input_numerics,
            "If true then insert CheckNumerics nodes to to check all cluster "
            "inputs."),
       Flag("tf_xla_check_cluster_output_numerics",
            &build_ops_flags->tf_xla_check_cluster_output_numerics,
            "If true then insert CheckNumerics nodes to to check all cluster "
            "outputs."),
       Flag("tf_xla_disable_constant_folding",
            &build_ops_flags->tf_xla_disable_constant_folding,
            "If true then disables constant folding on TF graph before XLA "
            "compilation."),

       Flag("tf_xla_compile_on_demand", &device_flags->tf_xla_compile_on_demand,
            "Switch a device into 'on-demand' mode, where instead of "
            "autoclustering ops are compiled one by one just-in-time."),

       Flag("tf_xla_enable_xla_devices",
            &device_flags->tf_xla_enable_xla_devices,
            "Generate XLA_* devices, where placing a computation on such a "
            "device"
            "forces compilation by XLA. Deprecated."),

       Flag("tf_xla_always_defer_compilation",
            &ops_flags->tf_xla_always_defer_compilation, ""),

       Flag("tf_introduce_floating_point_jitter_to_tensors",
            setter_for_jitter_tensor_names, "",
            "The Tensors to add the jitter to.  The tensors are named in the "
            "TensorId format of <node name>:<output idx>."),
       Flag("tf_introduce_floating_point_jitter_amount",
            &jitter_flags->jitter_amount,
            "The amount of jitter to introduce.  This amount is added to each "
            "element in the tensors named in `tensor_names.")});

  AppendMarkForCompilationPassFlagsInternal(flag_list);
  xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", *flag_list);
}

}  // namespace

bool SetXlaAutoJitFlagFromFlagString(const string& value) {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return SetterForXlaAutoJitFlag(value);
}

BuildXlaOpsPassFlags* GetBuildXlaOpsPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return build_ops_flags;
}

MarkForCompilationPassFlags* GetMarkForCompilationPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return mark_for_compilation_flags;
}

XlaDeviceFlags* GetXlaDeviceFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return device_flags;
}

const XlaOpsCommonFlags& GetXlaOpsCommonFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return *ops_flags;
}

const IntroduceFloatingPointJitterPassFlags&
GetIntroduceFloatingPointJitterPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return *jitter_flags;
}

void AppendMarkForCompilationPassFlags(std::vector<Flag>* flag_list) {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  AppendMarkForCompilationPassFlagsInternal(flag_list);
}

static bool xla_is_enabled = false;

void SetXlaIsEnabled() { xla_is_enabled = true; }

bool IsXlaEnabled() { return xla_is_enabled; }

}  // namespace tensorflow
<commit_msg>Small docstring fix. This make the example work.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/jit/flags.h"

#include <mutex>  // NOLINT

#include "absl/base/call_once.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/compiler/xla/parse_flags_from_env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/command_line_flags.h"

namespace tensorflow {
namespace {

BuildXlaOpsPassFlags* build_ops_flags;
MarkForCompilationPassFlags* mark_for_compilation_flags;
XlaDeviceFlags* device_flags;
XlaOpsCommonFlags* ops_flags;
IntroduceFloatingPointJitterPassFlags* jitter_flags;

std::vector<Flag>* flag_list;
absl::once_flag flags_init;

bool SetterForXlaAutoJitFlag(const string& value) {
  int32 opt_level;
  // We need to use the mark_for_compilation_flags directly here instead of
  // going via GetMarkForCompilationPassFlags() to avoid infinite recursion. The
  // latter will try to setup and parse flags, which would bring us back to this
  // setter.
  if (absl::SimpleAtoi(value, &opt_level)) {
    mark_for_compilation_flags->xla_auto_jit_flag
        .optimization_level_single_gpu = opt_level;
    mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
        opt_level;
    return true;
  }

  if (value == "fusible") {
    mark_for_compilation_flags->xla_auto_jit_flag
        .optimization_level_single_gpu = 1;
    mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
        1;
    mark_for_compilation_flags->tf_xla_ops_to_cluster = "FUSIBLE";
    return true;
  }

  absl::string_view value_sv(value);
  if (!absl::ConsumePrefix(&value_sv, "single-gpu(") ||
      !absl::ConsumeSuffix(&value_sv, ")") ||
      !absl::SimpleAtoi(value_sv, &opt_level)) {
    return false;
  }

  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
      opt_level;
  return true;
}

void AppendMarkForCompilationPassFlagsInternal(std::vector<Flag>* flag_list) {
  std::vector<Flag> new_flags = {
      Flag("tf_xla_auto_jit", SetterForXlaAutoJitFlag, "0",
           "Control compilation of operators into XLA computations on CPU and "
           "GPU devices.  0 = use ConfigProto setting; -1 = off; 1 = on for "
           "things very likely to be improved; 2 = on for everything; "
           "(experimental) fusible = only for Tensorflow operations that XLA "
           "knows how to fuse.  "
           "If set to single-gpu(<N>) then this resolves to <N> for single-GPU "
           "graphs (graphs that have at least one node placed on a GPU and no "
           "more than one GPU is in use through the entire graph) and 0 "
           "otherwise.  Experimental."),
      Flag("tf_xla_min_cluster_size",
           &mark_for_compilation_flags->tf_xla_min_cluster_size,
           "Minimum number of operators in an XLA compilation. Ignored for "
           "operators placed on an XLA device or operators explicitly marked "
           "for compilation."),
      Flag("tf_xla_max_cluster_size",
           &mark_for_compilation_flags->tf_xla_max_cluster_size,
           "Maximum number of operators in an XLA compilation."),
      Flag(
          "tf_xla_ops_to_cluster",
          &mark_for_compilation_flags->tf_xla_ops_to_cluster,
          "(experimental) "
          "Limit the operations clustered by XLA to these operations. "
          "If multiple, separate them with commas. Shortcuts: "
          " PW: All point-wise operations."
          " RED: All reduction operations."
          " MISC: Mixed operations."
          " PWRED: TF operations that get converted to PW+RED operation in XLA."
          " REDUCEWINDOW: TF operations like MaxPool/AvgPool that get "
          "converted to ReduceWindow in XLA."
          " REDUCEWINDOWPW: Operation that get converted to ReduceWindow + PW "
          "(LRN, LRNGrad)."
          " BN: TF FusedBatchNorm* operations."
          " FUSIBLE: All TF operations that XLA can fuse (All the above). "
          "You can also put any TF operation name, e.g. 'FUSIBLE,MatMul'."),
      Flag("tf_xla_clustering_debug",
           &mark_for_compilation_flags->tf_xla_clustering_debug,
           "Dump graphs during XLA compilation."),
      Flag("tf_xla_cpu_global_jit",
           &mark_for_compilation_flags->tf_xla_cpu_global_jit,
           "Enables global JIT compilation for CPU via SessionOptions."),
      Flag("tf_xla_clustering_fuel",
           &mark_for_compilation_flags->tf_xla_clustering_fuel,
           "Places an artificial limit on the number of ops marked as "
           "eligible for clustering."),
      Flag("tf_xla_disable_deadness_safety_checks_for_debugging",
           &mark_for_compilation_flags
                ->tf_xla_disable_deadness_safety_checks_for_debugging,
           "Disable deadness related safety checks when clustering (this is "
           "unsound)."),
      Flag("tf_xla_disable_resource_variable_safety_checks_for_debugging",
           &mark_for_compilation_flags
                ->tf_xla_disable_resource_variable_safety_checks_for_debugging,
           "Disable resource variables related safety checks when clustering "
           "(this is unsound).")};
  flag_list->insert(flag_list->end(), new_flags.begin(), new_flags.end());
}

void AllocateAndParseFlags() {
  build_ops_flags = new BuildXlaOpsPassFlags;
  build_ops_flags->tf_xla_enable_lazy_compilation = true;
  build_ops_flags->tf_xla_print_cluster_outputs = false;
  build_ops_flags->tf_xla_check_cluster_input_numerics = false;
  build_ops_flags->tf_xla_check_cluster_output_numerics = false;
  build_ops_flags->tf_xla_disable_constant_folding = false;

  mark_for_compilation_flags = new MarkForCompilationPassFlags;
  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
      0;
  mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general = 0;
  mark_for_compilation_flags->tf_xla_min_cluster_size = 4;
  mark_for_compilation_flags->tf_xla_max_cluster_size =
      std::numeric_limits<int32>::max();
  mark_for_compilation_flags->tf_xla_clustering_debug = false;
  mark_for_compilation_flags->tf_xla_cpu_global_jit = false;
  mark_for_compilation_flags->tf_xla_clustering_fuel =
      std::numeric_limits<int64>::max();
  mark_for_compilation_flags
      ->tf_xla_disable_deadness_safety_checks_for_debugging = false;
  mark_for_compilation_flags
      ->tf_xla_disable_resource_variable_safety_checks_for_debugging = false;

  device_flags = new XlaDeviceFlags;
  device_flags->tf_xla_compile_on_demand = false;
  device_flags->tf_xla_enable_xla_devices = true;

  ops_flags = new XlaOpsCommonFlags;
  ops_flags->tf_xla_always_defer_compilation = false;

  jitter_flags = new IntroduceFloatingPointJitterPassFlags;
  jitter_flags->jitter_amount = 1e-5;

  auto setter_for_jitter_tensor_names = [](string sequence) {
    jitter_flags->tensor_names = absl::StrSplit(sequence, ',');
    return true;
  };

  flag_list = new std::vector<Flag>(
      {Flag("tf_xla_enable_lazy_compilation",
            &build_ops_flags->tf_xla_enable_lazy_compilation, ""),
       Flag("tf_xla_print_cluster_outputs",
            &build_ops_flags->tf_xla_print_cluster_outputs,
            "If true then insert Print nodes to print out values produced by "
            "XLA clusters."),
       Flag("tf_xla_check_cluster_input_numerics",
            &build_ops_flags->tf_xla_check_cluster_input_numerics,
            "If true then insert CheckNumerics nodes to to check all cluster "
            "inputs."),
       Flag("tf_xla_check_cluster_output_numerics",
            &build_ops_flags->tf_xla_check_cluster_output_numerics,
            "If true then insert CheckNumerics nodes to to check all cluster "
            "outputs."),
       Flag("tf_xla_disable_constant_folding",
            &build_ops_flags->tf_xla_disable_constant_folding,
            "If true then disables constant folding on TF graph before XLA "
            "compilation."),

       Flag("tf_xla_compile_on_demand", &device_flags->tf_xla_compile_on_demand,
            "Switch a device into 'on-demand' mode, where instead of "
            "autoclustering ops are compiled one by one just-in-time."),

       Flag("tf_xla_enable_xla_devices",
            &device_flags->tf_xla_enable_xla_devices,
            "Generate XLA_* devices, where placing a computation on such a "
            "device"
            "forces compilation by XLA. Deprecated."),

       Flag("tf_xla_always_defer_compilation",
            &ops_flags->tf_xla_always_defer_compilation, ""),

       Flag("tf_introduce_floating_point_jitter_to_tensors",
            setter_for_jitter_tensor_names, "",
            "The Tensors to add the jitter to.  The tensors are named in the "
            "TensorId format of <node name>:<output idx>."),
       Flag("tf_introduce_floating_point_jitter_amount",
            &jitter_flags->jitter_amount,
            "The amount of jitter to introduce.  This amount is added to each "
            "element in the tensors named in `tensor_names.")});

  AppendMarkForCompilationPassFlagsInternal(flag_list);
  xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", *flag_list);
}

}  // namespace

bool SetXlaAutoJitFlagFromFlagString(const string& value) {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return SetterForXlaAutoJitFlag(value);
}

BuildXlaOpsPassFlags* GetBuildXlaOpsPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return build_ops_flags;
}

MarkForCompilationPassFlags* GetMarkForCompilationPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return mark_for_compilation_flags;
}

XlaDeviceFlags* GetXlaDeviceFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return device_flags;
}

const XlaOpsCommonFlags& GetXlaOpsCommonFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return *ops_flags;
}

const IntroduceFloatingPointJitterPassFlags&
GetIntroduceFloatingPointJitterPassFlags() {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  return *jitter_flags;
}

void AppendMarkForCompilationPassFlags(std::vector<Flag>* flag_list) {
  absl::call_once(flags_init, &AllocateAndParseFlags);
  AppendMarkForCompilationPassFlagsInternal(flag_list);
}

static bool xla_is_enabled = false;

void SetXlaIsEnabled() { xla_is_enabled = true; }

bool IsXlaEnabled() { return xla_is_enabled; }

}  // namespace tensorflow
<|endoftext|>


<commit_before>#include <realm/group_shared.hpp>
#include <realm/commit_log.hpp>
#include "../test.hpp"

#include <stdio.h>
#include <fstream>

using namespace realm;
using namespace realm::util;

struct InputStreamAdapter : _impl::InputStream {
    InputStreamAdapter(std::ifstream& s) : m_stream(s) {}

    size_t read(char* buffer, size_t size) final
    {
        return m_stream.read(buffer, size).gcount();
    }

    std::ifstream& m_stream;
};

int main(int argc, const char* argv[])
{
    if (argc == 1) {
        fprintf(stderr, "Usage: %s <LOGFILE>\n(where <LOGFILE> is a transaction log file that will be replayed.)", argv[0]);
        exit(1);
    }

    std::ifstream in{argv[1]};
    if (!in.is_open()) {
        fprintf(stderr, "Could not open file for reading: %s\n", argv[1]);
        exit(1);
    }

    InputStreamAdapter in_a{in};
    std::vector<char> buffer;
    buffer.resize(1024);
    _impl::NoCopyInputStreamAdaptor in_aa{in_a, buffer.data(), buffer.size()};

    test_util::unit_test::TestDetails test_details;
    test_details.test_index = 0;
    test_details.suite_name = "FuzzyTest";
    test_details.test_name = "TransactLogApplier";
    test_details.file_name = __FILE__;
    test_details.line_number = __LINE__;

    Group group;

    try {
        Replication::apply_changeset(in_aa, group);
    }
    catch (_impl::TransactLogParser::BadTransactLog) {
        return 0;
    }

    return 0;
}
<commit_msg>Remove old unused code, preventing compile of fuzz_transact_log.cpp<commit_after>#include <realm/group_shared.hpp>
#include <realm/commit_log.hpp>
#include "../test.hpp"

#include <stdio.h>
#include <fstream>

using namespace realm;
using namespace realm::util;

struct InputStreamAdapter : _impl::InputStream {
    InputStreamAdapter(std::ifstream& s) : m_stream(s) {}

    size_t read(char* buffer, size_t size) final
    {
        return m_stream.read(buffer, size).gcount();
    }

    std::ifstream& m_stream;
};

int main(int argc, const char* argv[])
{
    if (argc == 1) {
        fprintf(stderr, "Usage: %s <LOGFILE>\n(where <LOGFILE> is a transaction log file that will be replayed.)", argv[0]);
        exit(1);
    }

    std::ifstream in{argv[1]};
    if (!in.is_open()) {
        fprintf(stderr, "Could not open file for reading: %s\n", argv[1]);
        exit(1);
    }

    InputStreamAdapter in_a{in};
    std::vector<char> buffer;
    buffer.resize(1024);
    _impl::NoCopyInputStreamAdaptor in_aa{in_a, buffer.data(), buffer.size()};

    Group group;

    try {
        Replication::apply_changeset(in_aa, group);
    }
    catch (_impl::TransactLogParser::BadTransactLog) {
        return 0;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "nanocv.h"
#include "models/forward_network.h"
#include "task.h"
#include <boost/program_options.hpp>

namespace ncv
{
        class dummy_tast_t : public ncv::task_t
        {
        public:

                NANOCV_MAKE_CLONABLE(dummy_tast_t)

                // constructor
                dummy_tast_t(const string_t& = string_t())
                        :       task_t("test task")
                {
                }

                // create samples
                void resize(size_t samples)
                {
                        m_images.clear();
                        m_samples.clear();

                        for (size_t i = 0; i < samples; i ++)
                        {
                                sample_t sample(m_images.size(), sample_region(0, 0));
                                sample.m_label = "label";
                                sample.m_target = ncv::class_target(i % n_outputs(), n_outputs());
                                sample.m_fold = { 0, protocol::train };
                                m_samples.push_back(sample);

                                image_t image(n_rows(), n_cols(), color());
                                m_images.push_back(image);
                        }
                }

                // load images from the given directory
                virtual bool load(const string_t&) { return true; }

                // access functions
                virtual size_t n_rows() const { return 28; }
                virtual size_t n_cols() const { return 28; }
                virtual size_t n_outputs() const { return 10; }
                virtual size_t n_folds() const { return 1; }
                virtual color_mode color() const { return color_mode::luma; }
        };
}

int main(int argc, char *argv[])
{
        ncv::init();

        using namespace ncv;

        // parse the command line
        boost::program_options::options_description po_desc("", 160);
        po_desc.add_options()("help,h", "test program");
        po_desc.add_options()("threads,t",
                boost::program_options::value<size_t>()->default_value(1),
                "number of threads to use [1, 16], 0 - use all available threads");
        po_desc.add_options()("samples,s",
                boost::program_options::value<size_t>()->default_value(100000),
                "number of samples to use [1000, 100000]");
        po_desc.add_options()("forward",
                "evaluate the \'forward\' pass (output)");
        po_desc.add_options()("backward",
                "evaluate the \'backward' pass (gradient)");

        boost::program_options::variables_map po_vm;
        boost::program_options::store(
                boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
                po_vm);
        boost::program_options::notify(po_vm);

        // check arguments and options
        if (	po_vm.empty() ||
                po_vm.count("help"))
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        const size_t cmd_threads = math::clamp(po_vm["threads"].as<size_t>(), 0, 16);
        const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 100 * 1000);
        const bool cmd_forward = po_vm.count("forward");
        const bool cmd_backward = po_vm.count("backward");

        if (!cmd_forward && !cmd_backward)
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        dummy_tast_t task;
        task.resize(cmd_samples);

        const size_t cmd_outputs = task.n_outputs();

        const string_t lmodel0;
        const string_t lmodel1 = lmodel0 + "linear:dims=128;act-snorm;";
        const string_t lmodel2 = lmodel1 + "linear:dims=64;act-snorm;";
        const string_t lmodel3 = lmodel2 + "linear:dims=32;act-snorm;";
        const string_t lmodel4 = lmodel3 + "linear:dims=16;act-snorm;";
        const string_t lmodel5 = lmodel4 + "linear:dims=8;act-snorm;";

        string_t cmodel;
        cmodel = cmodel + "conv:dims=16,rows=7,cols=7;act-snorm;pool-max;";
        cmodel = cmodel + "conv:dims=32,rows=5,cols=5;act-snorm;pool-max;";
        cmodel = cmodel + "conv:dims=64,rows=3,cols=3;act-snorm;";

        const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";softmax:type=global;";

        strings_t cmd_networks =
        {
                lmodel0 + outlayer,
                lmodel1 + outlayer,
                lmodel2 + outlayer,
                lmodel3 + outlayer,
                lmodel4 + outlayer,
                lmodel5 + outlayer,
                cmodel + outlayer
        };

        const rloss_t rloss = loss_manager_t::instance().get("class-ratio");
        assert(rloss);
        const loss_t& loss = *rloss;

        for (const string_t& cmd_network : cmd_networks)
        {
                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                forward_network_t model(cmd_network);
                model.resize(task, true);

                // process the samples
                if (cmd_forward)
                {
                        accumulator_t ldata(model, cmd_threads, "l2-reg", criterion_t::type::value, 0.1);

                        const ncv::timer_t timer;
                        ldata.update(task, task.samples(), loss);

                        log_info() << "<<< processed [" << ldata.count() << "] forward samples in " << timer.elapsed() << ".";
                }

                if (cmd_backward)
                {
                        accumulator_t gdata(model, cmd_threads, "l2-reg", criterion_t::type::vgrad, 0.1);

                        const ncv::timer_t timer;
                        gdata.update(task, task.samples(), loss);

                        log_info() << "<<< processed [" << gdata.count() << "] backward samples in " << timer.elapsed() << ".";
                }
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<commit_msg>sample randomly for the test program<commit_after>#include "nanocv.h"
#include "models/forward_network.h"
#include "task.h"
#include <boost/program_options.hpp>

namespace ncv
{
        class dummy_tast_t : public ncv::task_t
        {
        public:

                NANOCV_MAKE_CLONABLE(dummy_tast_t)

                // constructor
                dummy_tast_t(const string_t& = string_t())
                        :       task_t("test task")
                {
                }

                // create samples
                void resize(size_t samples)
                {
                        m_images.clear();
                        m_samples.clear();

                        for (size_t i = 0; i < samples; i ++)
                        {
                                sample_t sample(m_images.size(), sample_region(0, 0));
                                sample.m_label = "label";
                                sample.m_target = ncv::class_target(i % n_outputs(), n_outputs());
                                sample.m_fold = { 0, protocol::train };
                                m_samples.push_back(sample);

                                image_t image(n_rows(), n_cols(), color());
                                m_images.push_back(image);
                        }
                }

                // load images from the given directory
                virtual bool load(const string_t&) { return true; }

                // access functions
                virtual size_t n_rows() const { return 28; }
                virtual size_t n_cols() const { return 28; }
                virtual size_t n_outputs() const { return 10; }
                virtual size_t n_folds() const { return 1; }
                virtual color_mode color() const { return color_mode::luma; }
        };
}

int main(int argc, char *argv[])
{
        ncv::init();

        using namespace ncv;

        // parse the command line
        boost::program_options::options_description po_desc("", 160);
        po_desc.add_options()("help,h", "test program");
        po_desc.add_options()("threads,t",
                boost::program_options::value<size_t>()->default_value(1),
                "number of threads to use [1, 16], 0 - use all available threads");
        po_desc.add_options()("samples,s",
                boost::program_options::value<size_t>()->default_value(100000),
                "number of samples to use [1000, 100000]");
        po_desc.add_options()("forward",
                "evaluate the \'forward\' pass (output)");
        po_desc.add_options()("backward",
                "evaluate the \'backward' pass (gradient)");

        boost::program_options::variables_map po_vm;
        boost::program_options::store(
                boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
                po_vm);
        boost::program_options::notify(po_vm);

        // check arguments and options
        if (	po_vm.empty() ||
                po_vm.count("help"))
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        const size_t cmd_threads = math::clamp(po_vm["threads"].as<size_t>(), 0, 16);
        const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 100 * 1000);
        const bool cmd_forward = po_vm.count("forward");
        const bool cmd_backward = po_vm.count("backward");

        if (!cmd_forward && !cmd_backward)
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        dummy_tast_t task;
        task.resize(cmd_samples * 100);

        const size_t cmd_outputs = task.n_outputs();

        const string_t lmodel0;
        const string_t lmodel1 = lmodel0 + "linear:dims=128;act-snorm;";
        const string_t lmodel2 = lmodel1 + "linear:dims=64;act-snorm;";
        const string_t lmodel3 = lmodel2 + "linear:dims=32;act-snorm;";
        const string_t lmodel4 = lmodel3 + "linear:dims=16;act-snorm;";
        const string_t lmodel5 = lmodel4 + "linear:dims=8;act-snorm;";

        string_t cmodel;
        cmodel = cmodel + "conv:dims=16,rows=7,cols=7;act-snorm;pool-max;";
        cmodel = cmodel + "conv:dims=32,rows=5,cols=5;act-snorm;pool-max;";
        cmodel = cmodel + "conv:dims=64,rows=3,cols=3;act-snorm;";

        const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";softmax:type=global;";

        strings_t cmd_networks =
        {
                lmodel0 + outlayer,
                lmodel1 + outlayer,
                lmodel2 + outlayer,
                lmodel3 + outlayer,
                lmodel4 + outlayer,
                lmodel5 + outlayer,
                cmodel + outlayer
        };

        const rloss_t rloss = loss_manager_t::instance().get("class-ratio");
        assert(rloss);
        const loss_t& loss = *rloss;

        for (const string_t& cmd_network : cmd_networks)
        {
                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                forward_network_t model(cmd_network);
                model.resize(task, true);

                sampler_t sampler(task);
                sampler.setup(sampler_t::stype::uniform, cmd_samples).setup(sampler_t::atype::annotated);

                // process the samples
                if (cmd_forward)
                {
                        accumulator_t ldata(model, cmd_threads, "l2-reg", criterion_t::type::value, 0.1);

                        const ncv::timer_t timer;
                        ldata.update(task, sampler.get(), loss);

                        log_info() << "<<< processed [" << ldata.count() << "] forward samples in " << timer.elapsed() << ".";
                }

                if (cmd_backward)
                {
                        accumulator_t gdata(model, cmd_threads, "l2-reg", criterion_t::type::vgrad, 0.1);

                        const ncv::timer_t timer;
                        gdata.update(task, sampler.get(), loss);

                        log_info() << "<<< processed [" << gdata.count() << "] backward samples in " << timer.elapsed() << ".";
                }
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<|endoftext|>