<commit_before>/*************************************************************************
 *
 *  $RCSfile: drawbase.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: os $ $Date: 2002-10-25 13:09:46 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SW_DRAWBASE_HXX
#define _SW_DRAWBASE_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif

class SwView;
class SwWrtShell;
class SwEditWin;
class KeyEvent;
class MouseEvent;

#define MIN_FREEHAND_DISTANCE   10

/*************************************************************************
|*
|* Basisklasse fuer alle Funktionen
|*
\************************************************************************/

class SwDrawBase
{
protected:
    SwView*         pView;
    SwWrtShell*     pSh;
    SwEditWin*      pWin;
    Point           aStartPos;              // Position von BeginCreate
    Point           aMDPos;                 // Position von MouseButtonDown
    USHORT          nSlotId;
    BOOL            bCreateObj  :1;
    BOOL            bInsForm    :1;

    Point           GetDefaultCenterPos();
public:
    SwDrawBase(SwWrtShell *pSh, SwEditWin* pWin, SwView* pView);
    virtual ~SwDrawBase();

    void         SetDrawPointer();
    void         EnterSelectMode(const MouseEvent& rMEvt);
    inline BOOL  IsInsertForm() const { return bInsForm; }
    inline BOOL  IsCreateObj() const { return bCreateObj; }

    // Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet
    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);

    void         BreakCreate();
    void         SetSlotId(USHORT nSlot) {nSlotId = nSlot;}

    virtual void Activate(const USHORT nSlotId);    // Function aktivieren
    virtual void Deactivate();                      // Function deaktivieren

    virtual void CreateDefaultObject();
};

#endif      // _SW_DRAWBASE_HXX

<commit_msg>INTEGRATION: CWS aw020 (1.4.914); FILE MERGED 2004/10/26 13:13:02 aw 1.4.914.1: #i33136#<commit_after>/*************************************************************************
 *
 *  $RCSfile: drawbase.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-17 09:38:58 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SW_DRAWBASE_HXX
#define _SW_DRAWBASE_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif

class SwView;
class SwWrtShell;
class SwEditWin;
class KeyEvent;
class MouseEvent;

#define MIN_FREEHAND_DISTANCE   10

/*************************************************************************
|*
|* Basisklasse fuer alle Funktionen
|*
\************************************************************************/

class SwDrawBase
{
protected:
    SwView*         pView;
    SwWrtShell*     pSh;
    SwEditWin*      pWin;
    Point           aStartPos;              // Position von BeginCreate
    Point           aMDPos;                 // Position von MouseButtonDown
    USHORT          nSlotId;
    BOOL            bCreateObj  :1;
    BOOL            bInsForm    :1;

    Point           GetDefaultCenterPos();
public:
    SwDrawBase(SwWrtShell *pSh, SwEditWin* pWin, SwView* pView);
    virtual ~SwDrawBase();

    void         SetDrawPointer();
    void         EnterSelectMode(const MouseEvent& rMEvt);
    inline BOOL  IsInsertForm() const { return bInsForm; }
    inline BOOL  IsCreateObj() const { return bCreateObj; }

    // Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet
    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);

    void         BreakCreate();
    void         SetSlotId(USHORT nSlot) {nSlotId = nSlot;}

    virtual void Activate(const USHORT nSlotId);    // Function aktivieren
    virtual void Deactivate();                      // Function deaktivieren

    virtual void CreateDefaultObject();

    // #i33136#
    virtual bool doConstructOrthogonal() const;
};

#endif      // _SW_DRAWBASE_HXX

<|endoftext|>


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

#include <shogun/base/init.h>
#include <shogun/labels/BinaryLabels.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(BinaryLabels,scores_to_probabilities)
{
	CBinaryLabels* labels=new CBinaryLabels(10);
	labels->set_values(SGVector<float64_t>(labels->get_num_labels()));

	for (index_t i=0; i<labels->get_num_labels(); ++i)
		labels->set_value(i%2==0 ? 1 : -1, i);

	labels->get_values().display_vector("scores");
	// call with 0,0 to make the method compute sigmoid parameters itself
	// g-test somehow does not allow std parameters
	labels->scores_to_probabilities(0,0);

	/* only two probabilities will be the result. Results from implementation that
	 * comes with the original paper, see BinaryLabels documentation */
	EXPECT_NEAR(labels->get_value(0), 0.8571428439385661, 10E-15);
	EXPECT_NEAR(labels->get_value(1), 0.14285715606143384, 10E-15);

	SG_UNREF(labels);
}
<commit_msg>removed print<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012-2013 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/labels/BinaryLabels.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(BinaryLabels,scores_to_probabilities)
{
	CBinaryLabels* labels=new CBinaryLabels(10);
	labels->set_values(SGVector<float64_t>(labels->get_num_labels()));

	for (index_t i=0; i<labels->get_num_labels(); ++i)
		labels->set_value(i%2==0 ? 1 : -1, i);

	//labels->get_values().display_vector("scores");
	// call with 0,0 to make the method compute sigmoid parameters itself
	// g-test somehow does not allow std parameters
	labels->scores_to_probabilities(0,0);

	/* only two probabilities will be the result. Results from implementation that
	 * comes with the original paper, see BinaryLabels documentation */
	EXPECT_NEAR(labels->get_value(0), 0.8571428439385661, 10E-15);
	EXPECT_NEAR(labels->get_value(1), 0.14285715606143384, 10E-15);

	SG_UNREF(labels);
}
<|endoftext|>


<commit_before>// @(#)root/tree:$Id$
// Author: Rene Brun   17/03/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A TLeaf for a variable length string.                                //
//////////////////////////////////////////////////////////////////////////

#include "TLeafC.h"
#include "TBranch.h"
#include "TBasket.h"
#include "TClonesArray.h"
#include "Riostream.h"
#include <string>

ClassImp(TLeafC)

//______________________________________________________________________________
TLeafC::TLeafC(): TLeaf()
{
//*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ============================

   fLenType = 1;
   fMinimum = 0;
   fMaximum = 0;
   fValue   = 0;
   fPointer = 0;
}

//______________________________________________________________________________
TLeafC::TLeafC(TBranch *parent, const char *name, const char *type)
   :TLeaf(parent, name,type)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ==============
//*-*

   fLenType = 1;
   fMinimum = 0;
   fMaximum = 0;
   fValue   = 0;
   fPointer = 0;
}

//______________________________________________________________________________
TLeafC::~TLeafC()
{
//*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ===============================

   if (ResetAddress(0,kTRUE)) delete [] fValue;
}

//______________________________________________________________________________
void TLeafC::Export(TClonesArray *list, Int_t n)
{
//*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-*
//*-*        ====================================================

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::FillBasket(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-*
//*-*                  ==========================================

   if (fPointer) fValue = *fPointer;
   Int_t len = strlen(fValue);
   if (len >= fMaximum) fMaximum = len+1;
   if (len >= fLen)     fLen = len+1;
   b.WriteFastArrayString(fValue,len);
}

//______________________________________________________________________________
const char *TLeafC::GetTypeName() const
{
//*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-*
//*-*            =========================

   if (fIsUnsigned) return "UChar_t";
   return "Char_t";
}

//______________________________________________________________________________
void TLeafC::Import(TClonesArray *list, Int_t n)
{
//*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-*
//*-*        ======================================================

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::PrintValue(Int_t) const
{
   // Prints leaf value.

   char *value = (char*)GetValuePointer();
   printf("%s",value);
}

//______________________________________________________________________________
void TLeafC::ReadBasket(TBuffer &b)
{
   // Read leaf elements from Basket input buffer.

   // Try to deal with the file written during the time where len was not
   // written to disk when len was == 0.
   Int_t readbasket = GetBranch()->GetReadBasket();
   TBasket *basket = GetBranch()->GetBasket(readbasket);
   Int_t* entryOffset = basket->GetEntryOffset();
   if (entryOffset) {
      Long64_t first = GetBranch()->GetBasketEntry()[readbasket];
      Long64_t entry = GetBranch()->GetReadEntry();
      if ( ( ( (readbasket == GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetEntries()) /* Very last entry */
               ||
               (readbasket <  GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetBasketEntry()[readbasket+1] ) /* Last entry of the basket */
             )
             &&
             ( entryOffset[entry-first] == basket->GetLast() ) /* The 'read' point is at the end of the basket */
           )
           ||
           ( entryOffset[entry-first] == entryOffset[entry-first+1] ) /* This string did not use up any space in the buffer */
         )
      {
         // Empty string
         fValue[0] = '\0';
         return;
      }
   }
   b.ReadFastArrayString(fValue,fLen);
}

//______________________________________________________________________________
void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n)
{
   // Read leaf elements from Basket input buffer
   // and export buffer to TClonesArray objects.

   UChar_t len;
   b >> len;
   if (len) {
      if (len >= fLen) len = fLen-1;
      b.ReadFastArray(fValue,len);
      fValue[len] = 0;
   } else {
      fValue[0] = 0;
   }

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::ReadValue(istream &s)
{
   // Read a string from istream s and store it into the branch buffer.

   string temp;
   s >> temp;
   if ( TestBit(kNewValue) &&
        (temp.size()+1 > ((UInt_t)fNdata))) {
      // Grow buffer if needed and we created the buffer.
      fNdata = temp.size() + 1;
      if (TestBit(kIndirectAddress) && fPointer) {
         delete [] *fPointer;
         *fPointer = new char[fNdata];
      } else {
         fValue = new char[fNdata];
      }
   }
   strlcpy(fValue,temp.c_str(),fNdata);
}

//______________________________________________________________________________
void TLeafC::SetAddress(void *add)
{
//*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-*
//*-*                  ============================

   if (ResetAddress(add)) {
      delete [] fValue;
   }
   if (add) {
      if (TestBit(kIndirectAddress)) {
         fPointer = (char**)add;
         Int_t ncountmax = fLen;
         if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1);
         if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) ||
             ncountmax > fNdata || *fPointer == 0) {
            if (*fPointer) delete [] *fPointer;
            if (ncountmax > fNdata) fNdata = ncountmax;
            *fPointer = new char[fNdata];
         }
         fValue = *fPointer;
      } else {
         fValue = (char*)add;
      }
   }
   else {
      fValue = new char[fNdata];
      fValue[0] = 0;
   }
}
<commit_msg>Avoid uninitialized memory read (past the array end) in TLeafC::ReadBasket<commit_after>// @(#)root/tree:$Id$
// Author: Rene Brun   17/03/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A TLeaf for a variable length string.                                //
//////////////////////////////////////////////////////////////////////////

