<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 16:17:37 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "Client.hxx"

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#include <toolkit/helper/vclunohelper.hxx>

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using namespace com::sun::star;

namespace sd {

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

Client::Client(SdrOle2Obj* pObj, ViewShell* pViewShell, ::Window* pWindow) :
    SfxInPlaceClient(pViewShell->GetViewShell(), pWindow, pObj->GetAspect() ),
    pViewShell(pViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
    SetObject( pObj->GetObjRef() );
    DBG_ASSERT( GetObject().is(), "No object connected!" );
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

Client::~Client()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void Client::RequestNewObjectArea( Rectangle& aObjRect )
{
    ::sd::View* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );
    if (!aWorkArea.IsInside(aObjRect))
    {
        // correct position
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);
    }
}

void Client::ObjectAreaChanged()
{
    ::sd::View* pView = pViewShell->GetView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        // no need to check for changes, this method is called only if the area really changed
        pObj->SetLogicRect( GetScaledObjArea() );
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void Client::ViewChanged()
{
    //TODO/LATER: should we try to avoid the recalculation of the visareasize
    //if we know that it didn't change?
    if (pViewShell->GetActiveWindow())
    {
        ::sd::View* pView = pViewShell->GetView();
        if (pView)
        {
            // TODO/LEAN: maybe we can do this without requesting the VisualArea?
            // working with the visual area might need running state
            svt::EmbeddedObjectRef::TryRunningState( GetObject() );
            MapMode             aMap100( MAP_100TH_MM );
            MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( GetObject()->getMapUnit( GetAspect() ) );
            Rectangle           aVisArea;
            awt::Size aSz = GetObject()->getVisualAreaSize( GetAspect() );
            aVisArea.SetSize( Size( aSz.Width, aSz.Height ) );
            aVisArea = OutputDevice::LogicToLogic( aVisArea, aMapUnit, aMap100 );
            Rectangle           aLogicRect( pSdrOle2Obj->GetLogicRect() );
            Size                aScaledSize( static_cast< long >( GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ),
                                                static_cast< long >( GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) );
            if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) !=
                Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) )
            {
                pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) );
                pSdrOle2Obj->BroadcastObjectChange();
            }
            else
                pSdrOle2Obj->ActionChanged();
        }
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void Client::MakeVisible()
{
    if (pViewShell->ISA(DrawViewShell))
    {
        static_cast<DrawViewShell*>(pViewShell)->MakeVisible(
            pSdrOle2Obj->GetLogicRect(),
            *pViewShell->GetActiveWindow());
    }
}

} // end of namespace sd

<commit_msg>INTEGRATION: CWS mav15 (1.10.62); FILE MERGED 2005/01/21 13:02:36 mav 1.10.62.1: #i39746# cache the visual area size for OLE objects and switch own objects to RUNNING state automatically<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-31 09:04: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): _______________________________________
 *
 *
 ************************************************************************/

#include "Client.hxx"

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#include <toolkit/helper/vclunohelper.hxx>

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using namespace com::sun::star;

namespace sd {

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

Client::Client(SdrOle2Obj* pObj, ViewShell* pViewShell, ::Window* pWindow) :
    SfxInPlaceClient(pViewShell->GetViewShell(), pWindow, pObj->GetAspect() ),
    pViewShell(pViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
    SetObject( pObj->GetObjRef() );
    DBG_ASSERT( GetObject().is(), "No object connected!" );
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

Client::~Client()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void Client::RequestNewObjectArea( Rectangle& aObjRect )
{
    ::sd::View* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );
    if (!aWorkArea.IsInside(aObjRect))
    {
        // correct position
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);
    }
}

void Client::ObjectAreaChanged()
{
    ::sd::View* pView = pViewShell->GetView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        // no need to check for changes, this method is called only if the area really changed
        pObj->SetLogicRect( GetScaledObjArea() );
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void Client::ViewChanged()
{
    //TODO/LATER: should we try to avoid the recalculation of the visareasize
    //if we know that it didn't change?
    if (pViewShell->GetActiveWindow())
    {
        ::sd::View* pView = pViewShell->GetView();
        if (pView)
        {
            // TODO/LEAN: maybe we can do this without requesting the VisualArea?
            // working with the visual area might need running state, so the object may switch itself to this state
            MapMode             aMap100( MAP_100TH_MM );
            MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( GetObject()->getMapUnit( GetAspect() ) );
            Rectangle           aVisArea;
            awt::Size aSz = GetObject()->getVisualAreaSize( GetAspect() );
            aVisArea.SetSize( Size( aSz.Width, aSz.Height ) );
            aVisArea = OutputDevice::LogicToLogic( aVisArea, aMapUnit, aMap100 );
            Rectangle           aLogicRect( pSdrOle2Obj->GetLogicRect() );
            Size                aScaledSize( static_cast< long >( GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ),
                                                static_cast< long >( GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) );
            if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) !=
                Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) )
            {
                pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) );
                pSdrOle2Obj->BroadcastObjectChange();
            }
            else
                pSdrOle2Obj->ActionChanged();
        }
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void Client::MakeVisible()
{
    if (pViewShell->ISA(DrawViewShell))
    {
        static_cast<DrawViewShell*>(pViewShell)->MakeVisible(
            pSdrOle2Obj->GetLogicRect(),
            *pViewShell->GetActiveWindow());
    }
}

} // end of namespace sd

<|endoftext|>


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

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif

namespace sd
{

class DialogListBox : public Control
{
private:
    ScrollBar*          mpHScrollBar;
    ScrollBar*          mpVScrollBar;
    ScrollBarBox*       mpScrollBarBox;
    ::Window*           mpChild;
    bool                mbVScroll;
    bool                mbHScroll;
    bool                mbAutoHScroll;
    Size                maMinSize, maInnerSize;

protected:
    virtual void        GetFocus();
    virtual void        StateChanged( StateChangedType nType );

    long                Notify( NotifyEvent& rNEvt );

    void                ImplResizeControls();
    void                ImplCheckScrollBars();
    void                ImplInitScrollBars();
    void                ImplResizeChild();

    DECL_LINK(          ScrollBarHdl, ScrollBar* );

public:
                    DialogListBox( ::Window* pParent, WinBits nWinStyle );
                    ~DialogListBox();

    void            SetChildWindow( ::Window* pChild, const Size& rMinSize );

    ::Window*           GetPreferredKeyInputWindow();
    void            Resize();

};

} //  namespace sd

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

#include <vcl/ctrl.hxx>
#include <vcl/scrbar.hxx>

namespace sd
{

class DialogListBox : public Control
{
private:
    ScrollBar*          mpHScrollBar;
    ScrollBar*          mpVScrollBar;
    ScrollBarBox*       mpScrollBarBox;
    ::Window*           mpChild;
    bool                mbVScroll;
    bool                mbHScroll;
    bool                mbAutoHScroll;
    Size                maMinSize, maInnerSize;

protected:
    virtual void        GetFocus();
    virtual void        StateChanged( StateChangedType nType );

    long                Notify( NotifyEvent& rNEvt );

    void                ImplResizeControls();
    void                ImplCheckScrollBars();
    void                ImplInitScrollBars();
    void                ImplResizeChild();

    DECL_LINK(          ScrollBarHdl, ScrollBar* );

public:
                    DialogListBox( ::Window* pParent, WinBits nWinStyle );
                    ~DialogListBox();

    void            SetChildWindow( ::Window* pChild, const Size& rMinSize );

    ::Window*           GetPreferredKeyInputWindow();
    void            Resize();

};

} //  namespace sd

// SD_DIALOGLISTBOX_HXX
#endif
<|endoftext|>


<commit_before>#ifndef _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
#define _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_

#include <string>

#include "sdd/values/bitset.hh"

namespace sdd { namespace conf {

/*-------------------------------------------------------------------------------------------*/

struct default_parameters
{
  typedef unsigned short alpha_size_type;
  typedef unsigned short operands_size_type;
};

/*-------------------------------------------------------------------------------------------*/

struct conf0
  : public default_parameters
{
  typedef std::string        Identifier;
  typedef unsigned char      Variable;
  typedef values::bitset<64> Values;
};

/*-------------------------------------------------------------------------------------------*/

}} // namespace sdd::conf

#endif // _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
<commit_msg>Remove unused typedef.<commit_after>#ifndef _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
#define _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_

#include <string>

#include "sdd/values/bitset.hh"

namespace sdd { namespace conf {

/*-------------------------------------------------------------------------------------------*/

struct default_parameters
{
  typedef unsigned short alpha_size_type;
  typedef unsigned short operands_size_type;
};

/*-------------------------------------------------------------------------------------------*/

struct conf0
  : public default_parameters
{
  typedef unsigned char      Variable;
  typedef values::bitset<64> Values;
};

/*-------------------------------------------------------------------------------------------*/

}} // namespace sdd::conf

#endif // _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Manasij Mukherjee  <manasij7479@gmail.com>
// author:  Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..)
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"

namespace {
  static const char annoTag[] = "$clingAutoload$";
  static const size_t lenAnnoTag = sizeof(annoTag) - 1;
}

using namespace clang;

namespace cling {

  void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name,
                                llvm::StringRef header) {
    Sema& sema= m_Interpreter->getSema();

    unsigned id
      = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
                                                 "Note: '%0' can be found in %1");