#include "TLeafC.h"
#include "TBranch.h"
#include "TBasket.h"
#include "TClonesArray.h"
#include "Riostream.h"
#include <string>

ClassImp(TLeafC)

//______________________________________________________________________________
TLeafC::TLeafC(): TLeaf()
{
//*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ============================

   fLenType = 1;
   fMinimum = 0;
   fMaximum = 0;
   fValue   = 0;
   fPointer = 0;
}

//______________________________________________________________________________
TLeafC::TLeafC(TBranch *parent, const char *name, const char *type)
   :TLeaf(parent, name,type)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ==============
//*-*

   fLenType = 1;
   fMinimum = 0;
   fMaximum = 0;
   fValue   = 0;
   fPointer = 0;
}

//______________________________________________________________________________
TLeafC::~TLeafC()
{
//*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ===============================

   if (ResetAddress(0,kTRUE)) delete [] fValue;
}

//______________________________________________________________________________
void TLeafC::Export(TClonesArray *list, Int_t n)
{
//*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-*
//*-*        ====================================================

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::FillBasket(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-*
//*-*                  ==========================================

   if (fPointer) fValue = *fPointer;
   Int_t len = strlen(fValue);
   if (len >= fMaximum) fMaximum = len+1;
   if (len >= fLen)     fLen = len+1;
   b.WriteFastArrayString(fValue,len);
}

//______________________________________________________________________________
const char *TLeafC::GetTypeName() const
{
//*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-*
//*-*            =========================

   if (fIsUnsigned) return "UChar_t";
   return "Char_t";
}

//______________________________________________________________________________
void TLeafC::Import(TClonesArray *list, Int_t n)
{
//*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-*
//*-*        ======================================================

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::PrintValue(Int_t) const
{
   // Prints leaf value.

   char *value = (char*)GetValuePointer();
   printf("%s",value);
}

//______________________________________________________________________________
void TLeafC::ReadBasket(TBuffer &b)
{
   // Read leaf elements from Basket input buffer.

   // Try to deal with the file written during the time where len was not
   // written to disk when len was == 0.
   Int_t readbasket = GetBranch()->GetReadBasket();
   TBasket *basket = GetBranch()->GetBasket(readbasket);
   Int_t* entryOffset = basket->GetEntryOffset();
   if (entryOffset) {
      Long64_t first = GetBranch()->GetBasketEntry()[readbasket];
      Long64_t entry = GetBranch()->GetReadEntry();
      if ( (readbasket == GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetEntries()) /* Very last entry */
               ||
               (readbasket <  GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetBasketEntry()[readbasket+1] ) /* Last entry of the basket */
           )
         {
            if ( entryOffset[entry-first] == basket->GetLast() ) /* The 'read' point is at the end of the basket */
               {
                  // Empty string
                  fValue[0] = '\0';
                  return;
               }
         }
      else if ( entryOffset[entry-first] == entryOffset[entry-first+1] ) /* This string did not use up any space in the buffer */
         {
            // Empty string
            fValue[0] = '\0';
            return;
         }
   }
   b.ReadFastArrayString(fValue,fLen);
}

//______________________________________________________________________________
void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n)
{
   // Read leaf elements from Basket input buffer
   // and export buffer to TClonesArray objects.

   UChar_t len;
   b >> len;
   if (len) {
      if (len >= fLen) len = fLen-1;
      b.ReadFastArray(fValue,len);
      fValue[len] = 0;
   } else {
      fValue[0] = 0;
   }

   Int_t j = 0;
   for (Int_t i=0;i<n;i++) {
      memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1);
      j += fLen;
   }
}

//______________________________________________________________________________
void TLeafC::ReadValue(istream &s)
{
   // Read a string from istream s and store it into the branch buffer.

   string temp;
   s >> temp;
   if ( TestBit(kNewValue) &&
        (temp.size()+1 > ((UInt_t)fNdata))) {
      // Grow buffer if needed and we created the buffer.
      fNdata = temp.size() + 1;
      if (TestBit(kIndirectAddress) && fPointer) {
         delete [] *fPointer;
         *fPointer = new char[fNdata];
      } else {
         fValue = new char[fNdata];
      }
   }
   strlcpy(fValue,temp.c_str(),fNdata);
}

//______________________________________________________________________________
void TLeafC::SetAddress(void *add)
{
//*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-*
//*-*                  ============================

   if (ResetAddress(add)) {
      delete [] fValue;
   }
   if (add) {
      if (TestBit(kIndirectAddress)) {
         fPointer = (char**)add;
         Int_t ncountmax = fLen;
         if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1);
         if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) ||
             ncountmax > fNdata || *fPointer == 0) {
            if (*fPointer) delete [] *fPointer;
            if (ncountmax > fNdata) fNdata = ncountmax;
            *fPointer = new char[fNdata];
         }
         fValue = *fPointer;
      } else {
         fValue = (char*)add;
      }
   }
   else {
      fValue = new char[fNdata];
      fValue[0] = 0;
   }
}
<|endoftext|>


<commit_before><commit_msg>fix duplicate after merge<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify calulations of paddingBox and borderBox in InspectorOverlay.cpp<commit_after><|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_GridTopology.h"
#include "Binding_MeshTopology.h"

using namespace sofa::component::topology;
using namespace sofa::core::objectmodel;

extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setSize(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNx());
}

extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNx(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNy());
}

extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNy(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNz());
}

extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNz(nb);
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(GridTopology)
SP_CLASS_METHOD(GridTopology,setSize)
SP_CLASS_METHOD(GridTopology,getNx)
SP_CLASS_METHOD(GridTopology,getNy)
SP_CLASS_METHOD(GridTopology,getNz)
SP_CLASS_METHOD(GridTopology,setNx)
SP_CLASS_METHOD(GridTopology,setNy)
SP_CLASS_METHOD(GridTopology,setNz)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology)

<commit_msg>[SofaPython] proper error handling<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_GridTopology.h"
#include "Binding_MeshTopology.h"

using namespace sofa::component::topology;
using namespace sofa::core::objectmodel;

extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setSize(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_setNumVertices(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNumVertices(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNx());
}

extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNx(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNy());
}

extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNy(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNz());
}

extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNz(nb);
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(GridTopology)
SP_CLASS_METHOD(GridTopology,setSize)
SP_CLASS_METHOD(GridTopology,setNumVertices)
SP_CLASS_METHOD(GridTopology,getNx)
SP_CLASS_METHOD(GridTopology,getNy)
SP_CLASS_METHOD(GridTopology,getNz)
SP_CLASS_METHOD(GridTopology,setNx)
SP_CLASS_METHOD(GridTopology,setNy)
SP_CLASS_METHOD(GridTopology,setNz)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology)

<|endoftext|>


<commit_before>#include "backends.hpp"

#include<string>
#include<armadillo>

using namespace std;
using namespace arma;

#define DIM_NAME "__hide"
#define ATTR_NAME "sample"
#define ROW_NAME "samples"
#define COL_NAME "channels"
#define RANGE_SIZE 4

string TileDBBackend::mrn_to_array_name(string mrn)
{
  return mrn + "-tiledb";
}

string TileDBBackend::get_workspace()
{
  return DATADIR;
}

int TileDBBackend::get_fs(string mrn)
{
  return 256; // TODO(joshblum) store this in TileDB metadata when it's implemented
}

int TileDBBackend::get_array_len(string mrn)
{
  return 84992; // TODO(joshblum) store this in TileDB metadata when it's implemented
}

void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata)
{

}

void TileDBBackend::open_array(string mrn)
{
  if (in_cache(mrn))
  {
    return;
  }
  TileDB_CTX* tiledb_ctx;
  tiledb_ctx_init(tiledb_ctx);
  string group = "";
  string workspace = get_workspace();
  string array_name = mrn_to_array_name(mrn);
  const char* mode = "r";
  int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode);
  put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id));
}

void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf)
{
  tiledb_cache_pair cache_pair = get_cache(mrn);
  TileDB_CTX* tiledb_ctx = cache_pair.first;
  int array_id = cache_pair.second;

  double* range = new double[RANGE_SIZE];
  range[0] = CH_REVERSE_IDX[ch];
  range[1] = CH_REVERSE_IDX[ch];
  range[2] = start_offset;
  range[3] = end_offset;

  const char* dim_names = DIM_NAME;
  int dim_names_num = 1;
  const char* attribute_names = ATTR_NAME;
  int attribute_names_num = 1;
  size_t cell_buf_size = sizeof(float) * buf.n_elem;
  tiledb_subarray_buf(tiledb_ctx, array_id, range,
      RANGE_SIZE, &dim_names, dim_names_num,
      &attribute_names, attribute_names_num,
      buf.memptr(), &cell_buf_size);
}

void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf)
{
}

void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf)
{
}

void TileDBBackend::close_array(string mrn)
{
  if (in_cache(mrn))
  {
    tiledb_cache_pair pair = get_cache(mrn);
    tiledb_array_close(pair.first, pair.second);
    pop_cache(mrn);
  }
}

void TileDBBackend::edf_to_array(string mrn)
{
  EDFBackend edf_backend;
  edf_backend.open_array(mrn);

  int nchannels = NCHANNELS;
  int nsamples = edf_backend.get_array_len(mrn);
  int fs = edf_backend.get_fs(mrn); // TODO(joshblum) store this in TileDB metadata when it's implemented
  cout << "Writing " << nsamples << " samples with fs=" << fs << "." << endl;

  string group = "";
  string workspace = get_workspace();
  string array_name = mrn_to_array_name(mrn);
  // csv of array schema
  string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(nsamples) + ",0," + to_string(nchannels) + ",float32,int32,*,column-major,*,*,*,*";

  // Initialize TileDB
  TileDB_CTX* tiledb_ctx;
  tiledb_ctx_init(tiledb_ctx);

  cout << "Defining TileDB schema." << endl;
  // Store the array schema
  if (tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str()))
  {
    tiledb_ctx_finalize(tiledb_ctx);
    return;
  }

  cout << "Opening TileDB array." << endl;
  const char* mode = "a";
  int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode);

  cout << "Writing cells to TileDB." << endl;
  int ch, start_offset, end_offset;
  cell_t cell;
  for (int i = 0; i < nchannels; i++)
  {
    ch = CHANNEL_ARRAY[i];
    start_offset = 0;
    end_offset = min(nsamples, CHUNK_SIZE);
    frowvec chunk_buf = frowvec(end_offset); // store samples from each channel here

    // read chunks from each signal and write them
    for (; end_offset <= nsamples; end_offset = min(end_offset + CHUNK_SIZE, nsamples))
    {
      if (end_offset - start_offset != CHUNK_SIZE) {
        chunk_buf.resize(end_offset - start_offset);
      }
      edf_backend.read_array(mrn, ch, start_offset, end_offset, chunk_buf);

      // write chunk_mat to file
      for (uword i = 0; i < chunk_buf.n_elem; i++)
      {
        // x coord, y coord, attribute
        cell.x = CH_REVERSE_IDX[ch];
        cell.y = start_offset + i;
        cell.sample = chunk_buf(i);
        tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell);
      }

      start_offset = end_offset;
      // ensure we write the last part of the samples
      if (end_offset == nsamples)
      {
        break;
      }

      if (!(ch % 2 || (end_offset / CHUNK_SIZE) % 10)) // print for even channels every 10 chunks (40MB)
      {
        cout << "Wrote " << end_offset / CHUNK_SIZE << " chunks for ch: " << ch << endl;
      }
    }
  }

  // Finalize TileDB
  tiledb_array_close(tiledb_ctx, array_id);
  tiledb_ctx_finalize(tiledb_ctx);
  cout << "Conversion complete." << endl;
}

<commit_msg>read/write mode on tiledb<commit_after>#include "backends.hpp"

#include<string>
#include<armadillo>

using namespace std;
using namespace arma;

#define DIM_NAME "__hide"
#define ATTR_NAME "sample"
#define ROW_NAME "samples"
#define COL_NAME "channels"
#define RANGE_SIZE 4

string TileDBBackend::mrn_to_array_name(string mrn)
{
  return mrn + "-tiledb";
}

string TileDBBackend::get_workspace()
{
  return DATADIR;
}

int TileDBBackend::get_fs(string mrn)
{
  return 256; // TODO(joshblum) store this in TileDB metadata when it's implemented
}

int TileDBBackend::get_array_len(string mrn)
{
  return 84992; // TODO(joshblum) store this in TileDB metadata when it's implemented
}

void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata)
{

}

void TileDBBackend::open_array(string mrn)
{
  if (in_cache(mrn))
  {
    return;
  }
  TileDB_CTX* tiledb_ctx;
  tiledb_ctx_init(tiledb_ctx);
  string group = "";
  string workspace = get_workspace();
  string array_name = mrn_to_array_name(mrn);
  const char* mode = "r"; // TODO(joshblum): if read/write available this would be better
  int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode);
  put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id));
}

void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf)
{
  tiledb_cache_pair cache_pair = get_cache(mrn);
  TileDB_CTX* tiledb_ctx = cache_pair.first;
  int array_id = cache_pair.second;

  double* range = new double[RANGE_SIZE];
  range[0] = CH_REVERSE_IDX[ch];
  range[1] = CH_REVERSE_IDX[ch];
  range[2] = start_offset;
  range[3] = end_offset;

  const char* dim_names = DIM_NAME;
  int dim_names_num = 1;
  const char* attribute_names = ATTR_NAME;
  int attribute_names_num = 1;
  size_t cell_buf_size = sizeof(float) * buf.n_elem;
  tiledb_subarray_buf(tiledb_ctx, array_id, range,
      RANGE_SIZE, &dim_names, dim_names_num,
      &attribute_names, attribute_names_num,
      buf.memptr(), &cell_buf_size);
}

void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf)
{
}

void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf)
{
}

void TileDBBackend::close_array(string mrn)
{
  if (in_cache(mrn))
  {
    tiledb_cache_pair pair = get_cache(mrn);
    tiledb_array_close(pair.first, pair.second);
    pop_cache(mrn);
  }
}

void TileDBBackend::edf_to_array(string mrn)
{
  EDFBackend edf_backend;
  edf_backend.open_array(mrn);

  int nchannels = NCHANNELS;
  int nsamples = edf_backend.get_array_len(mrn);
  int fs = edf_backend.get_fs(mrn); // TODO(joshblum) store this in TileDB metadata when it's implemented
  cout << "Writing " << nsamples << " samples with fs=" << fs << "." << endl;

  string group = "";
  string workspace = get_workspace();
  string array_name = mrn_to_array_name(mrn);
  // csv of array schema
  string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(nsamples) + ",0," + to_string(nchannels) + ",float32,int32,*,column-major,*,*,*,*";

  // Initialize TileDB
  TileDB_CTX* tiledb_ctx;
  tiledb_ctx_init(tiledb_ctx);

  cout << "Defining TileDB schema." << endl;
  // Store the array schema
  if (tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str()))
  {
    tiledb_ctx_finalize(tiledb_ctx);
    return;
  }

  cout << "Opening TileDB array." << endl;
  const char* mode = "a";
  int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode);

  cout << "Writing cells to TileDB." << endl;
  int ch, start_offset, end_offset;
  cell_t cell;
  for (int i = 0; i < nchannels; i++)
  {
    ch = CHANNEL_ARRAY[i];
    start_offset = 0;
    end_offset = min(nsamples, CHUNK_SIZE);
    frowvec chunk_buf = frowvec(end_offset); // store samples from each channel here

    // read chunks from each signal and write them
    for (; end_offset <= nsamples; end_offset = min(end_offset + CHUNK_SIZE, nsamples))
    {
      if (end_offset - start_offset != CHUNK_SIZE) {
        chunk_buf.resize(end_offset - start_offset);
      }
      edf_backend.read_array(mrn, ch, start_offset, end_offset, chunk_buf);

      // write chunk_mat to file
      for (uword i = 0; i < chunk_buf.n_elem; i++)
      {
        // x coord, y coord, attribute
        cell.x = CH_REVERSE_IDX[ch];
        cell.y = start_offset + i;
        cell.sample = chunk_buf(i);
        tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell);
      }

      start_offset = end_offset;
      // ensure we write the last part of the samples
      if (end_offset == nsamples)
      {
        break;
      }

      if (!(ch % 2 || (end_offset / CHUNK_SIZE) % 10)) // print for even channels every 10 chunks (40MB)
      {
        cout << "Wrote " << end_offset / CHUNK_SIZE << " chunks for ch: " << ch << endl;
      }
    }
  }

  // Finalize TileDB
  tiledb_array_close(tiledb_ctx, array_id);
  tiledb_ctx_finalize(tiledb_ctx);
  cout << "Conversion complete." << endl;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