/*    unsigned idn //TODO: To be enabled after we have a way to get the full path
      = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
                                                "Type : %0 , Full Path: %1")*/;

    if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag)))
      sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag);

  }

  bool AutoloadCallback::LookupObject (TagDecl *t) {
    if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>())
      report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
    return false;
  }

  class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> {
  private:
    bool m_IsStoringState;
    AutoloadCallback::FwdDeclsMap* m_Map;
    clang::Preprocessor* m_PP;
    const clang::FileEntry* m_PrevFE;
    std::string m_PrevFileName;
  private:
    void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) {

      assert(!annotation.empty() && "Empty annotation!");
      if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) {
        // not an autoload annotation.
        return;
      }

      assert(m_PP);

      const FileEntry* FE = 0;
      SourceLocation fileNameLoc;
      bool isAngled = false;
      const DirectoryLookup* LookupFrom = 0;
      const DirectoryLookup* CurDir = 0;
      llvm::StringRef FileName = annotation.drop_front(lenAnnoTag);
      if (FileName.equals(m_PrevFileName))
        FE = m_PrevFE;
      else {
        FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled,
                              LookupFrom, CurDir, /*SearchPath*/0,
                              /*RelativePath*/ 0, /*suggestedModule*/0,
                              /*SkipCache*/ false, /*OpenFile*/ false,
                              /*CacheFail*/ true);
        m_PrevFE = FE;
        m_PrevFileName = FileName;
      }

      assert(FE && "Must have a valid FileEntry");
      if (FE) {
        auto& Vec = (*m_Map)[FE];
        Vec.push_back(decl);
      }
    }

  public:
    AutoloadingVisitor():
      m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {}
    void RemoveDefaultArgsOf(Decl* D) {
      //D = D->getMostRecentDecl();
      TraverseDecl(D);
      //while ((D = D->getPreviousDecl()))
      //  TraverseDecl(D);
    }

    void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
                                Preprocessor& PP) {
      m_IsStoringState = true;
      m_Map = ↦
      m_PP = &PP;
      TraverseDecl(D);
      m_PP = 0;
      m_Map = 0;
      m_IsStoringState = false;
    }

    bool shouldVisitTemplateInstantiations() { return true; }

    bool VisitDecl(Decl* D) {
      if (!m_IsStoringState)
        return true;

      if (!D->hasAttr<AnnotateAttr>())
        return true;

      AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
      if (!attr)
        return true;

      switch (D->getKind()) {
      default:
        InsertIntoAutoloadingState(D, attr->getAnnotation());
        break;
      case Decl::Enum:
        // EnumDecls have extra information 2 chars after the filename used
        // for extra fixups.
          EnumDecl* ED = cast<EnumDecl>(D);
          if (ED->isFixed()) {
            StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation();
            char ch = str.back();
//            str.drop_back(2);
            ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str);
            struct EnumDeclDerived: public EnumDecl {
              static void setFixed(EnumDecl* ED, bool value = true) {
                ((EnumDeclDerived*)ED)->IsFixed = value;
              }
            };

            if (ch != '1')
              EnumDeclDerived::setFixed(ED, false);
          }
        InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
        break;
      }

      return true;
    }

    bool VisitCXXRecordDecl(CXXRecordDecl* D) {
      if (!D->hasAttr<AnnotateAttr>())
        return true;

      VisitDecl(D);

      if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate())
        return VisitTemplateDecl(TmplD);
      return true;
    }

    bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitTemplateDecl(TemplateDecl* D) {
      if (D->getTemplatedDecl() &&
          !D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
        return true;

      VisitDecl(D);

      for(auto P: D->getTemplateParameters()->asArray())
        TraverseDecl(P);
      return true;
    }

    bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitParmVarDecl(ParmVarDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArg())
        D->setDefaultArg(nullptr);
      return true;
    }
  };

  void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
                          const clang::Token &IncludeTok,
                          llvm::StringRef FileName,
                          bool IsAngled,
                          clang::CharSourceRange FilenameRange,
                          const clang::FileEntry *File,
                          llvm::StringRef SearchPath,
                          llvm::StringRef RelativePath,
                          const clang::Module *Imported) {
    // If File is 0 this means that the #included file doesn't exist.
    if (!File)
      return;

    auto found = m_Map.find(File);
    if (found == m_Map.end())
     return; // nothing to do, file not referred in any annotation

    AutoloadingVisitor defaultArgsCleaner;
    for (auto D : found->second) {
      defaultArgsCleaner.RemoveDefaultArgsOf(D);
    }
    // Don't need to keep track of cleaned up decls from file.
    m_Map.erase(found);
  }

  AutoloadCallback::~AutoloadCallback() {
  }

  void AutoloadCallback::TransactionCommitted(const Transaction &T) {
    if (T.decls_begin() == T.decls_end())
      return;
    if (T.decls_begin()->m_DGR.isNull())
      return;

    if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
      if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
        AutoloadingVisitor defaultArgsStateCollector;
        Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
        for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
             I != E; ++I) {
          Transaction::DelayCallInfo DCI = *I;

          // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
          //   continue;
          if (DCI.m_DGR.isNull())
            continue;

          if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
            if (ND->getIdentifier()
                && ND->getName().equals("__Cling_Autoloading_Map")) {

              for (Transaction::const_iterator I = T.decls_begin(),
                     E = T.decls_end(); I != E; ++I) {
                Transaction::DelayCallInfo DCI = *I;
                for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
                       JE = DCI.m_DGR.end(); J != JE; ++J) {
                    defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
                }
              }
            }

        }
      }
  }

} //end namespace cling
<commit_msg>Document crucial data member.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Manasij Mukherjee  <manasij7479@gmail.com>
// author:  Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..)
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"

namespace {
  static const char annoTag[] = "$clingAutoload$";
  static const size_t lenAnnoTag = sizeof(annoTag) - 1;
}

using namespace clang;

namespace cling {

  void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name,
                                llvm::StringRef header) {
    Sema& sema= m_Interpreter->getSema();

    unsigned id
      = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
                                                 "Note: '%0' can be found in %1");
/*    unsigned idn //TODO: To be enabled after we have a way to get the full path
      = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
                                                "Type : %0 , Full Path: %1")*/;

    if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag)))
      sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag);

  }

  bool AutoloadCallback::LookupObject (TagDecl *t) {
    if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>())
      report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
    return false;
  }

  class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> {
  private:
    ///\brief Flag determining the visitor's actions. If tru, register autoload
    /// entries, i.e. remember the connection between filename to declaration
    /// that needs to be updated on #include of the filename.
    /// If false, react on an #include by adjusting the forward decls, e.g. by
    /// removing the default tremplate arguments (that will now be provided by
    /// the definition read from the include) and by removing enum declarations
    /// that would otherwise be duplicates.
    bool m_IsStoringState;
    AutoloadCallback::FwdDeclsMap* m_Map;
    clang::Preprocessor* m_PP;
    const clang::FileEntry* m_PrevFE;
    std::string m_PrevFileName;
  private:
    void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) {

      assert(!annotation.empty() && "Empty annotation!");
      if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) {
        // not an autoload annotation.
        return;
      }

      assert(m_PP);

      const FileEntry* FE = 0;
      SourceLocation fileNameLoc;
      bool isAngled = false;
      const DirectoryLookup* LookupFrom = 0;
      const DirectoryLookup* CurDir = 0;
      llvm::StringRef FileName = annotation.drop_front(lenAnnoTag);
      if (FileName.equals(m_PrevFileName))
        FE = m_PrevFE;
      else {
        FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled,
                              LookupFrom, CurDir, /*SearchPath*/0,
                              /*RelativePath*/ 0, /*suggestedModule*/0,
                              /*SkipCache*/ false, /*OpenFile*/ false,
                              /*CacheFail*/ true);
        m_PrevFE = FE;
        m_PrevFileName = FileName;
      }

      assert(FE && "Must have a valid FileEntry");
      if (FE) {
        auto& Vec = (*m_Map)[FE];
        Vec.push_back(decl);
      }
    }

  public:
    AutoloadingVisitor():
      m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {}
    void RemoveDefaultArgsOf(Decl* D) {
      //D = D->getMostRecentDecl();
      TraverseDecl(D);
      //while ((D = D->getPreviousDecl()))
      //  TraverseDecl(D);
    }

    void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
                                Preprocessor& PP) {
      m_IsStoringState = true;
      m_Map = ↦
      m_PP = &PP;
      TraverseDecl(D);
      m_PP = 0;
      m_Map = 0;
      m_IsStoringState = false;
    }

    bool shouldVisitTemplateInstantiations() { return true; }

    bool VisitDecl(Decl* D) {
      if (!m_IsStoringState)
        return true;

      if (!D->hasAttr<AnnotateAttr>())
        return true;

      AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
      if (!attr)
        return true;

      switch (D->getKind()) {
      default:
        InsertIntoAutoloadingState(D, attr->getAnnotation());
        break;
      case Decl::Enum:
        // EnumDecls have extra information 2 chars after the filename used
        // for extra fixups.
          EnumDecl* ED = cast<EnumDecl>(D);
          if (ED->isFixed()) {
            StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation();
            char ch = str.back();
//            str.drop_back(2);
            ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str);
            struct EnumDeclDerived: public EnumDecl {
              static void setFixed(EnumDecl* ED, bool value = true) {
                ((EnumDeclDerived*)ED)->IsFixed = value;
              }
            };

            if (ch != '1')
              EnumDeclDerived::setFixed(ED, false);
          }
        InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
        break;
      }

      return true;
    }

    bool VisitCXXRecordDecl(CXXRecordDecl* D) {
      if (!D->hasAttr<AnnotateAttr>())
        return true;

      VisitDecl(D);

      if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate())
        return VisitTemplateDecl(TmplD);
      return true;
    }

    bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitTemplateDecl(TemplateDecl* D) {
      if (D->getTemplatedDecl() &&
          !D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
        return true;

      VisitDecl(D);

      for(auto P: D->getTemplateParameters()->asArray())
        TraverseDecl(P);
      return true;
    }

    bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArgument())
        D->removeDefaultArgument();
      return true;
    }

    bool VisitParmVarDecl(ParmVarDecl* D) {
      VisitDecl(D);

      if (m_IsStoringState)
        return true;

      if (D->hasDefaultArg())
        D->setDefaultArg(nullptr);
      return true;
    }
  };

  void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
                          const clang::Token &IncludeTok,
                          llvm::StringRef FileName,
                          bool IsAngled,
                          clang::CharSourceRange FilenameRange,
                          const clang::FileEntry *File,
                          llvm::StringRef SearchPath,
                          llvm::StringRef RelativePath,
                          const clang::Module *Imported) {
    // If File is 0 this means that the #included file doesn't exist.
    if (!File)
      return;

    auto found = m_Map.find(File);
    if (found == m_Map.end())
     return; // nothing to do, file not referred in any annotation

    AutoloadingVisitor defaultArgsCleaner;
    for (auto D : found->second) {
      defaultArgsCleaner.RemoveDefaultArgsOf(D);
    }
    // Don't need to keep track of cleaned up decls from file.
    m_Map.erase(found);
  }

  AutoloadCallback::~AutoloadCallback() {
  }

  void AutoloadCallback::TransactionCommitted(const Transaction &T) {
    if (T.decls_begin() == T.decls_end())
      return;
    if (T.decls_begin()->m_DGR.isNull())
      return;

    if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
      if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
        AutoloadingVisitor defaultArgsStateCollector;
        Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
        for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
             I != E; ++I) {
          Transaction::DelayCallInfo DCI = *I;

          // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
          //   continue;
          if (DCI.m_DGR.isNull())
            continue;

          if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
            if (ND->getIdentifier()
                && ND->getName().equals("__Cling_Autoloading_Map")) {

              for (Transaction::const_iterator I = T.decls_begin(),
                     E = T.decls_end(); I != E; ++I) {
                Transaction::DelayCallInfo DCI = *I;
                for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
                       JE = DCI.m_DGR.end(); J != JE; ++J) {
                    defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
                }
              }
            }

        }
      }
  }

} //end namespace cling
<|endoftext|>