//Own
#include "submarine.h"
#include "submarine_p.h"
#include "torpedo.h"
#include "pixmapitem.h"
#include "graphicsscene.h"
#include "animationmanager.h"
#include "custompropertyanimation.h"
#include "qanimationstate.h"

#include <QtCore/QPropertyAnimation>
#include <QtCore/QStateMachine>
#include <QtCore/QFinalState>
#include <QtCore/QSequentialAnimationGroup>

static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub)
{
    QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub);
#if QT_VERSION >=0x040500
    PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub);
    step1->setZValue(6);
    PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub);
    step2->setZValue(6);
    PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub);
    step3->setZValue(6);
    PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub);
    step4->setZValue(6);
    step1->setOpacity(0);
    step2->setOpacity(0);
    step3->setOpacity(0);
    step4->setOpacity(0);
    CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub);
    anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim1->setDuration(100);
    anim1->setEndValue(1);
    CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub);
    anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim2->setDuration(100);
    anim2->setEndValue(1);
    CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub);
    anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim3->setDuration(100);
    anim3->setEndValue(1);
    CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub);
    anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim4->setDuration(100);
    anim4->setEndValue(1);
    group->addAnimation(anim1);
    group->addAnimation(anim2);
    group->addAnimation(anim3);
    group->addAnimation(anim4);
#else
    // work around for a bug where we don't transition if the duration is zero.
    QtPauseAnimation *anim = new QtPauseAnimation(group);
    anim->setDuration(1);
    group->addAnimation(anim);
#endif
    AnimationManager::self()->registerAnimation(group);
    return group;
}

SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags)
    : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None)
{
    pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    setZValue(5);
    setFlags(QGraphicsItem::ItemIsMovable);
    resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height());
    setTransformOriginPoint(boundingRect().center());

    graphicsRotation = new QGraphicsRotation(this);
    graphicsRotation->setAxis(QVector3D(0, 1, 0));
    graphicsRotation->setOrigin(QPointF(size().width()/2, size().height()/2));
    QList<QGraphicsTransform *> r;
    r.append(graphicsRotation);
    setTransformations(r);

    //We setup the state machine of the submarine
    QStateMachine *machine = new QStateMachine(this);

    //This state is when the boat is moving/rotating
    QState *moving = new QState(machine);

    //This state is when the boat is moving from left to right
    MovementState *movement = new MovementState(this, moving);

    //This state is when the boat is moving from left to right
    ReturnState *rotation = new ReturnState(this, moving);

    //This is the initial state of the moving root state
    moving->setInitialState(movement);

    movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving);

    //This is the initial state of the machine
    machine->setInitialState(moving);

    //End
    QFinalState *final = new QFinalState(machine);

    //If the moving animation is finished we move to the return state
    movement->addTransition(movement, SIGNAL(animationFinished()), rotation);

    //If the return animation is finished we move to the moving state
    rotation->addTransition(rotation, SIGNAL(animationFinished()), movement);

    //This state play the destroyed animation
    QAnimationState *destroyedState = new QAnimationState(machine);
    destroyedState->setAnimation(setupDestroyAnimation(this));

    //Play a nice animation when the submarine is destroyed
    moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState);

    //Transition to final state when the destroyed animation is finished
    destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final);

    //The machine has finished to be executed, then the submarine is dead
    connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished()));

    machine->start();
}

int SubMarine::points()
{
    return subPoints;
}

void SubMarine::setCurrentDirection(SubMarine::Movement direction)
{
    if (this->direction == direction)
        return;
    if (direction == SubMarine::Right && this->direction == SubMarine::None) {
          graphicsRotation->setAngle(180);
    }
    this->direction = direction;
}

enum SubMarine::Movement SubMarine::currentDirection() const
{
    return direction;
}

void SubMarine::setCurrentSpeed(int speed)
{
    if (speed < 0 || speed > 3) {
        qWarning("SubMarine::setCurrentSpeed : The speed is invalid");
    }
    this->speed = speed;
    emit subMarineStateChanged();
}

int SubMarine::currentSpeed() const
{
    return speed;
}

void SubMarine::launchTorpedo(int speed)
{
    Torpedo * torp = new Torpedo();
    GraphicsScene *scene = static_cast<GraphicsScene *>(this->scene());
    scene->addItem(torp);
    torp->setPos(x(), y());
    torp->setCurrentSpeed(speed);
    torp->launch();
}

void SubMarine::destroy()
{
    emit subMarineDestroyed();
}

int SubMarine::type() const
{
    return Type;
}
<commit_msg>Fix sub-attaq after the QGraphicsTransform changes<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

//Own
#include "submarine.h"
#include "submarine_p.h"
#include "torpedo.h"
#include "pixmapitem.h"
#include "graphicsscene.h"
#include "animationmanager.h"
#include "custompropertyanimation.h"
#include "qanimationstate.h"

#include <QtCore/QPropertyAnimation>
#include <QtCore/QStateMachine>
#include <QtCore/QFinalState>
#include <QtCore/QSequentialAnimationGroup>

static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub)
{
    QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub);
#if QT_VERSION >=0x040500
    PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub);
    step1->setZValue(6);
    PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub);
    step2->setZValue(6);
    PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub);
    step3->setZValue(6);
    PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub);
    step4->setZValue(6);
    step1->setOpacity(0);
    step2->setOpacity(0);
    step3->setOpacity(0);
    step4->setOpacity(0);
    CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub);
    anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim1->setDuration(100);
    anim1->setEndValue(1);
    CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub);
    anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim2->setDuration(100);
    anim2->setEndValue(1);
    CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub);
    anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim3->setDuration(100);
    anim3->setEndValue(1);
    CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub);
    anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity);
    anim4->setDuration(100);
    anim4->setEndValue(1);
    group->addAnimation(anim1);
    group->addAnimation(anim2);
    group->addAnimation(anim3);
    group->addAnimation(anim4);
#else
    // work around for a bug where we don't transition if the duration is zero.
    QtPauseAnimation *anim = new QtPauseAnimation(group);
    anim->setDuration(1);
    group->addAnimation(anim);
#endif
    AnimationManager::self()->registerAnimation(group);
    return group;
}

SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags)
    : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None)
{
    pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    setZValue(5);
    setFlags(QGraphicsItem::ItemIsMovable);
    resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height());
    setTransformOriginPoint(boundingRect().center());

    graphicsRotation = new QGraphicsRotation(this);
    graphicsRotation->setAxis(QVector3D(0, 1, 0));
    graphicsRotation->setOrigin(QVector3D(size().width()/2, size().height()/2, 0));
    QList<QGraphicsTransform *> r;
    r.append(graphicsRotation);
    setTransformations(r);

    //We setup the state machine of the submarine
    QStateMachine *machine = new QStateMachine(this);

    //This state is when the boat is moving/rotating
    QState *moving = new QState(machine);

    //This state is when the boat is moving from left to right
    MovementState *movement = new MovementState(this, moving);

    //This state is when the boat is moving from left to right
    ReturnState *rotation = new ReturnState(this, moving);

    //This is the initial state of the moving root state
    moving->setInitialState(movement);

    movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving);

    //This is the initial state of the machine
    machine->setInitialState(moving);

    //End
    QFinalState *final = new QFinalState(machine);

    //If the moving animation is finished we move to the return state
    movement->addTransition(movement, SIGNAL(animationFinished()), rotation);

    //If the return animation is finished we move to the moving state
    rotation->addTransition(rotation, SIGNAL(animationFinished()), movement);

    //This state play the destroyed animation
    QAnimationState *destroyedState = new QAnimationState(machine);
    destroyedState->setAnimation(setupDestroyAnimation(this));

    //Play a nice animation when the submarine is destroyed
    moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState);

    //Transition to final state when the destroyed animation is finished
    destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final);

    //The machine has finished to be executed, then the submarine is dead
    connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished()));

    machine->start();
}

int SubMarine::points()
{
    return subPoints;
}

void SubMarine::setCurrentDirection(SubMarine::Movement direction)
{
    if (this->direction == direction)
        return;
    if (direction == SubMarine::Right && this->direction == SubMarine::None) {
          graphicsRotation->setAngle(180);
    }
    this->direction = direction;
}

enum SubMarine::Movement SubMarine::currentDirection() const
{
    return direction;
}

void SubMarine::setCurrentSpeed(int speed)
{
    if (speed < 0 || speed > 3) {
        qWarning("SubMarine::setCurrentSpeed : The speed is invalid");
    }
    this->speed = speed;
    emit subMarineStateChanged();
}

int SubMarine::currentSpeed() const
{
    return speed;
}

void SubMarine::launchTorpedo(int speed)
{
    Torpedo * torp = new Torpedo();
    GraphicsScene *scene = static_cast<GraphicsScene *>(this->scene());
    scene->addItem(torp);
    torp->setPos(x(), y());
    torp->setCurrentSpeed(speed);
    torp->launch();
}

void SubMarine::destroy()
{
    emit subMarineDestroyed();
}

int SubMarine::type() const
{
    return Type;
}
<|endoftext|>


<commit_before><commit_msg>TODO-697: minimising SPI activity<commit_after><|endoftext|>


<commit_before><commit_msg>no extra UI feedback right after POST<commit_after><|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <unistd.h>
#include <string>
#include <tbb/atomic.h>

#include <iostream> // TODO: remove me!

#include "../../cvmfs/util.h"
#include "../../cvmfs/upload_spooler_definition.h"
#include "../../cvmfs/upload_local.h"
#include "../../cvmfs/hash.h"
#include "../../cvmfs/file_processing/char_buffer.h"

#include "testutil.h"
#include "c_file_sandbox.h"

using namespace upload;

class UploadCallbacks {
 public:
  UploadCallbacks() {
    simple_upload_invocations = 0;
  }

  void SimpleUploadClosure(const UploaderResults &results,
                                 UploaderResults  expected) {
    EXPECT_EQ (expected.return_code, results.return_code);
    EXPECT_EQ (expected.local_path,  results.local_path);
    ++simple_upload_invocations;
  }

 public:
  tbb::atomic<unsigned int> simple_upload_invocations;
};

class T_LocalUploader : public FileSandbox {
 private:
  static const std::string sandbox_path;
  static const std::string dest_dir;
  static const std::string tmp_dir;

 public:
  T_LocalUploader() :
    FileSandbox(T_LocalUploader::sandbox_path) {}

 protected:
  virtual void SetUp() {
    CreateSandbox(T_LocalUploader::tmp_dir);

    const bool success = MkdirDeep(T_LocalUploader::dest_dir, 0700);
    ASSERT_TRUE (success) << "Failed to create uploader destination dir";
    InitializeStorageBackend();

    uploader_ = AbstractUploader::Construct(GetSpoolerDefinition());
    ASSERT_NE (static_cast<AbstractUploader*>(NULL), uploader_);
  }

  virtual void TearDown() {
    if (uploader_ != NULL) {
      uploader_->TearDown();
      delete uploader_;
      uploader_ = NULL;
    }
    RemoveSandbox(T_LocalUploader::tmp_dir);
  }

  void InitializeStorageBackend() {
    const std::string &dir = T_LocalUploader::dest_dir + "/data";
    bool success = MkdirDeep(dir + "/txn", 0700);
    ASSERT_TRUE (success) << "Failed to create transaction tmp dir";
    for (unsigned int i = 0; i <= 255; ++i) {
      success = MkdirDeep(dir + "/" + ByteToHex(static_cast<char>(i)), 0700);
      ASSERT_TRUE (success);
    }
  }

  SpoolerDefinition GetSpoolerDefinition() const {
    const std::string spl_type   = "local";
    const std::string spl_tmp    = T_LocalUploader::tmp_dir;
    const std::string spl_cfg    = T_LocalUploader::dest_dir;
    const std::string definition = spl_type + "," + spl_tmp + "," + spl_cfg;
    const bool use_file_chunking = true;
    const size_t min_chunk_size  = 0;   // chunking does not matter here, we are
    const size_t avg_chunk_size  = 1;   // only testing the upload module.
    const size_t max_chunk_size  = 2;

    return SpoolerDefinition(definition, use_file_chunking, min_chunk_size,
                                                            avg_chunk_size,
                                                            max_chunk_size);
  }

  bool CheckFile(const std::string &remote_path) const {
    const std::string absolute_path = AbsoluteDestinationPath(remote_path);
    return FileExists(absolute_path);
  }

  bool CompareFileContents(const std::string &testee_path,
                           const std::string &reference_path) const {
    shash::Any testee_hash    = HashFile(testee_path);
    shash::Any reference_hash = HashFile(reference_path);
    return testee_hash == reference_hash;
  }

  std::string AbsoluteDestinationPath(const std::string &remote_path) const {
    return T_LocalUploader::dest_dir + "/" + remote_path;
  }

 private:
  std::string ByteToHex(const unsigned char byte) {
    const char pos_1 = byte / 16;
    const char pos_0 = byte % 16;
    const char hex[3] = {
      (pos_1 <= 9) ? '0' + pos_1 : 'a' + (pos_1 - 10),
      (pos_0 <= 9) ? '0' + pos_0 : 'a' + (pos_0 - 10),
      0
    };
    return std::string(hex);
  }

  shash::Any HashFile(const std::string &path) const {
    shash::Any result(shash::kMd5);
    // googletest requires method that use EXPECT_* or ASSERT_* to return void
    HashFileInternal (path, &result);
    return result;
  }

  void HashFileInternal(const std::string &path, shash::Any *hash) const {
    const bool successful = shash::HashFile(path, hash);
    ASSERT_TRUE (successful);
  }

 protected:
  AbstractUploader *uploader_;
  UploadCallbacks   delegate_;
};

const std::string T_LocalUploader::sandbox_path = "/tmp/cvmfs_ut_localuploader";
const std::string T_LocalUploader::tmp_dir      = T_LocalUploader::sandbox_path + "/tmp";
const std::string T_LocalUploader::dest_dir     = T_LocalUploader::sandbox_path + "/dest";

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, Initialize) {
  // nothing to do here... initialization runs completely in the fixture!
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, SimpleFileUpload) {
  const std::string big_file_path = GetBigFile();
  const std::string dest_name     = "big_file";

  uploader_->Upload(big_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, big_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(big_file_path,
                                   AbsoluteDestinationPath(dest_name)));
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, PeekIntoStorage) {
  const std::string small_file_path = GetSmallFile();
  const std::string dest_name       = "small_file";

  uploader_->Upload(small_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, small_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(small_file_path,
                                   AbsoluteDestinationPath(dest_name)));

  const bool file_exists = uploader_->Peek(dest_name);
  EXPECT_TRUE (file_exists);

  const bool file_doesnt_exist = uploader_->Peek("alien");
  EXPECT_FALSE (file_doesnt_exist);
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, RemoveFromStorage) {
  const std::string small_file_path = GetSmallFile();
  const std::string dest_name       = "also_small_file";

  uploader_->Upload(small_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, small_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(small_file_path,
                                   AbsoluteDestinationPath(dest_name)));

  const bool file_exists = uploader_->Peek(dest_name);
  EXPECT_TRUE (file_exists);

  const bool removed_successfully = uploader_->Remove(dest_name);
  EXPECT_TRUE (removed_successfully);

  EXPECT_FALSE(CheckFile(dest_name));
  const bool file_still_exists = uploader_->Peek(dest_name);
  EXPECT_FALSE (file_still_exists);
}

<commit_msg>TEST: edge cases: huge file and empty file upload<commit_after>#include <gtest/gtest.h>
#include <unistd.h>
#include <string>
#include <tbb/atomic.h>

#include <iostream> // TODO: remove me!

#include "../../cvmfs/util.h"
#include "../../cvmfs/upload_spooler_definition.h"
#include "../../cvmfs/upload_local.h"
#include "../../cvmfs/hash.h"
#include "../../cvmfs/file_processing/char_buffer.h"

#include "testutil.h"
#include "c_file_sandbox.h"

using namespace upload;

class UploadCallbacks {
 public:
  UploadCallbacks() {
    simple_upload_invocations = 0;
  }

  void SimpleUploadClosure(const UploaderResults &results,
                                 UploaderResults  expected) {
    EXPECT_EQ (expected.return_code, results.return_code);
    EXPECT_EQ (expected.local_path,  results.local_path);
    ++simple_upload_invocations;
  }

 public:
  tbb::atomic<unsigned int> simple_upload_invocations;
};

class T_LocalUploader : public FileSandbox {
 private:
  static const std::string sandbox_path;
  static const std::string dest_dir;
  static const std::string tmp_dir;

 public:
  T_LocalUploader() :
    FileSandbox(T_LocalUploader::sandbox_path) {}

 protected:
  virtual void SetUp() {
    CreateSandbox(T_LocalUploader::tmp_dir);

    const bool success = MkdirDeep(T_LocalUploader::dest_dir, 0700);
    ASSERT_TRUE (success) << "Failed to create uploader destination dir";
    InitializeStorageBackend();

    uploader_ = AbstractUploader::Construct(GetSpoolerDefinition());
    ASSERT_NE (static_cast<AbstractUploader*>(NULL), uploader_);
  }

  virtual void TearDown() {
    if (uploader_ != NULL) {
      uploader_->TearDown();
      delete uploader_;
      uploader_ = NULL;
    }
    RemoveSandbox(T_LocalUploader::tmp_dir);
  }