<commit_before>/* <x0/RegExp.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://redmine.trapni.de/projects/x0
 *
 * (c) 2010-2012 Christian Parpart <trapni@gentoo.org>
 */

#include <x0/RegExp.h>
#include <x0/Buffer.h>
#include <x0/BufferRef.h>
#include <cstring>
#include <pcre.h>

namespace x0 {

RegExp::RegExp() :
	pattern_(),
	re_(NULL)
{
}

RegExp::RegExp(const RegExp& v) :
	pattern_(v.pattern_),
	re_()
{
	// there's no pcre_clone() unfortunately ^^
	const char *errMsg = "";
	int errOfs = 0;

	re_ = pcre_compile(pattern_.c_str(), PCRE_CASELESS | PCRE_EXTENDED, &errMsg, &errOfs, 0);
}

RegExp::RegExp(const std::string& pattern) :
	pattern_(pattern),
	re_()
{
	const char *errMsg = "";
	int errOfs = 0;

	re_ = pcre_compile(pattern_.c_str(), PCRE_CASELESS | PCRE_EXTENDED, &errMsg, &errOfs, 0);
}

RegExp::~RegExp()
{
	pcre_free(re_);
}

bool RegExp::match(const char *cstring) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

	int rc = pcre_exec(re_, NULL, cstring, strlen(cstring), 0, 0, ov, OV_COUNT);
	return rc > 0;
}

bool RegExp::match(const char *buffer, size_t size, Result* result) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

#ifndef NDEBUG
	for (size_t i = 0; i < OV_COUNT; ++i)
		ov[i] = 1337;
#endif

	int rc = pcre_exec(re_, NULL, buffer, size, 0, 0, ov, OV_COUNT);
	if (result) {
		if (rc > 0) {
			Buffer buf(buffer);
			for (size_t i = 0, e = rc * 2; i != e; i += 2) {
				const char* value = buffer + ov[i];
				size_t length = ov[i + 1] - ov[i];
				result->push_back(std::make_pair(value, length));
			}
		} else {
			result->push_back(std::make_pair("", 0));
		}
	}
	return rc > 0;
}

bool RegExp::match(const BufferRef& buffer) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

#ifndef NDEBUG
	for (size_t i = 0; i < OV_COUNT; ++i)
		ov[i] = 1337;
#endif

	int rc = pcre_exec(re_, NULL, buffer.data(), buffer.size(), 0, 0, ov, OV_COUNT);
	return rc > 0;
}

const char *RegExp::c_str() const
{
	return pattern_.c_str();
}

} // namespace x0
<commit_msg>[base] RegExp: ensure empty result set before populating with our current results.<commit_after>/* <x0/RegExp.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://redmine.trapni.de/projects/x0
 *
 * (c) 2010-2012 Christian Parpart <trapni@gentoo.org>
 */

#include <x0/RegExp.h>
#include <x0/Buffer.h>
#include <x0/BufferRef.h>
#include <cstring>
#include <pcre.h>

namespace x0 {

RegExp::RegExp() :
	pattern_(),
	re_(NULL)
{
}

RegExp::RegExp(const RegExp& v) :
	pattern_(v.pattern_),
	re_()
{
	// there's no pcre_clone() unfortunately ^^
	const char *errMsg = "";
	int errOfs = 0;

	re_ = pcre_compile(pattern_.c_str(), PCRE_CASELESS | PCRE_EXTENDED, &errMsg, &errOfs, 0);
}

RegExp::RegExp(const std::string& pattern) :
	pattern_(pattern),
	re_()
{
	const char *errMsg = "";
	int errOfs = 0;

	re_ = pcre_compile(pattern_.c_str(), PCRE_CASELESS | PCRE_EXTENDED, &errMsg, &errOfs, 0);
}

RegExp::~RegExp()
{
	pcre_free(re_);
}

bool RegExp::match(const char *cstring) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

	int rc = pcre_exec(re_, NULL, cstring, strlen(cstring), 0, 0, ov, OV_COUNT);
	return rc > 0;
}

bool RegExp::match(const char *buffer, size_t size, Result* result) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

#ifndef NDEBUG
	for (size_t i = 0; i < OV_COUNT; ++i)
		ov[i] = 1337;
#endif

	int rc = pcre_exec(re_, NULL, buffer, size, 0, 0, ov, OV_COUNT);
	if (result) {
		result->clear();
		if (rc > 0) {
			Buffer buf(buffer);
			for (size_t i = 0, e = rc * 2; i != e; i += 2) {
				const char* value = buffer + ov[i];
				size_t length = ov[i + 1] - ov[i];
				result->push_back(std::make_pair(value, length));
			}
		} else {
			result->push_back(std::make_pair("", 0));
		}
	}
	return rc > 0;
}

bool RegExp::match(const BufferRef& buffer) const
{
	if (!re_)
		return false;

	const size_t OV_COUNT = 3 * 36;
	int ov[OV_COUNT];

#ifndef NDEBUG
	for (size_t i = 0; i < OV_COUNT; ++i)
		ov[i] = 1337;
#endif

	int rc = pcre_exec(re_, NULL, buffer.data(), buffer.size(), 0, 0, ov, OV_COUNT);
	return rc > 0;
}

const char *RegExp::c_str() const
{
	return pattern_.c_str();
}

} // namespace x0
<|endoftext|>


<commit_before>#include<iostream>
#include<fstream>
using namespace std;
void cpy(char out[])
{
	ifstream ob("/home/sampath/repo/note_lib/sampath.s16");
	ofstream o(out);
	char ch;
//	printf("%s\n",out);
	while(ob.eof()==0)
	{
		ob.get(ch);
		o.put(ch);
//		cout << ch;
	}
	o.close();
	ob.close();
	return;
}

int main(int argc,char *argv[])
{
	if(argc<2)
	{
		cerr << "No Input File's specified!!"<<endl;
		return 1;
	}
	for(int i=1;i<argc;i++)
		cpy(argv[i]);
	return 0;
}
<commit_msg>Changes to temp.cpp<commit_after>#include<iostream>
#include<fstream>
#include<ctime>
#include<cstdio>
const std::string currentDateTime()
{
	time_t     now = time(0);
	struct tm  tstruct;
	char       buf[80];
	tstruct = *localtime(&now);
	strftime(buf, sizeof(buf), "%d-%m-%Y.%X", &tstruct);
	return buf;
}
using namespace std;
void cpy(char out[])
{
	ofstream fout(out);
	fout << "/*" << endl;
	fout << "\tCoder\t: R Sampath Sukesh." << endl;
	fout << "\tHandle\t: rsampaths16." << endl;
	fout << "\tEmail\t: rsampaths16@gamil.com." << endl;
	fout << "\tCountry\t: India." << endl;
	fout << "\tTStamp\t: " << currentDateTime() << endl;
	fout << "*/" << endl << endl << endl;
	fout << "#pragma comment(linker, \"/STACK:36777216\")" << endl;
	fout << "#include<bits/stdc++.h>" << endl;
	fout << "using namespace std;" << endl;
	fout << "typedef long long ll;" << endl << endl << endl;
	fout << "/*==================!!-Code-Starts-From-Here-!!==================*/" << endl << endl << endl;
	fout << "/*=======================!!-End-Of-Code-!!=======================*/" << endl;

	fout.close();
	return;
}

int main(int argc,char *argv[])
{
	if(argc<2)
	{
		cerr << "No Input File's specified!!"<<endl;
		return 1;
	}
	for(int i=1;i<argc;i++)
		cpy(argv[i]);
	return 0;
}
<|endoftext|>


<commit_before>// CS 372 Project 3
// The Platformer
// Noah Betzen, William Fisher, Jacob McKenna
// Dylan Tucker, William Showalter, Saira Walia, Adam Walters
// test.cpp

#define CATCH_CONFIG_MAIN
#include "Catch/single_include/catch.hpp"
#include <SFML/Graphics.hpp>
#include "Player.h"
#include <memory>
using std::shared_ptr;

TEST_CASE("Implement The Platformer", "Platformer")
{

	Player testPlayer;
    REQUIRE(testPlayer.getLives() == 3);

		auto speed = testPlayer.getSpeed();
    REQUIRE(speed.x == Approx(16.f));
		REQUIRE(speed.y == Approx(16.f));

		auto pos = testPlayer.getPosition();
		REQUIRE(pos.x == Approx(0.f));
		REQUIRE(pos.y == Approx(0.f));
}
<commit_msg>fixing test for player speed<commit_after>// CS 372 Project 3
// The Platformer
// Noah Betzen, William Fisher, Jacob McKenna
// Dylan Tucker, William Showalter, Saira Walia, Adam Walters
// test.cpp

#define CATCH_CONFIG_MAIN
#include "Catch/single_include/catch.hpp"
#include <SFML/Graphics.hpp>
#include "Player.h"
#include <memory>
using std::shared_ptr;