  void InitializeStorageBackend() {
    const std::string &dir = T_LocalUploader::dest_dir + "/data";
    bool success = MkdirDeep(dir + "/txn", 0700);
    ASSERT_TRUE (success) << "Failed to create transaction tmp dir";
    for (unsigned int i = 0; i <= 255; ++i) {
      success = MkdirDeep(dir + "/" + ByteToHex(static_cast<char>(i)), 0700);
      ASSERT_TRUE (success);
    }
  }

  SpoolerDefinition GetSpoolerDefinition() const {
    const std::string spl_type   = "local";
    const std::string spl_tmp    = T_LocalUploader::tmp_dir;
    const std::string spl_cfg    = T_LocalUploader::dest_dir;
    const std::string definition = spl_type + "," + spl_tmp + "," + spl_cfg;
    const bool use_file_chunking = true;
    const size_t min_chunk_size  = 0;   // chunking does not matter here, we are
    const size_t avg_chunk_size  = 1;   // only testing the upload module.
    const size_t max_chunk_size  = 2;

    return SpoolerDefinition(definition, use_file_chunking, min_chunk_size,
                                                            avg_chunk_size,
                                                            max_chunk_size);
  }

  bool CheckFile(const std::string &remote_path) const {
    const std::string absolute_path = AbsoluteDestinationPath(remote_path);
    return FileExists(absolute_path);
  }

  bool CompareFileContents(const std::string &testee_path,
                           const std::string &reference_path) const {
    shash::Any testee_hash    = HashFile(testee_path);
    shash::Any reference_hash = HashFile(reference_path);
    return testee_hash == reference_hash;
  }

  std::string AbsoluteDestinationPath(const std::string &remote_path) const {
    return T_LocalUploader::dest_dir + "/" + remote_path;
  }

 private:
  std::string ByteToHex(const unsigned char byte) {
    const char pos_1 = byte / 16;
    const char pos_0 = byte % 16;
    const char hex[3] = {
      (pos_1 <= 9) ? '0' + pos_1 : 'a' + (pos_1 - 10),
      (pos_0 <= 9) ? '0' + pos_0 : 'a' + (pos_0 - 10),
      0
    };
    return std::string(hex);
  }

  shash::Any HashFile(const std::string &path) const {
    shash::Any result(shash::kMd5);
    // googletest requires method that use EXPECT_* or ASSERT_* to return void
    HashFileInternal (path, &result);
    return result;
  }

  void HashFileInternal(const std::string &path, shash::Any *hash) const {
    const bool successful = shash::HashFile(path, hash);
    ASSERT_TRUE (successful);
  }

 protected:
  AbstractUploader *uploader_;
  UploadCallbacks   delegate_;
};

const std::string T_LocalUploader::sandbox_path = "/tmp/cvmfs_ut_localuploader";
const std::string T_LocalUploader::tmp_dir      = T_LocalUploader::sandbox_path + "/tmp";
const std::string T_LocalUploader::dest_dir     = T_LocalUploader::sandbox_path + "/dest";

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, Initialize) {
  // nothing to do here... initialization runs completely in the fixture!
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, SimpleFileUpload) {
  const std::string big_file_path = GetBigFile();
  const std::string dest_name     = "big_file";

  uploader_->Upload(big_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, big_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(big_file_path,
                                   AbsoluteDestinationPath(dest_name)));
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, PeekIntoStorage) {
  const std::string small_file_path = GetSmallFile();
  const std::string dest_name       = "small_file";

  uploader_->Upload(small_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, small_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(small_file_path,
                                   AbsoluteDestinationPath(dest_name)));

  const bool file_exists = uploader_->Peek(dest_name);
  EXPECT_TRUE (file_exists);

  const bool file_doesnt_exist = uploader_->Peek("alien");
  EXPECT_FALSE (file_doesnt_exist);
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, RemoveFromStorage) {
  const std::string small_file_path = GetSmallFile();
  const std::string dest_name       = "also_small_file";

  uploader_->Upload(small_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, small_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(small_file_path,
                                   AbsoluteDestinationPath(dest_name)));

  const bool file_exists = uploader_->Peek(dest_name);
  EXPECT_TRUE (file_exists);

  const bool removed_successfully = uploader_->Remove(dest_name);
  EXPECT_TRUE (removed_successfully);

  EXPECT_FALSE(CheckFile(dest_name));
  const bool file_still_exists = uploader_->Peek(dest_name);
  EXPECT_FALSE (file_still_exists);
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, UploadEmptyFile) {
  const std::string empty_file_path = GetEmptyFile();
  const std::string dest_name     = "empty_file";

  uploader_->Upload(empty_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, empty_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(empty_file_path,
                                   AbsoluteDestinationPath(dest_name)));
  EXPECT_EQ (0, GetFileSize(AbsoluteDestinationPath(dest_name)));
}

//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

TEST_F(T_LocalUploader, UploadHugeFile) {
  const std::string huge_file_path = GetHugeFile();
  const std::string dest_name     = "huge_file";

  uploader_->Upload(huge_file_path, dest_name,
    AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure,
                                  &delegate_,
                                  UploaderResults(0, huge_file_path)));
  uploader_->WaitForUpload();

  EXPECT_TRUE (CheckFile(dest_name));
  EXPECT_EQ (1u, delegate_.simple_upload_invocations);
  EXPECT_TRUE (CompareFileContents(huge_file_path,
                                   AbsoluteDestinationPath(dest_name)));
}
<|endoftext|>


<commit_before>#include "base/logging.hpp"

#include "indexer/feature.hpp"

#include "editor/changeset_wrapper.hpp"

#include "std/algorithm.hpp"
#include "std/sstream.hpp"
#include "std/map.hpp"

#include "geometry/mercator.hpp"

#include "private.h"

using editor::XMLFeature;

namespace
{
double ScoreLatLon(XMLFeature const & xmlFt, ms::LatLon const & latLon)
{
  double constexpr eps = MercatorBounds::GetCellID2PointAbsEpsilon();
  return latLon.EqualDxDy(xmlFt.GetCenter(), eps);
}

double ScoreNames(XMLFeature const & xmlFt, StringUtf8Multilang const & names)
{
  double score = 0;
  names.ForEachRef([&score, &xmlFt](uint8_t const langCode, string const & name)
                   {
                     if (xmlFt.GetName(langCode) == name)
                       score += 1;
                     return true;
                   });

  // TODO(mgsergio): Deafult name match should have greater wieght. Should it?

  return score;
}

vector<string> GetOsmOriginalTagsForType(feature::Metadata::EType const et)
{
  static multimap<feature::Metadata::EType, string> const kFmd2Osm = {
    {feature::Metadata::EType::FMD_CUISINE, "cuisine"},
    {feature::Metadata::EType::FMD_OPEN_HOURS, "opening_hours"},
    {feature::Metadata::EType::FMD_PHONE_NUMBER, "phone"},
    {feature::Metadata::EType::FMD_PHONE_NUMBER, "contact:phone"},
    {feature::Metadata::EType::FMD_FAX_NUMBER, "fax"},
    {feature::Metadata::EType::FMD_FAX_NUMBER, "contact:fax"},
    {feature::Metadata::EType::FMD_STARS, "stars"},
    {feature::Metadata::EType::FMD_OPERATOR, "operator"},
    {feature::Metadata::EType::FMD_URL, "url"},
    {feature::Metadata::EType::FMD_WEBSITE, "website"},
    {feature::Metadata::EType::FMD_WEBSITE, "contact:website"},
    // TODO: {feature::Metadata::EType::FMD_INTERNET, ""},
    {feature::Metadata::EType::FMD_ELE, "ele"},
    {feature::Metadata::EType::FMD_TURN_LANES, "turn:lanes"},
    {feature::Metadata::EType::FMD_TURN_LANES_FORWARD, "turn:lanes:forward"},
    {feature::Metadata::EType::FMD_TURN_LANES_BACKWARD, "turn:lanes:backward"},
    {feature::Metadata::EType::FMD_EMAIL, "email"},
    {feature::Metadata::EType::FMD_EMAIL, "contact:email"},
    {feature::Metadata::EType::FMD_POSTCODE, "addr:postcode"},
    {feature::Metadata::EType::FMD_WIKIPEDIA, "wikipedia"},
    {feature::Metadata::EType::FMD_MAXSPEED, "maxspeed"},
    {feature::Metadata::EType::FMD_FLATS, "addr:flats"},
    {feature::Metadata::EType::FMD_HEIGHT, "height"},
    {feature::Metadata::EType::FMD_MIN_HEIGHT, "min_height"},
    {feature::Metadata::EType::FMD_MIN_HEIGHT, "building:min_level"},
    {feature::Metadata::EType::FMD_DENOMINATION, "denomination"},
    {feature::Metadata::EType::FMD_BUILDING_LEVELS, "building:levels"},
  };

  vector<string> result;
  auto const range = kFmd2Osm.equal_range(et);
  for (auto it = range.first; it != range.second; ++it)
    result.emplace_back(it->second);

  return result;
}

double ScoreMetadata(XMLFeature const & xmlFt, feature::Metadata const & metadata)
{
  double score = 0;

  for (auto const type : metadata.GetPresentTypes())
  {
    for (auto const osm_tag : GetOsmOriginalTagsForType(static_cast<feature::Metadata::EType>(type)))
    {
      if (xmlFt.GetTagValue(osm_tag) == metadata.Get(type))
      {
        score += 1;
        break;
      }
    }
  }

  return score;
}

bool TypesEqual(XMLFeature const & xmlFt, feature::TypesHolder const & types)
{
  return false;
}

pugi::xml_node GetBestOsmNode(pugi::xml_document const & osmResponse, FeatureType const & ft)
{
  double bestScore = -1;
  pugi::xml_node bestMatchNode;

  for (auto const & xNode : osmResponse.select_nodes("node"))
  {
    try
    {
      XMLFeature xmlFt(xNode.node());

      if (!TypesEqual(xmlFt, feature::TypesHolder(ft)))
        continue;

      double nodeScore = ScoreLatLon(xmlFt, MercatorBounds::ToLatLon(ft.GetCenter()));
      if (nodeScore < 0)
        continue;

      nodeScore += ScoreNames(xmlFt, ft.GetNames());
      nodeScore += ScoreMetadata(xmlFt, ft.GetMetadata());

      if (bestScore < nodeScore)
      {
        bestScore = nodeScore;
        bestMatchNode = xNode.node();
      }
    }
    catch (editor::XMLFeatureNoLatLonError const & ex)
    {
      LOG(LWARNING, ("No lat/lon attribute in osm response node.", ex.Msg()));
      continue;
    }
  }

  // TODO(mgsergio): Add a properly defined threshold.
  // if (bestScore < minimumScoreThreshold)
  //   return pugi::xml_node;

  return bestMatchNode;
}
}  // namespace

string DebugPrint(pugi::xml_document const & doc)
{
  ostringstream stream;
  doc.print(stream, "  ");
  return stream.str();
}

namespace osm
{

ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret,
                                   ServerApi06::TKeyValueTags const & comments)
  : m_changesetComments(comments),
    m_api(OsmOAuth::ServerAuth().SetToken(keySecret))
{
}

ChangesetWrapper::~ChangesetWrapper()
{
  if (m_changesetId)
    m_api.CloseChangeSet(m_changesetId);
}

void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc)
{
  auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon);
  if (response.first == OsmOAuth::ResponseCode::NetworkError)
    MYTHROW(NetworkErrorException, ("NetworkError with GetXmlFeaturesAtLatLon request."));
  if (response.first != OsmOAuth::ResponseCode::OK)
    MYTHROW(HttpErrorException, ("HTTP error", response.first, "with GetXmlFeaturesAtLatLon", ll));

  if (pugi::status_ok != doc.load(response.second.c_str()).status)
    MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second));
}

XMLFeature ChangesetWrapper::GetMatchingFeatureFromOSM(XMLFeature const & ourPatch, FeatureType const & feature)
{
  if (feature.GetFeatureType() == feature::EGeomType::GEOM_POINT)
  {
    // Match with OSM node.
    ms::LatLon const ll = ourPatch.GetCenter();
    pugi::xml_document doc;
    // Throws!
    LoadXmlFromOSM(ll, doc);

    // feature must be the original one, not patched!
    pugi::xml_node const bestNode = GetBestOsmNode(doc, feature);
    if (bestNode.empty())
      MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc));

    return XMLFeature(bestNode);
  }
  else if (feature.GetFeatureType() == feature::EGeomType::GEOM_AREA)
  {
    using m2::PointD;
    // Set filters out duplicate points for closed ways or triangles' vertices.
    set<PointD> geometry;
    feature.ForEachTriangle([&geometry](PointD const & p1, PointD const & p2, PointD const & p3)
    {
      geometry.insert(p1);
      geometry.insert(p2);
      geometry.insert(p3);
    }, FeatureType::BEST_GEOMETRY);

    ASSERT_GREATER_OR_EQUAL(geometry.size(), 3, ("Is it an area feature?"));

    for (auto const & pt : geometry)
    {
      ms::LatLon const ll = MercatorBounds::ToLatLon(pt);
      pugi::xml_document doc;
      // Throws!
      LoadXmlFromOSM(ll, doc);

      // TODO(AlexZ): Select best matching OSM way from possible many ways.
      pugi::xml_node const firstWay = doc.child("osm").child("way");
      if (firstWay.empty())
        continue;

      XMLFeature const way(firstWay);
      if (!way.IsArea())
        continue;

      // TODO: Check that this way is really match our feature.

      return way;
    }
    MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature", feature));
  }
  MYTHROW(LinearFeaturesAreNotSupportedException, ("We don't edit linear features yet."));
}

void ChangesetWrapper::ModifyNode(XMLFeature node)
{
  // TODO(AlexZ): ServerApi can be much better with exceptions.
  if (m_changesetId == kInvalidChangesetId && !m_api.CreateChangeSet(m_changesetComments, m_changesetId))
    MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException"));

  uint64_t nodeId;
  if (!strings::to_uint64(node.GetAttribute("id"), nodeId))
    MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException"));

  // Changeset id should be updated for every OSM server commit.
  node.SetAttribute("changeset", strings::to_string(m_changesetId));

  if (!m_api.ModifyNode(node.ToOSMString(), nodeId))
    MYTHROW(ModifyNodeFailedException, ("ModifyNodeFailedException"));
}

} // namespace osm
<commit_msg>Fix after rebase.<commit_after>#include "base/logging.hpp"

#include "indexer/feature.hpp"

#include "editor/changeset_wrapper.hpp"

#include "std/algorithm.hpp"
#include "std/sstream.hpp"
#include "std/map.hpp"

#include "geometry/mercator.hpp"

#include "private.h"

using editor::XMLFeature;

namespace
{
double ScoreLatLon(XMLFeature const & xmlFt, ms::LatLon const & latLon)
{
  double constexpr eps = MercatorBounds::GetCellID2PointAbsEpsilon();
  return latLon.EqualDxDy(xmlFt.GetCenter(), eps);
}

double ScoreNames(XMLFeature const & xmlFt, StringUtf8Multilang const & names)
{
  double score = 0;
  names.ForEach([&score, &xmlFt](uint8_t const langCode, string const & name)
                {
                  if (xmlFt.GetName(langCode) == name)
                    score += 1;
                  return true;
                });

  // TODO(mgsergio): Deafult name match should have greater wieght. Should it?

  return score;
}

vector<string> GetOsmOriginalTagsForType(feature::Metadata::EType const et)
{
  static multimap<feature::Metadata::EType, string> const kFmd2Osm = {
    {feature::Metadata::EType::FMD_CUISINE, "cuisine"},
    {feature::Metadata::EType::FMD_OPEN_HOURS, "opening_hours"},
    {feature::Metadata::EType::FMD_PHONE_NUMBER, "phone"},
    {feature::Metadata::EType::FMD_PHONE_NUMBER, "contact:phone"},
    {feature::Metadata::EType::FMD_FAX_NUMBER, "fax"},
    {feature::Metadata::EType::FMD_FAX_NUMBER, "contact:fax"},
    {feature::Metadata::EType::FMD_STARS, "stars"},
    {feature::Metadata::EType::FMD_OPERATOR, "operator"},
    {feature::Metadata::EType::FMD_URL, "url"},
    {feature::Metadata::EType::FMD_WEBSITE, "website"},
    {feature::Metadata::EType::FMD_WEBSITE, "contact:website"},
    // TODO: {feature::Metadata::EType::FMD_INTERNET, ""},
    {feature::Metadata::EType::FMD_ELE, "ele"},
    {feature::Metadata::EType::FMD_TURN_LANES, "turn:lanes"},
    {feature::Metadata::EType::FMD_TURN_LANES_FORWARD, "turn:lanes:forward"},
    {feature::Metadata::EType::FMD_TURN_LANES_BACKWARD, "turn:lanes:backward"},
    {feature::Metadata::EType::FMD_EMAIL, "email"},
    {feature::Metadata::EType::FMD_EMAIL, "contact:email"},
    {feature::Metadata::EType::FMD_POSTCODE, "addr:postcode"},
    {feature::Metadata::EType::FMD_WIKIPEDIA, "wikipedia"},
    {feature::Metadata::EType::FMD_MAXSPEED, "maxspeed"},
    {feature::Metadata::EType::FMD_FLATS, "addr:flats"},
    {feature::Metadata::EType::FMD_HEIGHT, "height"},
    {feature::Metadata::EType::FMD_MIN_HEIGHT, "min_height"},
    {feature::Metadata::EType::FMD_MIN_HEIGHT, "building:min_level"},
    {feature::Metadata::EType::FMD_DENOMINATION, "denomination"},
    {feature::Metadata::EType::FMD_BUILDING_LEVELS, "building:levels"},
  };

  vector<string> result;
  auto const range = kFmd2Osm.equal_range(et);
  for (auto it = range.first; it != range.second; ++it)
    result.emplace_back(it->second);

  return result;
}

double ScoreMetadata(XMLFeature const & xmlFt, feature::Metadata const & metadata)
{
  double score = 0;

  for (auto const type : metadata.GetPresentTypes())
  {
    for (auto const osm_tag : GetOsmOriginalTagsForType(static_cast<feature::Metadata::EType>(type)))
    {
      if (xmlFt.GetTagValue(osm_tag) == metadata.Get(type))
      {
        score += 1;
        break;
      }
    }
  }

  return score;
}

bool TypesEqual(XMLFeature const & xmlFt, feature::TypesHolder const & types)
{
  return false;
}

pugi::xml_node GetBestOsmNode(pugi::xml_document const & osmResponse, FeatureType const & ft)
{
  double bestScore = -1;
  pugi::xml_node bestMatchNode;

  for (auto const & xNode : osmResponse.select_nodes("node"))
  {
    try
    {
      XMLFeature xmlFt(xNode.node());

      if (!TypesEqual(xmlFt, feature::TypesHolder(ft)))
        continue;

      double nodeScore = ScoreLatLon(xmlFt, MercatorBounds::ToLatLon(ft.GetCenter()));
      if (nodeScore < 0)
        continue;

      nodeScore += ScoreNames(xmlFt, ft.GetNames());
      nodeScore += ScoreMetadata(xmlFt, ft.GetMetadata());

      if (bestScore < nodeScore)
      {
        bestScore = nodeScore;
        bestMatchNode = xNode.node();
      }
    }
    catch (editor::XMLFeatureNoLatLonError const & ex)
    {
      LOG(LWARNING, ("No lat/lon attribute in osm response node.", ex.Msg()));
      continue;
    }
  }

  // TODO(mgsergio): Add a properly defined threshold.
  // if (bestScore < minimumScoreThreshold)
  //   return pugi::xml_node;

  return bestMatchNode;
}
}  // namespace