TEST_CASE("Implement The Platformer", "Platformer")
{

	Player testPlayer;
    REQUIRE(testPlayer.getLives() == 3);

		//default speed is 0
		auto pos = testPlayer.getPosition();
		REQUIRE(pos.x == Approx(0.f));
		REQUIRE(pos.y == Approx(0.f));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>

#include "immutable_map.hpp"

using namespace deepness;

int main(int argc, char *argv[])
{
    std::cout << "immutable_map tests" << std::endl;
    immutable_map<int, int> intmap;
    auto intmap2 = intmap.set(0, 42);
    assert(intmap2[0] == 42);

    auto intmap3 = intmap2.set(0, 1);
    assert(intmap3[0] == 1);

    intmap3 = intmap2.erase(0);
    bool exception = false;
    try
    {
        intmap3[0];
    }
    catch(key_error &)
    {
        exception = true;
    }
    assert(exception);

    immutable_map<int, int> intmap4;
    for(size_t i = 0; i < 10000; ++i)
    {
        intmap4 = intmap4.set(i, i);
		assert(intmap4[i] == i);
    }

    for(size_t i = 0; i < 10000; ++i)
    {
        assert(intmap4[i] == i);
    }

    std::cout << "tests complete" << std::endl;;
}
<commit_msg>better tests<commit_after>#include <iostream>
#include <cassert>

#include "immutable_map.hpp"

using namespace deepness;

int main(int argc, char *argv[])
{
    std::cout << "immutable_map tests" << std::endl;
    immutable_map<int, const int> intmap;
    auto intmap2 = intmap.set(0, 42);
    assert(intmap2[0] == 42);

    auto intmap3 = intmap2.set(0, 1);
    assert(intmap3[0] == 1);

    intmap3 = intmap2.erase(0);
    bool exception = false;
    try
    {
        intmap3[0];
    }
    catch(key_error &)
    {
        exception = true;
    }
    assert(exception);

    immutable_map<int, const int> intmap4;
    for(size_t i = 0; i < 10000; ++i)
    {
        intmap4 = intmap4.set(i, i);
		assert(intmap4[i] == i);
    }

    for(size_t i = 0; i < 10000; ++i)
    {
        assert(intmap4[i] == i);
    }

	immutable_map<int, int> intmap5;
	intmap5 = intmap5.set(0, 0);
	assert(intmap5[0] == 0);
	// since we return a non-const reference this is possible
	intmap5[0] = 4;
	assert(intmap5[0] == 4);

    std::cout << "tests complete" << std::endl;;
}
<|endoftext|>


<commit_before>#include <clunk/context.h>
#include <clunk/backend/sdl/backend.h>
#include <clunk/source.h>
#include <clunk/wav_file.h>
#include <stdlib.h>
#ifdef _WINDOWS
#	include <Windows.h>
#	define usleep(us) ::Sleep(((us) + 999) / 1000)
#else
#	include <unistd.h>
#endif
#include <clunk/ref_mdct_context.h>

#define WINDOW_BITS 9

typedef clunk::mdct_context<WINDOW_BITS, clunk::vorbis_window_func, float> mdct_type;
typedef clunk::ref_mdct_context<WINDOW_BITS, clunk::vorbis_window_func, float> ref_mdct_type;
typedef clunk::fft_context<WINDOW_BITS - 2, float> fft_type;

template<typename mdct_type>
struct mdct_test {
	mdct_type	_mdct;
	float		_input[mdct_type::N];
	float		_overlap[mdct_type::N2];

	mdct_test(): _input(), _overlap() { }
	void dump(int n = mdct_type::N)
	{
		for(int i = 0; i < n; ++i)
			printf("%+1.1g ", _mdct.data[i]);
	}

	void feed()
	{
		//printf("feeding ");
		for(int i = 0; i < mdct_type::N2; ++i)
		{
			float v = (rand() % 11) - 5;
			_input[i] = _input[i + mdct_type::N2];
			_input[i + mdct_type::N2] = v;
			//printf("%+g ", v);
		}
		printf("\ninput: ");
		for(int i = 0; i < mdct_type::N; ++i)
		{
			_mdct.data[i] = _input[i];
		}
		dump();
		_mdct.apply_window();
		_mdct.mdct();
		//printf("\n\tfreq: "); dump();
		_mdct.imdct();
		_mdct.apply_window();

		for(int i = 0; i < mdct_type::N2; ++i)
			_mdct.data[i] += _overlap[i];

		for(int i = 0; i < mdct_type::N2; ++i)
			_overlap[i] = _mdct.data[mdct_type::N2 + i];

		printf("\nresult: "); dump(mdct_type::N2);
		printf("\n");
	}
};

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

	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'm') {
		mdct_type mdct;
		for(int i = 0; i < 200000; ++i)
		{
			mdct.mdct();
			clunk::Buffer::unoptimize(mdct.data, mdct.N);
		}
		return 0;
	}
	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'r') {
		ref_mdct_type mdct;
		for(int i = 0; i < 200000; ++i)
		{
			mdct.mdct();
			clunk::Buffer::unoptimize(mdct.data, mdct.N);
		}
		return 0;
	}
	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'f') {
		fft_type fft;
		for(int i = 0; i < 2000000; ++i)
			fft.fft();
		return 0;
	}
	if (argc > 1 && argv[1][0] == 't') {
		fft_type fft;
		for(int i = 0; i < fft_type::N; ++i) {
			fft.data[i] = std::complex<float>((float)((i / 4) & 1), 0);
		}
		fft.fft();
		for(int i = 0; i < fft_type::N; ++i) {
			printf("%f, %f = %f\n", fft.data[i].real(), fft.data[i].imag(), std::abs(fft.data[i]));
		}
		fft.ifft();

		for(int i = 0; i < fft_type::N; ++i) {
			fft.data[i] -= std::complex<float>((float)((i / 4) & 1), 0);
			printf("%f, %f\n", fft.data[i].real(), fft.data[i].imag());
		}

		return 0;
	}
	if (argc > 1 && argv[1][0] == 'f')
	{
		printf("reference: \n");
		mdct_test<clunk::ref_mdct_context<3, clunk::sin_window_func, float> > test;
		test.feed();
		test.feed();
		test.feed();
		test.feed();
		printf("fft based: \n");
		mdct_test<clunk::mdct_context<3, clunk::sin_window_func, float> > test2;
		test2.feed();
		test2.feed();
		test2.feed();
		test2.feed();
		return 0;
	}

	clunk::sdl::Backend backend(44100, 2, 1024);
	clunk::Context &context = backend.get_context();

	clunk::Object * o = context.create_object();
	clunk::Sample * s = clunk::WavFile::load(context, "scissors.wav");
	clunk::Sample * h = clunk::WavFile::load(context, "helicopter.wav");

	static const int d = 3, n = 72;
	clunk::DistanceModel dm(clunk::DistanceModel::Exponent, false);
	dm.rolloff_factor = 0.7f;
	context.set_distance_model(dm);

	context.save("test_out.raw");
	backend.start();
/*	o->play("l", new clunk::Source(s, false, clunk::v3f(-d, 0, 0)));
	sleep(1);
	//o->play("c", new clunk::Source(s, false, clunk::v3f(0, 0, 0)));
	//sleep(1);
	o->play("r", new clunk::Source(s, false, clunk::v3f(d, 0, 0)));
	sleep(1);

	o->play("u", new clunk::Source(s, false, clunk::v3f(0, d, 0)));
	sleep(1);

	o->play("b", new clunk::Source(s, false, clunk::v3f(0, 0, d)));
	sleep(1);
*/
	o->play("h", new clunk::Source(h, true));

	for(int i = 0; i <= n; ++i) {
		float a = float(2 * M_PI * i / n);
		clunk::v3f pos(cos(a) * d, sin(a) * d * 2, 1);
		o->set_position(pos);
		printf("%g %g %g\n", pos.x, pos.y, pos.z);
		usleep(100000);
	}

/*	for(int i = 0; i <= n; ++i) {
		float a = M_PI * i / n;
		o->play("s", new clunk::Source(s, false, clunk::v3f(cos(a), -0.25f, sin(a)) * d));
		usleep(500000);
	}
*/	backend.stop();
	return 0;
}
<commit_msg>adjusted cycles for benchmark, unoptimize fft result<commit_after>#include <clunk/context.h>
#include <clunk/backend/sdl/backend.h>
#include <clunk/source.h>
#include <clunk/wav_file.h>
#include <stdlib.h>
#ifdef _WINDOWS
#	include <Windows.h>
#	define usleep(us) ::Sleep(((us) + 999) / 1000)
#else
#	include <unistd.h>
#endif
#include <clunk/ref_mdct_context.h>

#define WINDOW_BITS 9

typedef clunk::mdct_context<WINDOW_BITS, clunk::vorbis_window_func, float> mdct_type;
typedef clunk::ref_mdct_context<WINDOW_BITS, clunk::vorbis_window_func, float> ref_mdct_type;
typedef clunk::fft_context<WINDOW_BITS - 2, float> fft_type;

template<typename mdct_type>
struct mdct_test {
	mdct_type	_mdct;
	float		_input[mdct_type::N];
	float		_overlap[mdct_type::N2];

	mdct_test(): _input(), _overlap() { }
	void dump(int n = mdct_type::N)
	{
		for(int i = 0; i < n; ++i)
			printf("%+1.1g ", _mdct.data[i]);
	}