string DebugPrint(pugi::xml_document const & doc)
{
  ostringstream stream;
  doc.print(stream, "  ");
  return stream.str();
}

namespace osm
{

ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret,
                                   ServerApi06::TKeyValueTags const & comments)
  : m_changesetComments(comments),
    m_api(OsmOAuth::ServerAuth().SetToken(keySecret))
{
}

ChangesetWrapper::~ChangesetWrapper()
{
  if (m_changesetId)
    m_api.CloseChangeSet(m_changesetId);
}

void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc)
{
  auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon);
  if (response.first == OsmOAuth::ResponseCode::NetworkError)
    MYTHROW(NetworkErrorException, ("NetworkError with GetXmlFeaturesAtLatLon request."));
  if (response.first != OsmOAuth::ResponseCode::OK)
    MYTHROW(HttpErrorException, ("HTTP error", response.first, "with GetXmlFeaturesAtLatLon", ll));

  if (pugi::status_ok != doc.load(response.second.c_str()).status)
    MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second));
}

XMLFeature ChangesetWrapper::GetMatchingFeatureFromOSM(XMLFeature const & ourPatch, FeatureType const & feature)
{
  if (feature.GetFeatureType() == feature::EGeomType::GEOM_POINT)
  {
    // Match with OSM node.
    ms::LatLon const ll = ourPatch.GetCenter();
    pugi::xml_document doc;
    // Throws!
    LoadXmlFromOSM(ll, doc);

    // feature must be the original one, not patched!
    pugi::xml_node const bestNode = GetBestOsmNode(doc, feature);
    if (bestNode.empty())
      MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc));

    return XMLFeature(bestNode);
  }
  else if (feature.GetFeatureType() == feature::EGeomType::GEOM_AREA)
  {
    using m2::PointD;
    // Set filters out duplicate points for closed ways or triangles' vertices.
    set<PointD> geometry;
    feature.ForEachTriangle([&geometry](PointD const & p1, PointD const & p2, PointD const & p3)
    {
      geometry.insert(p1);
      geometry.insert(p2);
      geometry.insert(p3);
    }, FeatureType::BEST_GEOMETRY);

    ASSERT_GREATER_OR_EQUAL(geometry.size(), 3, ("Is it an area feature?"));

    for (auto const & pt : geometry)
    {
      ms::LatLon const ll = MercatorBounds::ToLatLon(pt);
      pugi::xml_document doc;
      // Throws!
      LoadXmlFromOSM(ll, doc);

      // TODO(AlexZ): Select best matching OSM way from possible many ways.
      pugi::xml_node const firstWay = doc.child("osm").child("way");
      if (firstWay.empty())
        continue;

      XMLFeature const way(firstWay);
      if (!way.IsArea())
        continue;

      // TODO: Check that this way is really match our feature.

      return way;
    }
    MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature", feature));
  }
  MYTHROW(LinearFeaturesAreNotSupportedException, ("We don't edit linear features yet."));
}

void ChangesetWrapper::ModifyNode(XMLFeature node)
{
  // TODO(AlexZ): ServerApi can be much better with exceptions.
  if (m_changesetId == kInvalidChangesetId && !m_api.CreateChangeSet(m_changesetComments, m_changesetId))
    MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException"));

  uint64_t nodeId;
  if (!strings::to_uint64(node.GetAttribute("id"), nodeId))
    MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException"));

  // Changeset id should be updated for every OSM server commit.
  node.SetAttribute("changeset", strings::to_string(m_changesetId));

  if (!m_api.ModifyNode(node.ToOSMString(), nodeId))
    MYTHROW(ModifyNodeFailedException, ("ModifyNodeFailedException"));
}

} // namespace osm
<|endoftext|>


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

#include "modules/dreamview/backend/util/trajectory_point_collector.h"

#include <cmath>

#include "gtest/gtest.h"
#include "modules/common/configs/vehicle_config_helper.h"

using apollo::common::TrajectoryPoint;

namespace apollo {
namespace dreamview {
namespace util {

class TrajectoryPointCollectorTest : public ::testing::Test {
 public:
  virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); }
};

TEST_F(TrajectoryPointCollectorTest, ThreePoints) {
  SimulationWorld world;
  TrajectoryPointCollector collector(&world);

  const double base_time = 1000.0;
  for (int i = 0; i < 4; ++i) {
    TrajectoryPoint point;
    point.mutable_path_point()->set_x(i * 100.0);
    point.mutable_path_point()->set_y(i * 100.0 + 100.0);
    point.set_relative_time(i * 1000.0);
    collector.Collect(point, base_time);
  }

  EXPECT_EQ(world.planning_trajectory_size(), 3);

  {
    const Object &point = world.planning_trajectory(0);
    EXPECT_DOUBLE_EQ(0.0, point.position_x());
    EXPECT_DOUBLE_EQ(100.0, point.position_y());
    EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }

  {
    const Object &point = world.planning_trajectory(1);
    EXPECT_DOUBLE_EQ(100.0, point.position_x());
    EXPECT_DOUBLE_EQ(200.0, point.position_y());
    EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }

  {
    const Object &point = world.planning_trajectory(2);
    EXPECT_DOUBLE_EQ(200.0, point.position_x());
    EXPECT_DOUBLE_EQ(300.0, point.position_y());
    EXPECT_DOUBLE_EQ(4000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }
}

}  // namespace util
}  // namespace dreamview
}  // namespace apollo
<commit_msg>Dreamview: fixed a unit test<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/dreamview/backend/util/trajectory_point_collector.h"

#include <cmath>

#include "gtest/gtest.h"
#include "modules/common/configs/vehicle_config_helper.h"

using apollo::common::TrajectoryPoint;

namespace apollo {
namespace dreamview {
namespace util {

class TrajectoryPointCollectorTest : public ::testing::Test {
 public:
  virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); }
};

TEST_F(TrajectoryPointCollectorTest, ThreePoints) {
  SimulationWorld world;
  TrajectoryPointCollector collector(&world);

  const double base_time = 1000.0;
  for (int i = 0; i < 4; ++i) {
    TrajectoryPoint point;
    point.mutable_path_point()->set_x(i * 100.0);
    point.mutable_path_point()->set_y(i * 100.0 + 100.0);
    point.set_relative_time(i * 1000.0);
    collector.Collect(point, base_time);
  }

  EXPECT_EQ(world.planning_trajectory_size(), 3);

  {
    const Object &point = world.planning_trajectory(0);
    EXPECT_DOUBLE_EQ(0.0, point.position_x());
    EXPECT_DOUBLE_EQ(100.0, point.position_y());
    EXPECT_DOUBLE_EQ(1000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }

  {
    const Object &point = world.planning_trajectory(1);
    EXPECT_DOUBLE_EQ(100.0, point.position_x());
    EXPECT_DOUBLE_EQ(200.0, point.position_y());
    EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }

  {
    const Object &point = world.planning_trajectory(2);
    EXPECT_DOUBLE_EQ(200.0, point.position_x());
    EXPECT_DOUBLE_EQ(300.0, point.position_y());
    EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec());
    EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
  }
}

}  // namespace util
}  // namespace dreamview
}  // namespace apollo
<|endoftext|>