	void feed()
	{
		//printf("feeding ");
		for(int i = 0; i < mdct_type::N2; ++i)
		{
			float v = (rand() % 11) - 5;
			_input[i] = _input[i + mdct_type::N2];
			_input[i + mdct_type::N2] = v;
			//printf("%+g ", v);
		}
		printf("\ninput: ");
		for(int i = 0; i < mdct_type::N; ++i)
		{
			_mdct.data[i] = _input[i];
		}
		dump();
		_mdct.apply_window();
		_mdct.mdct();
		//printf("\n\tfreq: "); dump();
		_mdct.imdct();
		_mdct.apply_window();

		for(int i = 0; i < mdct_type::N2; ++i)
			_mdct.data[i] += _overlap[i];

		for(int i = 0; i < mdct_type::N2; ++i)
			_overlap[i] = _mdct.data[mdct_type::N2 + i];

		printf("\nresult: "); dump(mdct_type::N2);
		printf("\n");
	}
};

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

	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'm') {
		mdct_type mdct;
		for(int i = 0; i < 200000; ++i)
		{
			mdct.mdct();
			clunk::Buffer::unoptimize(mdct.data, mdct.N);
		}
		return 0;
	}
	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'r') {
		ref_mdct_type mdct;
		for(int i = 0; i < 200000; ++i)
		{
			mdct.mdct();
			clunk::Buffer::unoptimize(mdct.data, mdct.N);
		}
		return 0;
	}
	if (argc > 1 && argv[1][0] == 'b' && argv[1][1] == 'f') {
		fft_type fft;
		for(int i = 0; i < 400000; ++i)
		{
			fft.fft();
			clunk::Buffer::unoptimize(fft.data, fft.N);
		}
		return 0;
	}
	if (argc > 1 && argv[1][0] == 't') {
		fft_type fft;
		for(int i = 0; i < fft_type::N; ++i) {
			fft.data[i] = std::complex<float>((float)((i / 4) & 1), 0);
		}
		fft.fft();
		for(int i = 0; i < fft_type::N; ++i) {
			printf("%f, %f = %f\n", fft.data[i].real(), fft.data[i].imag(), std::abs(fft.data[i]));
		}
		fft.ifft();

		for(int i = 0; i < fft_type::N; ++i) {
			fft.data[i] -= std::complex<float>((float)((i / 4) & 1), 0);
			printf("%f, %f\n", fft.data[i].real(), fft.data[i].imag());
		}

		return 0;
	}
	if (argc > 1 && argv[1][0] == 'f')
	{
		printf("reference: \n");
		mdct_test<clunk::ref_mdct_context<3, clunk::sin_window_func, float> > test;
		test.feed();
		test.feed();
		test.feed();
		test.feed();
		printf("fft based: \n");
		mdct_test<clunk::mdct_context<3, clunk::sin_window_func, float> > test2;
		test2.feed();
		test2.feed();
		test2.feed();
		test2.feed();
		return 0;
	}

	clunk::sdl::Backend backend(44100, 2, 1024);
	clunk::Context &context = backend.get_context();

	clunk::Object * o = context.create_object();
	clunk::Sample * s = clunk::WavFile::load(context, "scissors.wav");
	clunk::Sample * h = clunk::WavFile::load(context, "helicopter.wav");

	static const int d = 3, n = 72;
	clunk::DistanceModel dm(clunk::DistanceModel::Exponent, false);
	dm.rolloff_factor = 0.7f;
	context.set_distance_model(dm);

	context.save("test_out.raw");
	backend.start();
/*	o->play("l", new clunk::Source(s, false, clunk::v3f(-d, 0, 0)));
	sleep(1);
	//o->play("c", new clunk::Source(s, false, clunk::v3f(0, 0, 0)));
	//sleep(1);
	o->play("r", new clunk::Source(s, false, clunk::v3f(d, 0, 0)));
	sleep(1);

	o->play("u", new clunk::Source(s, false, clunk::v3f(0, d, 0)));
	sleep(1);

	o->play("b", new clunk::Source(s, false, clunk::v3f(0, 0, d)));
	sleep(1);
*/
	o->play("h", new clunk::Source(h, true));

	for(int i = 0; i <= n; ++i) {
		float a = float(2 * M_PI * i / n);
		clunk::v3f pos(cos(a) * d, sin(a) * d * 2, 1);
		o->set_position(pos);
		printf("%g %g %g\n", pos.x, pos.y, pos.z);
		usleep(100000);
	}

/*	for(int i = 0; i <= n; ++i) {
		float a = M_PI * i / n;
		o->play("s", new clunk::Source(s, false, clunk::v3f(cos(a), -0.25f, sin(a)) * d));
		usleep(500000);
	}
*/	backend.stop();
	return 0;
}
<|endoftext|>


<commit_before>#include <exception>
#include <string>
#include <sstream>
#include <iostream>

void make_string_(std::stringstream &) {}

template<class F, class... T>
void make_string_(std::stringstream & ss, F && first, T && ... next) {
	ss << first;
	make_string_(ss, next...);
}

template<class... T>
std::string && make_string(T && ... args) {
	std::stringstream ss;
	make_string_(ss, args...);
	return std::move(ss.str());
}

struct out_of_bounds : std::exception {
	size_t input;
	size_t bound;
	out_of_bounds(size_t input, size_t bound) : input(input), bound(bound) {}
	const char* what() const noexcept override { return make_string("out of bounds access at ", input, " where bound was ", bound).c_str(); }
};

template<class T> T max(T a, T b) { return a > b ? a : b; }
template<class T> T min(T a, T b) { return a < b ? a : b; }

// globals only used in checked_array should be moved there as statics
int array_counter = 0;
int index_counter = 0;

template<class T> struct checked_array {
	typedef T value_type;
	size_t size() const { return n; }

	size_t n;
	T* d;
	checked_array(size_t n = 0) : n(n), d(n ? new T[n] : 0) { ++array_counter; }
	checked_array(const checked_array<T> & cp) : n(cp.n), d(n ? new T[n] : 0) {
		if(n) memcpy(d, cp.d, sizeof(T) * n);
		++array_counter;
	}
	checked_array(checked_array<T> && mv) : n(mv.n), d(mv.d) {
		mv.d = 0; mv.n = 0;
		++array_counter;
	}
	~checked_array() { free(); --array_counter; }
	void free() { if(d) delete[] d; }
	void clear() { free(); d = 0; n = 0; }
	void resize(size_t nn) {
		T* nd;
		if(nn) {
			nd = new T[nn];
			if(n) memcpy(nd, d, sizeof(T) * max(n, nn));
		}
		free();
		d = nd; n = nn;
	}
	T & operator[](size_t i) {
		if(i >= n) throw out_of_bounds(i, n);
		++index_counter;
		return d[i];
	}
	T & operator[](size_t i) const {
		if(i >= n) throw out_of_bounds(i, n);
		++index_counter;
		return d[i];
	}
};

int x = 3; // scope test (global)

// dead class
struct independant {
	int x; // scope test (member)
	int f() { return x; }
	const char* g() { return "indep"; }
};

struct base {
	int x; // scope test (shadowed member)
	virtual int f() { return x; }
	base(int x = 0) : x(x) {}
};

struct derived : base {
	int x; // scope test (shadowing member)
	int f() { return base::x + x; }
	const char* g() { return "derived"; }
	derived(int x = 0, int base_x = 0) : base(base_x), x(x) {}
};

template<class F> checked_array<int> && build(size_t n, F f) {
	checked_array<int> arr(n);
	for(size_t i = 0; i < n; ++i) arr[i] = f();
	return std::move(arr);
}

template<class T> typename T::value_type sum(const T & vec) {
	typename T::value_type v = 0;
	for(size_t i = 0; i < vec.size(); ++i) v += vec[i];
	return v;
}

int test() {
	auto data = build(rand() % 100, [](){ return derived(rand() & 1, rand() & 1).f(); } );
	std::cout << sum(data) << std::endl;
	return 0;
}
<commit_msg>added 'test' namespace to test the inNamespace matcher<commit_after>#include <exception>
#include <string>
#include <sstream>
#include <iostream>

namespace test {

void make_string_(std::stringstream &) {}

template<class F, class... T>
void make_string_(std::stringstream & ss, F && first, T && ... next) {
	ss << first;
	make_string_(ss, next...);
}

template<class... T>
std::string && make_string(T && ... args) {
	std::stringstream ss;
	make_string_(ss, args...);
	return std::move(ss.str());
}

struct out_of_bounds : std::exception {
	size_t input;
	size_t bound;
	out_of_bounds(size_t input, size_t bound) : input(input), bound(bound) {}
	const char* what() const noexcept override { return make_string("out of bounds access at ", input, " where bound was ", bound).c_str(); }
};

template<class T> T max(T a, T b) { return a > b ? a : b; }
template<class T> T min(T a, T b) { return a < b ? a : b; }

// globals only used in checked_array should be moved there as statics
int array_counter = 0;
int index_counter = 0;

template<class T> struct checked_array {
	typedef T value_type;
	size_t size() const { return n; }

	size_t n;
	T* d;
	checked_array(size_t n = 0) : n(n), d(n ? new T[n] : 0) { ++array_counter; }
	checked_array(const checked_array<T> & cp) : n(cp.n), d(n ? new T[n] : 0) {
		if(n) memcpy(d, cp.d, sizeof(T) * n);
		++array_counter;
	}
	checked_array(checked_array<T> && mv) : n(mv.n), d(mv.d) {
		mv.d = 0; mv.n = 0;
		++array_counter;
	}
	~checked_array() { free(); --array_counter; }
	void free() { if(d) delete[] d; }
	void clear() { free(); d = 0; n = 0; }
	void resize(size_t nn) {
		T* nd;
		if(nn) {
			nd = new T[nn];
			if(n) memcpy(nd, d, sizeof(T) * max(n, nn));
		}
		free();
		d = nd; n = nn;
	}
	T & operator[](size_t i) {
		if(i >= n) throw out_of_bounds(i, n);
		++index_counter;
		return d[i];
	}
	T & operator[](size_t i) const {
		if(i >= n) throw out_of_bounds(i, n);
		++index_counter;
		return d[i];
	}
};

int x = 3; // scope test (global)

// dead class
struct independant {
	int x; // scope test (member)
	int f() { return x; }
	const char* g() { return "indep"; }
};

struct base {
	int x; // scope test (shadowed member)
	virtual int f() { return x; }
	base(int x = 0) : x(x) {}
};

struct derived : base {
	int x; // scope test (shadowing member)
	int f() { return base::x + x; }
	const char* g() { return "derived"; }
	derived(int x = 0, int base_x = 0) : base(base_x), x(x) {}
};

template<class F> checked_array<int> && build(size_t n, F f) {
	checked_array<int> arr(n);
	for(size_t i = 0; i < n; ++i) arr[i] = f();
	return std::move(arr);
}

template<class T> typename T::value_type sum(const T & vec) {
	typename T::value_type v = 0;
	for(size_t i = 0; i < vec.size(); ++i) v += vec[i];
	return v;
}

int test() {
	auto data = build(rand() % 100, [](){ return derived(rand() & 1, rand() & 1).f(); } );
	std::cout << sum(data) << std::endl;
	return 0;
}

} // test namespace
<|endoftext|>


<commit_before>//@	{"targets":[{"name":"test","type":"application"}]}

#include "itemtree.hpp"
#include <cstdio>
#include <clocale>
#include <cinttypes>
#include <algorithm>

using namespace Temple;

class Monitor
	{
	public:
		[[noreturn]] void operator()(const Temple::Error& error)
			{
			auto line=Temple::convert(m_line);
			auto col=Temple::convert(m_col);
			Error e(line.data(),':',col.data(),": ",error.message());
			throw e;
			}

		void positionUpdate(uintmax_t line,uintmax_t col) noexcept
			{
			m_line=line;
			m_col=col;
			}

	private:
		uintmax_t m_line;
		uintmax_t m_col;
	};

std::string& concat(char a,std::string& b)
	{
	b+=a;
	return b;
	}

std::string& concat(std::string& a,const char* b)
	{
	a+=b;
	return a;
	}

std::string& concat(std::string& a,const std::string& b)
	{
	a+=b;
	return a;
	}

struct Reader
	{
	Reader(const char* src)
		{handle=fopen(src,"rb");}
	~Reader()
		{fclose(handle);}

	FILE* handle;
	};

bool read(Reader& reader,char& ch)
	{
	auto ch_in=getc(reader.handle);
	if(ch_in==-1)
		{return 0;}
	ch=ch_in;
	return 1;
	}

int main()
	{
	setlocale(LC_ALL,"");
	try
		{
		ItemTree<> tree(Reader("test.temple"),Monitor{});
		tree.store(stdout);

		auto& x=tree.root().value<ItemTree<>::CompoundArray>()[0]
			.find_typed<ItemTree<>::Compound>("foo",[](auto err){throw err;})
			.find_typed<ItemTree<>::Compound>("more objects",[](auto err){throw err;})
			.find_typed<double>("value",[](auto err){throw err;});

		printf("Found value: %.7g\n",x);

		auto& y=find_typed<double>([](auto err){throw err;}
			,tree.root(),0,"foo","more objects","value");

		assert(x==y);

		const auto& tree_const=tree;

		auto& xc=tree_const.root().value<ItemTree<>::CompoundArray>()[0]
			.find_typed<ItemTree<>::Compound>("foo",[](auto err){throw err;})
			.find_typed<ItemTree<>::Compound>("more objects",[](auto err){throw err;})
			.find_typed<double>("value",[](auto err){throw err;});
		printf("Found value: %.7g\n",xc);

		auto& yc=find_typed<double>([](auto err){throw err;}
			,tree_const.root(),0,"foo","more objects","value");

		assert(yc==xc);
		}
	catch(const Temple::Error& error)
		{
		fprintf(stderr,"%s\n",error.message());
		}
	return 0;
	}
<commit_msg>Cleanup<commit_after>//@	{"targets":[{"name":"test","type":"application"}]}

#include "itemtree.hpp"
#include <cstdio>
#include <clocale>
#include <cinttypes>
#include <algorithm>

class Monitor
	{
	public:
		[[noreturn]] void operator()(const Temple::Error& error)
			{
			auto line=Temple::convert(m_line);
			auto col=Temple::convert(m_col);
			Temple::Error e(line.data(),':',col.data(),": ",error.message());
			throw e;
			}

		void positionUpdate(uintmax_t line,uintmax_t col) noexcept
			{
			m_line=line;
			m_col=col;
			}

	private:
		uintmax_t m_line;
		uintmax_t m_col;
	};

struct Reader
	{
	Reader(const char* src)
		{handle=fopen(src,"rb");}
	~Reader()
		{fclose(handle);}

	FILE* handle;
	};

bool read(Reader& reader,char& ch)
	{
	auto ch_in=getc(reader.handle);
	if(ch_in==-1)
		{return 0;}
	ch=ch_in;
	return 1;
	}

int main()
	{
	setlocale(LC_ALL,"");
	try
		{
		using namespace Temple;
		ItemTree<> tree(Reader("test.temple"),Monitor{});
		tree.store(stdout);

		auto& x=tree.root().value<ItemTree<>::CompoundArray>()[0]
			.find_typed<ItemTree<>::Compound>("foo",[](auto err){throw err;})
			.find_typed<ItemTree<>::Compound>("more objects",[](auto err){throw err;})
			.find_typed<double>("value",[](auto err){throw err;});

		printf("Found value: %.7g\n",x);

		auto& y=find_typed<double>([](auto err){throw err;}
			,tree.root(),0,"foo","more objects","value");

		assert(x==y);

		const auto& tree_const=tree;

		auto& xc=tree_const.root().value<ItemTree<>::CompoundArray>()[0]
			.find_typed<ItemTree<>::Compound>("foo",[](auto err){throw err;})
			.find_typed<ItemTree<>::Compound>("more objects",[](auto err){throw err;})
			.find_typed<double>("value",[](auto err){throw err;});
		printf("Found value: %.7g\n",xc);

		auto& yc=find_typed<double>([](auto err){throw err;}
			,tree_const.root(),0,"foo","more objects","value");

		assert(yc==xc);
		}
	catch(const Temple::Error& error)
		{
		fprintf(stderr,"%s\n",error.message());
		}
	return 0;
	}
<|endoftext|>


<commit_before>#if defined(__GNUC__) && (defined(__linux__) || defined(__linux))
#include <execinfo.h>
#include <unistd.h>
#endif

#include "exception.hpp"

#define ENABLE_BACK_TRACE

using namespace aff3ct::tools;

exception
::exception() throw()
{
}

exception
::exception(const std::string message) throw()
: message(message)
{
#if defined(ENABLE_BACK_TRACE)
	this->message += get_back_trace();
#endif
}

exception
::exception(const std::string filename,
            const int line_num,
            const std::string funcname,
            const std::string message) throw()
{
	if (!filename.empty())
		this->message += "In the '" + filename + "' file";
	if (line_num >= 0)
		this->message += " at line " + std::to_string(line_num);
	if (!funcname.empty())
		this->message += " ('" + funcname + "' function)";
	this->message += ": ";
	this->message += "\"" + message + "\"";

#if defined(ENABLE_BACK_TRACE)
	this->message += get_back_trace();
#endif
}

exception
::~exception() throw()
{
}

const char* exception
::what() const throw()
{
	return message.c_str();
}

std::string exception
::get_back_trace()
{
	std::string bt_str;
#if defined(__GNUC__) && (defined(__linux__) || defined(__linux))
	const int bt_max_depth = 32;
	void *bt_array[bt_max_depth];

	size_t size = backtrace(bt_array, bt_max_depth);
	char** bt_symbs = backtrace_symbols(bt_array, size);

	bt_str += "\nBacktrace:";
	for (size_t i = 0; i < size; i++)
		bt_str += "\n" + std::string(bt_symbs[i]);
	free(bt_symbs);
#endif

	return bt_str;
}
<commit_msg>Enable backtrace for clang.<commit_after>#if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__))
#include <execinfo.h>
#include <unistd.h>
#include <cstdlib>
#endif

#include "exception.hpp"

#define ENABLE_BACK_TRACE

using namespace aff3ct::tools;

exception
::exception() throw()
{
}

exception
::exception(const std::string message) throw()
: message(message)
{
#if defined(ENABLE_BACK_TRACE)
	this->message += get_back_trace();
#endif
}

exception
::exception(const std::string filename,
            const int line_num,
            const std::string funcname,
            const std::string message) throw()
{
	if (!filename.empty())
		this->message += "In the '" + filename + "' file";
	if (line_num >= 0)
		this->message += " at line " + std::to_string(line_num);
	if (!funcname.empty())
		this->message += " ('" + funcname + "' function)";
	this->message += ": ";
	this->message += "\"" + message + "\"";

#if defined(ENABLE_BACK_TRACE)
	this->message += get_back_trace();
#endif
}

exception
::~exception() throw()
{
}

const char* exception
::what() const throw()
{
	return message.c_str();
}

std::string exception
::get_back_trace()
{
	std::string bt_str;
#if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__))
	const int bt_max_depth = 32;
	void *bt_array[bt_max_depth];

	size_t size = backtrace(bt_array, bt_max_depth);
	char** bt_symbs = backtrace_symbols(bt_array, size);

	bt_str += "\nBacktrace:";
	for (size_t i = 0; i < size; i++)
		bt_str += "\n" + std::string(bt_symbs[i]);
	free(bt_symbs);
#endif

	return bt_str;
}
<|endoftext|>


<commit_before>#ifndef TREX_HPP
#define TREX_HPP

#include "Scene.hpp"
#include "AnimatedSprite.hpp"

#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <sstream>

class TREX: public Scene{
public:
    TREX(std::string _name, SceneManager* mgr, sf::RenderWindow* w)
    :Scene(_name, mgr, w)
    {}

    virtual void onSceneLoadToMemory(){
        animRunTexture1.loadFromFile("files/textures/trex/trexRun0.png");
        animRunTexture2.loadFromFile("files/textures/trex/trexRun1.png");

        animVultureFlyTexture1.loadFromFile("files/textures/trex/vultureFly0.png");
        animVultureFlyTexture2.loadFromFile("files/textures/trex/vultureFly1.png");

        texCactus.loadFromFile("files/textures/trex/cactus.png");

        if (!font.loadFromFile("files/textures/trex/Carnevalee_Freakshow.ttf")){
            std::cout << "cannot load font\n";
        }

        textScore.setFont(font);

        animTadzikRun.addFrame(AnimationFrame(&animRunTexture1, 150));
        animTadzikRun.addFrame(AnimationFrame(&animRunTexture2, 150));

        animVultureFly.addFrame(AnimationFrame(&animVultureFlyTexture1, 150));
        animVultureFly.addFrame(AnimationFrame(&animVultureFlyTexture2, 150));
    }

    virtual void onSceneActivate(){
        window->setTitle("Tadzik ~TREX");
        spTadzik.setAnimation(&animTadzikRun);
        spTadzik.sprite.setPosition(offsetX, window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY);
    }

    virtual void draw(double deltaTime){
        if(gameOver){
            textScore.setString("press space to play again");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
                spTadzik.sprite.setPosition(offsetX, window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY);
                gameOver=false;
                vecCactus.clear();
                result=0;
                isJumping=false;
            }
        }
        else{
            spTadzik.sprite.move(0, deltaTime * -speedY);
            spTadzik.update(deltaTime);
            double critHeight = window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY;
            if(spTadzik.sprite.getGlobalBounds().top < critHeight)speedY-=g;
            if(spTadzik.sprite.getGlobalBounds().top > critHeight){
                speedY=0;
                spTadzik.sprite.setPosition(offsetX, critHeight);
                isJumping=false;
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up)
               || sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
                if(!isJumping){
                    jump();
                }
            }
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
                //schylanie
            }

            manageObstacles();

            textScore.setString("score: " + stringify((int)result));

            result += speedX/10.0;
        }
        window->clear();
        for(sf::Sprite& sp : vecCactus){
            window->draw(sp);
        }
        window->draw(spTadzik.sprite);
        window->draw(textScore);
    }

    std::string stringify(int x){
        std::ostringstream o;
        o << x;
        return o.str();
    }

    void jump(){
        isJumping=true;
        speedY=0.5;
        spTadzik.sprite.move(0, -10);
    }

    void manageObstacles(){
        double addCactusChance = (double)rand()/RAND_MAX;
        if(addCactusChance <= 0.01){
            sf::Sprite spTmp(texCactus);
            spTmp.setPosition(0, 0);
            spTmp.setScale(0.4+((double)rand()/RAND_MAX)*0.1, 0.4+((double)rand()/RAND_MAX)*0.1);
            spTmp.setPosition(window->getSize().x+50, window->getSize().y-spTmp.getGlobalBounds().height-offsetY);
            vecCactus.push_back(spTmp);
        }

        for(int i = vecCactus.size()-1; i >= 0; i--){
            if(vecCactus[i].getGlobalBounds().left < -100){
                vecCactus.erase(vecCactus.begin()+i);
            }
        }

        for(int i = vecCactus.size()-1; i >= 0; i--){
            vecCactus[i].move(-speedX, 0);
            if(spTadzik.sprite.getGlobalBounds().intersects(vecCactus[i].getGlobalBounds())){
                gameOver=true;
            }
        }
    }

protected:
    Animation animTadzikRun, animVultureFly;
    sf::Texture animRunTexture1, animRunTexture2;
    sf::Texture animVultureFlyTexture1, animVultureFlyTexture2;
    sf::Texture texCactus;

    AnimatedSprite spTadzik;

    double speedX=5, speedY=0.0;

    double offsetX = 32, offsetY=4;
    bool isJumping=false;
    double g = 0.03;

    double result=0;

    std::vector<sf::Sprite> vecCactus;
    sf::Font font;
    sf::Text textScore;
    bool gameOver=false;
};

#endif // TREX_HPP

<commit_msg>Sępy, szakale!<commit_after>#ifndef TREX_HPP
#define TREX_HPP

#include "Scene.hpp"
#include "AnimatedSprite.hpp"

#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <sstream>

class TREX: public Scene{
public:
    TREX(std::string _name, SceneManager* mgr, sf::RenderWindow* w)
    :Scene(_name, mgr, w)
    {}

    virtual void onSceneLoadToMemory(){
        animRunTexture1.loadFromFile("files/textures/trex/trexRun0.png");
        animRunTexture2.loadFromFile("files/textures/trex/trexRun1.png");

        animVultureFlyTexture1.loadFromFile("files/textures/trex/vultureFly0.png");
        animVultureFlyTexture2.loadFromFile("files/textures/trex/vultureFly1.png");

        texCactus.loadFromFile("files/textures/trex/cactus.png");

        if (!font.loadFromFile("files/textures/trex/Carnevalee_Freakshow.ttf")){
            std::cout << "cannot load font\n";
        }

        textScore.setFont(font);

        animTadzikRun.addFrame(AnimationFrame(&animRunTexture1, 150));
        animTadzikRun.addFrame(AnimationFrame(&animRunTexture2, 150));

        animVultureFly.addFrame(AnimationFrame(&animVultureFlyTexture1, 150));
        animVultureFly.addFrame(AnimationFrame(&animVultureFlyTexture2, 150));
    }

    virtual void onSceneActivate(){
        window->setTitle("Tadzik ~TREX");
        spTadzik.setAnimation(&animTadzikRun);
        spTadzik.sprite.setPosition(offsetX, window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY);
    }

    virtual void draw(double deltaTime){
        if(gameOver){
            textScore.setString("press space to play again");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
                spTadzik.sprite.setPosition(offsetX, window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY);
                gameOver=false;
                vecCactus.clear();
                vecVulture.clear();
                result=0;
                isJumping=false;
            }
        }
        else{
            spTadzik.sprite.move(0, deltaTime * -speedY);
            spTadzik.update(deltaTime);
            double critHeight = window->getSize().y-spTadzik.sprite.getGlobalBounds().height-offsetY;
            if(spTadzik.sprite.getGlobalBounds().top < critHeight)speedY-=g;
            if(spTadzik.sprite.getGlobalBounds().top > critHeight){
                speedY=0;
                spTadzik.sprite.setPosition(offsetX, critHeight);
                isJumping=false;
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up)
               || sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
                if(!isJumping){
                    jump();
                }
            }
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
                //schylanie
            }

            manageObstacles();

            textScore.setString("score: " + stringify((int)result));

            result += speedX/10.0;
        }
        window->clear();
        for(sf::Sprite& sp : vecCactus){
            window->draw(sp);
        }
        for(AnimatedSprite& sp : vecVulture){
            sp.update(deltaTime);
            window->draw(sp.sprite);
        }
        window->draw(spTadzik.sprite);
        window->draw(textScore);
    }

    std::string stringify(int x){
        std::ostringstream o;
        o << x;
        return o.str();
    }

    void jump(){
        isJumping=true;
        speedY=0.5;
        spTadzik.sprite.move(0, -10);
    }

    void manageObstacles(){
        double addCactusChance = (double)rand()/RAND_MAX;
        if(addCactusChance <= 0.01){
            sf::Sprite spTmp(texCactus);
            spTmp.setPosition(0, 0);
            spTmp.setScale(0.4+((double)rand()/RAND_MAX)*0.1, 0.4+((double)rand()/RAND_MAX)*0.1);
            spTmp.setPosition(window->getSize().x+50, window->getSize().y-spTmp.getGlobalBounds().height-offsetY);
            vecCactus.push_back(spTmp);
        }

        for(int i = vecCactus.size()-1; i >= 0; i--){
            if(vecCactus[i].getGlobalBounds().left < -100){
                vecCactus.erase(vecCactus.begin()+i);
            }
        }

        for(int i = vecCactus.size()-1; i >= 0; i--){
            vecCactus[i].move(-speedX, 0);
            if(spTadzik.sprite.getGlobalBounds().intersects(vecCactus[i].getGlobalBounds())){
                gameOver=true;
            }
        }

        double addVultureChance = (double)rand()/RAND_MAX;
        if(addVultureChance <= 0.005){
            AnimatedSprite spTmp;
            spTmp.setAnimation(&animVultureFly);
            spTmp.sprite.setPosition(0, 0);
            spTmp.sprite.setScale(0.4+((double)rand()/RAND_MAX)*0.1, 0.4+((double)rand()/RAND_MAX)*0.1);
            spTmp.sprite.setPosition(window->getSize().x+50, window->getSize().y-spTmp.sprite.getGlobalBounds().height-offsetY);
            vecVulture.push_back(spTmp);
        }

        for(int i = vecVulture.size()-1; i >= 0; i--){
            if(vecVulture[i].sprite.getGlobalBounds().left < -100){
                vecVulture.erase(vecVulture.begin()+i);
            }
        }

        for(int i = vecVulture.size()-1; i >= 0; i--){
            vecVulture[i].sprite.move(-speedX, 0);
            if(spTadzik.sprite.getGlobalBounds().intersects(vecVulture[i].sprite.getGlobalBounds())){
                gameOver=true;
            }
        }
    }

protected:
    Animation animTadzikRun, animVultureFly;
    sf::Texture animRunTexture1, animRunTexture2;
    sf::Texture animVultureFlyTexture1, animVultureFlyTexture2;
    sf::Texture texCactus;

    AnimatedSprite spTadzik;

    double speedX=5, speedY=0.0;

    double offsetX = 32, offsetY=4;
    bool isJumping=false;
    double g = 0.03;

    double result=0;

    std::vector<sf::Sprite> vecCactus;
    std::vector<AnimatedSprite> vecVulture;
    sf::Font font;
    sf::Text textScore;
    bool gameOver=false;
};

#endif // TREX_HPP

<|endoftext|>


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

#include "wfa/virtual_people/core/model/attributes_updater/sparse_update_matrix_impl.h"

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/field_mask.pb.h"
#include "google/protobuf/repeated_field.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/measurement/common/macros.h"
#include "wfa/virtual_people/common/field_filter/field_filter.h"
#include "wfa/virtual_people/core/model/attributes_updater/attributes_updater.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/update_matrix_helper.h"

namespace wfa_virtual_people {

absl::StatusOr<std::unique_ptr<HashFieldMaskMatcher>> BuildHashFieldMaskMatcher(
    const google::protobuf::RepeatedPtrField<SparseUpdateMatrix::Column>&
        columns,
    const google::protobuf::FieldMask& hash_field_mask) {
  std::vector<const LabelerEvent*> events;
  for (const SparseUpdateMatrix::Column& column : columns) {
    events.push_back(&column.column_attrs());
  }
  return HashFieldMaskMatcher::Build(events, hash_field_mask);
}

// Converts each column to a FieldFilter, and builds a FieldFiltersMatcher
// with all the FieldFilters.
absl::StatusOr<std::unique_ptr<FieldFiltersMatcher>> BuildFieldFiltersMatcher(
    const google::protobuf::RepeatedPtrField<SparseUpdateMatrix::Column>&
        columns) {
  std::vector<std::unique_ptr<FieldFilter>> filters;
  for (const SparseUpdateMatrix::Column& column : columns) {
    filters.emplace_back();
    ASSIGN_OR_RETURN(filters.back(), FieldFilter::New(column.column_attrs()));

    if (!filters.back()) {
      return absl::InternalError("FieldFilter::New should never return NULL.");
    }
  }
  return FieldFiltersMatcher::Build(std::move(filters));
}

absl::StatusOr<std::unique_ptr<DistributedConsistentHashing>> BuildRowsHashing(
    const SparseUpdateMatrix::Column& column) {
  // Gets the probabilities distribution of the rows, and build the hashing.
  std::vector<DistributionChoice> distribution;
  for (int i = 0; i < column.probabilities_size(); i++) {
    distribution.push_back(
        DistributionChoice({i, static_cast<double>(column.probabilities(i))}));
  }
  return DistributedConsistentHashing::Build(std::move(distribution));
}

absl::StatusOr<std::unique_ptr<SparseUpdateMatrixImpl>>
SparseUpdateMatrixImpl::Build(const SparseUpdateMatrix& config) {
  if (config.columns_size() == 0) {
    return absl::InvalidArgumentError(absl::StrCat(
        "No column exists in SparseUpdateMatrix: ", config.DebugString()));
  }

  for (const SparseUpdateMatrix::Column& column : config.columns()) {
    if (!column.has_column_attrs()) {
      return absl::InvalidArgumentError(absl::StrCat(
        "No column_attrs in the column in SparseUpdateMatrix: ",
        column.DebugString()));
    }
    if (column.rows_size() == 0) {
      return absl::InvalidArgumentError(absl::StrCat(
        "No row exists in the column in SparseUpdateMatrix: ",
        column.DebugString()));
    }
    if (column.rows_size() != column.probabilities_size()) {
      return absl::InvalidArgumentError(absl::StrCat(
        "Rows and probabilities are not aligned in the column in "
        "SparseUpdateMatrix: ",
        column.DebugString()));
    }
  }

  std::unique_ptr<HashFieldMaskMatcher> hash_matcher = nullptr;
  std::unique_ptr<FieldFiltersMatcher> filters_matcher = nullptr;
  if (config.has_hash_field_mask()) {
    ASSIGN_OR_RETURN(
        hash_matcher,
        BuildHashFieldMaskMatcher(config.columns(), config.hash_field_mask()));
    if (!hash_matcher) {
      return absl::InternalError(
          "HashFieldMaskMatcher::Build should never return NULL.");
    }
  } else {
    ASSIGN_OR_RETURN(
        filters_matcher, BuildFieldFiltersMatcher(config.columns()));
    if (!filters_matcher) {
      return absl::InternalError(
          "FieldFiltersMatcher::Build should never return NULL.");
    }
  }

  // Converts the probabilities distribution of each column to
  // DistributedConsistentHashing.
  std::vector<std::unique_ptr<DistributedConsistentHashing>> row_hashings;
  // Keeps the rows of each column.
  std::vector<std::vector<LabelerEvent>> rows;
  for (const SparseUpdateMatrix::Column& column : config.columns()) {
    row_hashings.emplace_back();
    ASSIGN_OR_RETURN(
        row_hashings.back(), BuildRowsHashing(column));

    if (!row_hashings.back()) {
      return absl::InternalError(
          "DistributedConsistentHashing::Build should never return NULL.");
    }

    // Gets the rows.
    rows.push_back(std::vector<LabelerEvent>(
        {column.rows().begin(), column.rows().end()}));
  }

  PassThroughNonMatches pass_through_non_matches =
      config.pass_through_non_matches() ?
      PassThroughNonMatches::kYes : PassThroughNonMatches::kNo;

  return absl::make_unique<SparseUpdateMatrixImpl>(
      std::move(hash_matcher), std::move(filters_matcher),
      std::move(row_hashings), config.random_seed(), std::move(rows),
      pass_through_non_matches);
}

absl::Status SparseUpdateMatrixImpl::Update(LabelerEvent& event) const {
  ASSIGN_OR_RETURN(
      MatrixIndexes indexes,
      SelectFromMatrix(
          hash_matcher_.get(), filters_matcher_.get(), row_hashings_,
          random_seed_, event));
  if (indexes.column_index == kNoMatchingIndex) {
    if (pass_through_non_matches_ == PassThroughNonMatches::kYes) {
      return absl::OkStatus();
    } else {
      return absl::InvalidArgumentError(absl::StrCat(
          "No column matching for event: ", event.DebugString()));
    }
  }
  event.MergeFrom(rows_[indexes.column_index][indexes.row_index]);
  return absl::OkStatus();
}

}  // namespace wfa_virtual_people
<commit_msg>Use the reference returned by emplace_back instead of calling back.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "wfa/virtual_people/core/model/attributes_updater/sparse_update_matrix_impl.h"

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/field_mask.pb.h"
#include "google/protobuf/repeated_field.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/measurement/common/macros.h"
#include "wfa/virtual_people/common/field_filter/field_filter.h"
#include "wfa/virtual_people/core/model/attributes_updater/attributes_updater.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/update_matrix_helper.h"

namespace wfa_virtual_people {

absl::StatusOr<std::unique_ptr<HashFieldMaskMatcher>> BuildHashFieldMaskMatcher(
    const google::protobuf::RepeatedPtrField<SparseUpdateMatrix::Column>&
        columns,
    const google::protobuf::FieldMask& hash_field_mask) {
  std::vector<const LabelerEvent*> events;
  for (const SparseUpdateMatrix::Column& column : columns) {
    events.push_back(&column.column_attrs());
  }
  return HashFieldMaskMatcher::Build(events, hash_field_mask);
}

// Converts each column to a FieldFilter, and builds a FieldFiltersMatcher
// with all the FieldFilters.
absl::StatusOr<std::unique_ptr<FieldFiltersMatcher>> BuildFieldFiltersMatcher(
    const google::protobuf::RepeatedPtrField<SparseUpdateMatrix::Column>&
        columns) {
  std::vector<std::unique_ptr<FieldFilter>> filters;
  for (const SparseUpdateMatrix::Column& column : columns) {
    ASSIGN_OR_RETURN(
        filters.emplace_back(), FieldFilter::New(column.column_attrs()));

    if (!filters.back()) {
      return absl::InternalError("FieldFilter::New should never return NULL.");
    }
  }
  return FieldFiltersMatcher::Build(std::move(filters));
}

absl::StatusOr<std::unique_ptr<DistributedConsistentHashing>> BuildRowsHashing(
    const SparseUpdateMatrix::Column& column) {
  // Gets the probabilities distribution of the rows, and build the hashing.
  std::vector<DistributionChoice> distribution;
  for (int i = 0; i < column.probabilities_size(); i++) {
    distribution.push_back(
        DistributionChoice({i, static_cast<double>(column.probabilities(i))}));
  }
  return DistributedConsistentHashing::Build(std::move(distribution));
}

absl::StatusOr<std::unique_ptr<SparseUpdateMatrixImpl>>
SparseUpdateMatrixImpl::Build(const SparseUpdateMatrix& config) {
  if (config.columns_size() == 0) {
    return absl::InvalidArgumentError(absl::StrCat(
        "No column exists in SparseUpdateMatrix: ", config.DebugString()));
  }

  for (const SparseUpdateMatrix::Column& column : config.columns()) {
    if (!column.has_column_attrs()) {
      return absl::InvalidArgumentError(absl::StrCat(
        "No column_attrs in the column in SparseUpdateMatrix: ",
        column.DebugString()));
    }
    if (column.rows_size() == 0) {
      return absl::InvalidArgumentError(absl::StrCat(
        "No row exists in the column in SparseUpdateMatrix: ",
        column.DebugString()));
    }
    if (column.rows_size() != column.probabilities_size()) {
      return absl::InvalidArgumentError(absl::StrCat(
        "Rows and probabilities are not aligned in the column in "
        "SparseUpdateMatrix: ",
        column.DebugString()));
    }
  }

  std::unique_ptr<HashFieldMaskMatcher> hash_matcher = nullptr;
  std::unique_ptr<FieldFiltersMatcher> filters_matcher = nullptr;
  if (config.has_hash_field_mask()) {
    ASSIGN_OR_RETURN(
        hash_matcher,
        BuildHashFieldMaskMatcher(config.columns(), config.hash_field_mask()));
    if (!hash_matcher) {
      return absl::InternalError(
          "HashFieldMaskMatcher::Build should never return NULL.");
    }
  } else {
    ASSIGN_OR_RETURN(
        filters_matcher, BuildFieldFiltersMatcher(config.columns()));
    if (!filters_matcher) {
      return absl::InternalError(
          "FieldFiltersMatcher::Build should never return NULL.");
    }
  }

  // Converts the probabilities distribution of each column to
  // DistributedConsistentHashing.
  std::vector<std::unique_ptr<DistributedConsistentHashing>> row_hashings;
  // Keeps the rows of each column.
  std::vector<std::vector<LabelerEvent>> rows;
  for (const SparseUpdateMatrix::Column& column : config.columns()) {
    row_hashings.emplace_back();
    ASSIGN_OR_RETURN(
        row_hashings.back(), BuildRowsHashing(column));

    if (!row_hashings.back()) {
      return absl::InternalError(
          "DistributedConsistentHashing::Build should never return NULL.");
    }

    // Gets the rows.
    rows.push_back(std::vector<LabelerEvent>(
        {column.rows().begin(), column.rows().end()}));
  }

  PassThroughNonMatches pass_through_non_matches =
      config.pass_through_non_matches() ?
      PassThroughNonMatches::kYes : PassThroughNonMatches::kNo;

  return absl::make_unique<SparseUpdateMatrixImpl>(
      std::move(hash_matcher), std::move(filters_matcher),
      std::move(row_hashings), config.random_seed(), std::move(rows),
      pass_through_non_matches);
}

absl::Status SparseUpdateMatrixImpl::Update(LabelerEvent& event) const {
  ASSIGN_OR_RETURN(
      MatrixIndexes indexes,
      SelectFromMatrix(
          hash_matcher_.get(), filters_matcher_.get(), row_hashings_,
          random_seed_, event));
  if (indexes.column_index == kNoMatchingIndex) {
    if (pass_through_non_matches_ == PassThroughNonMatches::kYes) {
      return absl::OkStatus();
    } else {
      return absl::InvalidArgumentError(absl::StrCat(
          "No column matching for event: ", event.DebugString()));
    }
  }
  event.MergeFrom(rows_[indexes.column_index][indexes.row_index]);
  return absl::OkStatus();
}

}  // namespace wfa_virtual_people
<|endoftext|>