<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleOLEShape.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: af $ $Date: 2002-04-22 14:32:17 $
 *
 *  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 _SVX_ACCESSIBILITY_ACCESSIBLE_OLE_SHAPE_HXX
#include "AccessibleOLEShape.hxx"
#endif

#include "ShapeTypeHandler.hxx"
#include "SvxShapeTypes.hxx"

using namespace accessibility;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::accessibility;

//=====  internal  ============================================================

AccessibleOLEShape::AccessibleOLEShape (const ::com::sun::star::uno::Reference<
        ::com::sun::star::drawing::XShape>& rxShape,
    const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
    const AccessibleShapeTreeInfo& rShapeTreeInfo,
    long nIndex)
    :      AccessibleShape (rxShape, rxParent, rShapeTreeInfo, nIndex)
{
}

AccessibleOLEShape::~AccessibleOLEShape (void)
{
}

//=====  XAccessibleAction  ===================================================

sal_Int32 SAL_CALL AccessibleOLEShape::getAccessibleActionCount (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return 0;
}

sal_Bool SAL_CALL AccessibleOLEShape::doAccessibleAction (sal_Int32 nIndex)
    throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

::rtl::OUString SAL_CALL AccessibleOLEShape::getAccessibleActionDescription (sal_Int32 nIndex)
    throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

::com::sun::star::uno::Any SAL_CALL AccessibleOLEShape::getAccessibleKeyBinding (sal_Int32 nIndex)
    throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

//=====  XInterface  ==========================================================

com::sun::star::uno::Any SAL_CALL
    AccessibleOLEShape::queryInterface (const com::sun::star::uno::Type & rType)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Any aReturn = AccessibleShape::queryInterface (rType);
    if ( ! aReturn.hasValue())
        aReturn = ::cppu::queryInterface (rType,
            static_cast<XAccessibleAction*>(this));
    return aReturn;
}

void SAL_CALL
    AccessibleOLEShape::acquire (void)
    throw ()
{
    AccessibleShape::acquire ();
}

void SAL_CALL
    AccessibleOLEShape::release (void)
    throw ()
{
    AccessibleShape::release ();
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleOLEShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleOLEShape"));
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleOLEShape::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (AccessibleShape::getTypes());
    // ...and add the additional type for the component.
    long nTypeCount = aTypeList.getLength();
    aTypeList.realloc (nTypeCount + 1);
    const uno::Type aActionType =
        ::getCppuType((const uno::Reference<XAccessibleAction>*)0);
    aTypeList[nTypeCount] = aActionType;

    return aTypeList;
}

/// Set this object's name if is different to the current name.
::rtl::OUString
    AccessibleOLEShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::rtl::OUString sName;

    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case DRAWING_APPLET:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("AppletOLEShape"));
            break;
        case DRAWING_FRAME:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("FrameOLEShape"));
            break;
        case DRAWING_OLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("OLEShape"));
            break;
        case DRAWING_PLUGIN:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("PluginOLEShape"));
            break;

        default:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleOLEShape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
                sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
                    + xDescriptor->getShapeType();
    }

    return sName;
}

::rtl::OUString
    AccessibleOLEShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return CreateAccessibleName ();
}

<commit_msg>#95585# Using new class AccessibleShapeTreeInfo in constructor.<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleOLEShape.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: af $ $Date: 2002-05-06 09:05:29 $
 *
 *  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 _SVX_ACCESSIBILITY_ACCESSIBLE_OLE_SHAPE_HXX
#include "AccessibleOLEShape.hxx"
#endif

#include "ShapeTypeHandler.hxx"
#include "SvxShapeTypes.hxx"

using namespace accessibility;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::accessibility;

//=====  internal  ============================================================

AccessibleOLEShape::AccessibleOLEShape (
    const AccessibleShapeInfo& rShapeInfo,
    const AccessibleShapeTreeInfo& rShapeTreeInfo)
    : AccessibleShape (rShapeInfo, rShapeTreeInfo)
{
}

AccessibleOLEShape::~AccessibleOLEShape (void)
{
}

//=====  XAccessibleAction  ===================================================

sal_Int32 SAL_CALL AccessibleOLEShape::getAccessibleActionCount (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return 0;
}

sal_Bool SAL_CALL AccessibleOLEShape::doAccessibleAction (sal_Int32 nIndex)
    throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

::rtl::OUString SAL_CALL AccessibleOLEShape::getAccessibleActionDescription (sal_Int32 nIndex)
    throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

::com::sun::star::uno::Any SAL_CALL AccessibleOLEShape::getAccessibleKeyBinding (sal_Int32 nIndex)
    throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException();
}

//=====  XInterface  ==========================================================

com::sun::star::uno::Any SAL_CALL
    AccessibleOLEShape::queryInterface (const com::sun::star::uno::Type & rType)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Any aReturn = AccessibleShape::queryInterface (rType);
    if ( ! aReturn.hasValue())
        aReturn = ::cppu::queryInterface (rType,
            static_cast<XAccessibleAction*>(this));
    return aReturn;
}

void SAL_CALL
    AccessibleOLEShape::acquire (void)
    throw ()
{
    AccessibleShape::acquire ();
}

void SAL_CALL
    AccessibleOLEShape::release (void)
    throw ()
{
    AccessibleShape::release ();
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleOLEShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleOLEShape"));
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleOLEShape::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (AccessibleShape::getTypes());
    // ...and add the additional type for the component.
    long nTypeCount = aTypeList.getLength();
    aTypeList.realloc (nTypeCount + 1);
    const uno::Type aActionType =
        ::getCppuType((const uno::Reference<XAccessibleAction>*)0);
    aTypeList[nTypeCount] = aActionType;

    return aTypeList;
}

/// Set this object's name if is different to the current name.
::rtl::OUString
    AccessibleOLEShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::rtl::OUString sName;

    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case DRAWING_APPLET:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("AppletOLEShape"));
            break;
        case DRAWING_FRAME:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("FrameOLEShape"));
            break;
        case DRAWING_OLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("OLEShape"));
            break;
        case DRAWING_PLUGIN:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("PluginOLEShape"));
            break;

        default:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleOLEShape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
                sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
                    + xDescriptor->getShapeType();
    }

    return sName;
}

::rtl::OUString
    AccessibleOLEShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return CreateAccessibleName ();
}

<|endoftext|>


<commit_before>AliAnalysisTaskSEHFQA* AddTaskBasicHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,
					Bool_t readMC,
					TString suffix=""){

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBasicHFQA", "No analysis manager to connect to.");
    return NULL;
  }

  AliRDHFCuts *analysiscuts=0x0;
  switch (ch){
  case 0:
    analysiscuts = new AliRDHFCutsDplustoKpipi();
    suffix="Dplus";
    break;
  case 1:
    analysiscuts = new AliRDHFCutsD0toKpi();
    suffix="D0";
    break;
  case 2:
    analysiscuts = new AliRDHFCutsDstoKKpi();
    suffix="Ds";
    break;
  case 4:
    analysiscuts = new AliRDHFCutsD0toKpipipi();
    suffix="D04";
    break;
  case 5:
    analysiscuts = new AliRDHFCutsLctopKpi();
    suffix="Lc";
    break;
  case 6:
    analysiscuts = new AliRDHFCutsLctoV0bachelor();
     suffix="LcToV0x";
    break;
  }

  analysiscuts->SetTriggerClass("");
  analysiscuts->SetTriggerMask(AliVEvent::kAnyINT);
  analysiscuts->SetUseCentrality(1);

  AliAODPidHF* pid4hf=new AliAODPidHF();
  Double_t plim[2]={0.6,0.8};
  Double_t nsigma[5]={2.,1.,2.,3.,0.};
  pid4hf->SetPLimit(plim,2);
  pid4hf->SetAsym(kTRUE);
  pid4hf->SetSigma(nsigma);
  pid4hf->SetMatch(1);
  pid4hf->SetTPC(1);
  pid4hf->SetTOF(1);
  pid4hf->SetITS(0);
  pid4hf->SetTRD(0);
  pid4hf->SetCompat(kTRUE);
  analysiscuts->SetPidHF(pid4hf);

  AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
  taskQA->SetReadMC(readMC);
  taskQA->SetSimpleMode(kTRUE);
  taskQA->SetTrackOn(kTRUE);
  taskQA->SetPIDOn(kTRUE);
  taskQA->SetCentralityOn(kFALSE);
  taskQA->SetEvSelectionOn(kTRUE);
  taskQA->SetFlowObsOn(kFALSE);
  taskQA->SetFillDistributionsForTrackEffChecks(kFALSE);
  mgr->AddTask(taskQA);

  TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",out8name="outputFlowObs",inname="input",suffix="",cutsobjname="",centr="";
  filename = AliAnalysisManager::GetCommonFileName();
  filename += ":PWG3_D2H_QA";
  inname+=suffix;
  out1name+=suffix;
  out2name+=suffix;
  out3name+=suffix;
  out4name+=suffix;
  out5name+=suffix;
  out6name+=suffix;
  out7name+=suffix;
  out8name+=suffix;

  //
  // Create containers for input/output
  AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
  mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
  mgr->ConnectOutput(taskQA,1,coutput1);

  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
  mgr->ConnectOutput(taskQA,2,coutput2);

  AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
  mgr->ConnectOutput(taskQA,3,coutput3);

  AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
  mgr->ConnectOutput(taskQA,4,coutput4);

  AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
  mgr->ConnectOutput(taskQA,7,coutput7);

 return taskQA;
}
<commit_msg>Disable centrality selection in basic configuration of HF QA<commit_after>AliAnalysisTaskSEHFQA* AddTaskBasicHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,
					Bool_t readMC,
					TString suffix=""){

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBasicHFQA", "No analysis manager to connect to.");
    return NULL;
  }

  AliRDHFCuts *analysiscuts=0x0;
  switch (ch){
  case 0:
    analysiscuts = new AliRDHFCutsDplustoKpipi();
    suffix="Dplus";
    break;
  case 1:
    analysiscuts = new AliRDHFCutsD0toKpi();
    suffix="D0";
    break;
  case 2:
    analysiscuts = new AliRDHFCutsDstoKKpi();
    suffix="Ds";
    break;
  case 4:
    analysiscuts = new AliRDHFCutsD0toKpipipi();
    suffix="D04";
    break;
  case 5:
    analysiscuts = new AliRDHFCutsLctopKpi();
    suffix="Lc";
    break;
  case 6:
    analysiscuts = new AliRDHFCutsLctoV0bachelor();
     suffix="LcToV0x";
    break;
  }

  analysiscuts->SetTriggerClass("");
  analysiscuts->SetTriggerMask(AliVEvent::kAnyINT);
  analysiscuts->SetUseCentrality(AliRDHFCuts::kCentOff);

  AliAODPidHF* pid4hf=new AliAODPidHF();
  Double_t plim[2]={0.6,0.8};
  Double_t nsigma[5]={2.,1.,2.,3.,0.};
  pid4hf->SetPLimit(plim,2);
  pid4hf->SetAsym(kTRUE);
  pid4hf->SetSigma(nsigma);
  pid4hf->SetMatch(1);
  pid4hf->SetTPC(1);
  pid4hf->SetTOF(1);
  pid4hf->SetITS(0);
  pid4hf->SetTRD(0);
  pid4hf->SetCompat(kTRUE);
  analysiscuts->SetPidHF(pid4hf);

  AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
  taskQA->SetReadMC(readMC);
  taskQA->SetSimpleMode(kTRUE);
  taskQA->SetTrackOn(kTRUE);
  taskQA->SetPIDOn(kTRUE);
  taskQA->SetCentralityOn(kFALSE);
  taskQA->SetEvSelectionOn(kTRUE);
  taskQA->SetFlowObsOn(kFALSE);
  taskQA->SetFillDistributionsForTrackEffChecks(kFALSE);
  mgr->AddTask(taskQA);

  TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",out8name="outputFlowObs",inname="input",suffix="",cutsobjname="",centr="";
  filename = AliAnalysisManager::GetCommonFileName();
  filename += ":PWG3_D2H_QA";
  inname+=suffix;
  out1name+=suffix;
  out2name+=suffix;
  out3name+=suffix;
  out4name+=suffix;
  out5name+=suffix;
  out6name+=suffix;
  out7name+=suffix;
  out8name+=suffix;

  //
  // Create containers for input/output
  AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
  mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
  mgr->ConnectOutput(taskQA,1,coutput1);

  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
  mgr->ConnectOutput(taskQA,2,coutput2);

  AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
  mgr->ConnectOutput(taskQA,3,coutput3);

  AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
  mgr->ConnectOutput(taskQA,4,coutput4);

  AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
  mgr->ConnectOutput(taskQA,7,coutput7);

 return taskQA;
}
<|endoftext|>


<commit_before>/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h>			// For multithreading
#include <stdint.h>
#include <sstream>

#include "serverCommands.cpp"

struct thread_info { 	   		/* Used as argument to thread_start() */
	pthread_t 	thread_id;     /* ID returned by pthread_create() */
	int 			sock;			/* Socket. I think */
	userDB		*users; 		/* Pointer to global users object */
	//session_type	*sessions;		// pointer to global sessions object
	// CryptoPP::SecByteBlock session_key;
	// string 			username;
};

//HashMap of usernames to a tuple of user info or user object containing {username, pin, balance}

void error(const char *msg);

void* consoleThread(void *threadid);
void* socketThread(void* arg);

int main(int argc, char *argv[]) {
  	if (argc != 2) {                     // Test for correct number of arguments
  		std::cerr << "Usage: " << argv[0] << " <Server Port>" << std::endl;
  		exit(1);
  	}
    // socket initialization
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    if (argc < 2) {
        std::cerr << "Usage: ATMserver <Port>" << std::endl;
        exit(1);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("ERROR opening socket");
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    // assign socket to port number
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        error("ERROR on binding");
    }
    listen(sockfd,5);
    clilen = sizeof(cli_addr);

    pthread_t thread;
    thread_info args;

    userDB* users = new userDB();
    init_bank(users);
    args.users = users;

    pthread_create(&thread, NULL, consoleThread, &args);

    while (1) {
        newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
        if (newsockfd < 0) {
          error("ERROR on accept");
          continue;
        }
        pthread_t thread;
        // thread_info args;
        args.sock = newsockfd;

        // pid = fork();
        pthread_create(&thread, NULL, socketThread, &args);
        // close(newsockfd);
        // int threadNum* ++;
    } /* end of while */
    close(newsockfd);
    close(sockfd);
  	//create 2 threads, one for I/O another for incomming connections
  	return 0;
}

//
void error(const char *msg) {
    std::cerr << msg <<std::endl;
    exit(1);
}
// Read input until we read a space, then for each character add it to the command string
std::string advanceCommand(const std::string& line, int &index) {
  std::string command = "";
  for(; line[index] != ' ' && index < line.length(); index++) {
    command += line[index];
  }
  return command;
}
// Skip any number of spaces
void advanceSpaces(const std::string &line, int &index) {
  for(; line[index] == ' ' && index < line.length(); index++);
}

void *consoleThread(void *threadid) {
	// Read in commands from cin
	for(std::string line; getline(std::cin, line);) {

		int index = 0;
		std::string command = advanceCommand(line, index);
    advanceSpaces(line, index);
		std::string username = advanceCommand(line, index);

		//deposit [username] [amount]  Increase <username>’s balance by <amount>
		if(command.compare("deposit") == 0) {
      advanceSpaces(line, index);
			std::string amount = advanceCommand(line, index);

			// Execute deposit command
			deposit(&username, atol(amount.c_str()));
		}
		//balance [username]  Print the balance of <username>
		else if(command.compare("balance") == 0) {
			// Execute balance command
			balance(&username);
		}
	}
	pthread_exit(NULL);		// Ends the thread
}
std::string genSessionKey(std::string username) {
  int secret = rand() % 10 + 1;
  std::stringstream ss;
  ss << secret;
  return username + ss.str();
}
std::string parseCommands(char buffer[], userDB* users, std::string& sessionKey) {
  int index = 0;
  std::string input(buffer);
  std::string command = advanceCommand(input, index);
  std::string sendStr;
  advanceSpaces(input, index);
  if (command.compare("login") == 0) {
    std::string username = advanceCommand(input, index);
    advanceSpaces(input, index);
    std::string pin = advanceCommand(input, index);
    if (users->loginUser(username, pin)) {
      std::cout << "logged in!" << std::endl;
      sessionKey = genSessionKey(username);
      sendStr = "y " + sessionKey;
    } else {
      sendStr = "n";
    }
  } else if (command.compare("balance") == 0) {

  } else if (command.compare("withdraw") == 0) {

  } else if (command.compare("transfer") == 0) {

  } else if (command.compare("logout") == 0) {

  } else {
    std::cout << "error! bad command!" << std::endl;
  }
  return sendStr;
}

void* socketThread(void* args) {
  struct thread_info *tinfo;
  tinfo = (thread_info *) args;
  int sock = tinfo->sock;
  userDB *users = tinfo->users;
  std::string sessionKey;

  bool logginIn = false;

  while (1) {
    int n;
    char buffer[256];
    char sendBuffer[256];
    bzero(buffer,256);
    bzero(sendBuffer,256);

    n = read(sock,buffer,255);
    buffer[n-1] = '\0';
    if (n < 0) {
      break;
      error("ERROR reading from socket");
    }
    std::cout << n << std::endl;
    // printf("Here is the message: %s\n",buffer);
    std::string send = parseCommands(buffer, users, sessionKey);
    n = write(sock, send.c_str(), send.length());

    if (n < 0) error("ERROR writing to socket");
    if (buffer == "exit") {
      std::cout << "exiting!" << std::endl;
	    pthread_exit(NULL);		// Ends the thread
      break;
    }
  }
  return NULL;
}
<commit_msg>fixed endless loop<commit_after>/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h>			// For multithreading
#include <stdint.h>
#include <sstream>
#include <iomanip>

#include "serverCommands.cpp"

struct thread_info { 	   		/* Used as argument to thread_start() */
	pthread_t 	thread_id;     /* ID returned by pthread_create() */
	int 			sock;			/* Socket. I think */
	userDB		*users; 		/* Pointer to global users object */
	//session_type	*sessions;		// pointer to global sessions object
	// CryptoPP::SecByteBlock session_key;
	// string 			username;
};

//HashMap of usernames to a tuple of user info or user object containing {username, pin, balance}

void error(const char *msg);

void* consoleThread(void *threadid);
void* socketThread(void* arg);

int main(int argc, char *argv[]) {
  	if (argc != 2) {                     // Test for correct number of arguments
  		std::cerr << "Usage: " << argv[0] << " <Server Port>" << std::endl;
  		exit(1);
  	}
    // socket initialization
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    if (argc < 2) {
        std::cerr << "Usage: ATMserver <Port>" << std::endl;
        exit(1);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("ERROR opening socket");
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    // assign socket to port number
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        error("ERROR on binding");
    }
    listen(sockfd,5);
    clilen = sizeof(cli_addr);

    pthread_t thread;
    thread_info args;

    userDB* users = new userDB();
    init_bank(users);
    args.users = users;

    pthread_create(&thread, NULL, consoleThread, &args);

    while (1) {
        newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
        if (newsockfd < 0) {
          error("ERROR on accept");
          continue;
        }
        pthread_t thread;
        // thread_info args;
        args.sock = newsockfd;

        // pid = fork();
        pthread_create(&thread, NULL, socketThread, &args);
        // close(newsockfd);
        // int threadNum* ++;
    } /* end of while */
    close(newsockfd);
    close(sockfd);
  	//create 2 threads, one for I/O another for incomming connections
  	return 0;
}

//
void error(const char *msg) {
    std::cerr << msg <<std::endl;
    exit(1);
}
// Read input until we read a space, then for each character add it to the command string
std::string advanceCommand(const std::string& line, int &index) {
  std::string command = "";
  for(; line[index] != ' ' && index < line.length(); index++) {
    command += line[index];
  }
  return command;
}
// Skip any number of spaces
void advanceSpaces(const std::string &line, int &index) {
  for(; line[index] == ' ' && index < line.length(); index++);
}

void *consoleThread(void *threadid) {
	// Read in commands from cin
	for(std::string line; getline(std::cin, line);) {

		int index = 0;
		std::string command = advanceCommand(line, index);
    advanceSpaces(line, index);
		std::string username = advanceCommand(line, index);

		//deposit [username] [amount]  Increase <username>’s balance by <amount>
		if(command.compare("deposit") == 0) {
      advanceSpaces(line, index);
			std::string amount = advanceCommand(line, index);

			// Execute deposit command
			deposit(&username, atol(amount.c_str()));
		}
		//balance [username]  Print the balance of <username>
		else if(command.compare("balance") == 0) {
			// Execute balance command
			balance(&username);
		}
	}
	pthread_exit(NULL);		// Ends the thread
}
std::string genSessionKey(std::string username) {
  int secret = rand() % 1000 + 1;
  std::stringstream ss;
  ss << std::setfill('0') << std::setw(4) << secret;
  return username + ss.str();
}
std::string parseCommands(char buffer[], userDB* users, std::string& sessionKey) {
  int index = 0;
  std::string input(buffer);
  std::string command = advanceCommand(input, index);
  std::string sendStr;
  advanceSpaces(input, index);
  if (command.compare("login") == 0) {
    std::string username = advanceCommand(input, index);
    advanceSpaces(input, index);
    std::string pin = advanceCommand(input, index);
    if (users->loginUser(username, pin)) {
      std::cout << "logged in!" << std::endl;
      sessionKey = genSessionKey(username);
      sendStr = "y " + sessionKey;
    } else {
      sendStr = "n";
    }
  } else if (command.compare("balance") == 0) {

  } else if (command.compare("withdraw") == 0) {

  } else if (command.compare("transfer") == 0) {

  } else if (command.compare("logout") == 0) {

  } else {
    std::cout << "error! bad command!" << std::endl;
  }
  return sendStr;
}

void* socketThread(void* args) {
  struct thread_info *tinfo;
  tinfo = (thread_info *) args;
  int sock = tinfo->sock;
  userDB *users = tinfo->users;
  std::string sessionKey;

  bool logginIn = false;

  while (1) {
    int n;
    char buffer[256];
    char sendBuffer[256];
    bzero(buffer,256);
    bzero(sendBuffer,256);

    n = read(sock,buffer,255);
    // buffer[n-1] = '\0';
    // printf("Here is the message: %s\n",buffer);

    if (n < 0) error("ERROR writing to socket");
    if (buffer == "exit" || n == 0) {
      std::cout << "exiting!" << std::endl;
	    pthread_exit(NULL);		// Ends the thread
      break;
    }

    std::string send = parseCommands(buffer, users, sessionKey);
    n = write(sock, send.c_str(), send.length());
  }
  return NULL;
}
<|endoftext|>


<commit_before>#include <array>
#include <cmath>
#include <iostream>
#include <string>
#include <utility>

#include <TCanvas.h>
#include <TEfficiency.h>
#include <TFile.h>
#include <TList.h>
#include <TH1D.h>
#include <TH3D.h>

#include <AliPID.h>

#include "AliAnalysisTaskLFefficiencies.h"

const char* TOF_cut_names[7] = {"","","","FB5 + TOF matching", "FB5 + TOF pid", "FB5 + TOF matching - TOF mismatch","FB5 + TOF matching - TOF mismatch + TOF pid"};

void DivideBinomial(TH1* num, const TH1* den) {
  for (int iBin = 1; iBin <= num->GetNbinsX(); ++iBin) {
    const double n = num->GetBinContent(iBin);
    const double d = den->GetBinContent(iBin);
    const double eff = (d > 1.e-24) ? n / d : 0.;
    const double err_eff = (d > 1.e-24 && eff < 1) ? std::sqrt(eff * (1. - eff) / d) : 0.;
    num->SetBinContent(iBin, eff);
    num->SetBinError(iBin, err_eff);
  }
}

bool endsWith(const std::string &mainStr, const std::string &&toMatch)
{
	if(mainStr.size() >= toMatch.size() &&
			mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
			return true;
		else
			return false;
}

std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>>
ComputeLFefficiencies(std::string filename = "AnalysisResults") {
  if (endsWith(filename,".root")) {
    for (int i = 0; i < 5; ++i) filename.pop_back();
  }

  TFile input_file((filename + ".root").data());
  TList* input_list = static_cast<TList*>(input_file.Get("PWGLF_QA/efficiencies"));
  if (!input_list) {
    ::Fatal("ComputeLFefficiencies","Missing input list, check the input file.");
  }

  std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> vec;
  TCanvas cv("canvas");
  TCanvas cv_eta("canvas_eta");
  TCanvas cv_rec("reconstructed");
  TCanvas cv_gen("generated");
  cv.Print((filename + "_y.pdf[").data(),"pdf");
  cv_eta.Print((filename + "_eta.pdf[").data(),"pdf");

  TCanvas cv_tof("canvas_tof");
  cv_tof.Print((filename + "_tof_y.pdf[").data(),"pdf");
  TCanvas cv_tof_eta("canvas_tof_eta");
  cv_tof_eta.Print((filename + "_tof_eta.pdf[").data(),"pdf");

  TFile output_file((filename + "_out.root").data(),"recreate");

  for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
    for (int iCharge = 0; iCharge < 2; ++iCharge) {
      cv.cd();
      cv.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      TH3D* gen3D = static_cast<TH3D*>(input_list->FindObject(Form("Gen_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
      TH1D* gen = gen3D->ProjectionZ(Form("Gen_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),3,7);

      cv_eta.cd();
      cv_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      TH3D* gen3Deta = static_cast<TH3D*>(input_list->FindObject(Form("GenEta_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
      TH1D* genEta = gen3Deta->ProjectionZ(Form("GenEta_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),2,9);

      TH1D *rec[AliAnalysisTaskLFefficiencies::fNcuts];
      TH1D *recEta[AliAnalysisTaskLFefficiencies::fNcuts];

      for (int iCut = 0; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
        cv.cd();
        TH3D* rec3D = static_cast<TH3D*>(input_list->FindObject(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
        rec[iCut] = rec3D->ProjectionZ(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),3,7);
        TH1D* eff = (TH1D*)rec[iCut]->Clone(Form("Eff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        if(iCut==5){
          eff->SetTitle("FB5 + TOF matching - mismatch");
        }
        DivideBinomial(eff,gen);
        eff->Draw("same PLC PMC");
        vec.first[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
        vec.first[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);

        cv_eta.cd();
        TH3D* rec3Deta = static_cast<TH3D*>(input_list->FindObject(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
        recEta[iCut] = rec3Deta->ProjectionZ(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),2,9);
        TH1D* effEta = (TH1D*)recEta[iCut]->Clone(Form("EffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        DivideBinomial(effEta,genEta);
        effEta->Draw("same PLC PMC");

        output_file.cd();
        eff->Write();
        effEta->Write();
        vec.second[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
        vec.second[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);
      }

      cv.cd();
      cv.BuildLegend();
      cv.Print((filename + "_y.pdf").data(),"pdf");

      cv_eta.cd();
      cv_eta.BuildLegend();
      cv_eta.Print((filename + "_eta.pdf").data(),"pdf");

      // TOF matching efficiency

      cv_tof.cd();
      cv_tof.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); TOF Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      cv_tof_eta.cd();
      cv_tof_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); TOF Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      for(int iCut = 3; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
        cv_tof.cd();
        TH1D* hTOFmatchEff = (TH1D*)rec[iCut]->Clone(Form("TOFmatchEff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        hTOFmatchEff->SetTitle(Form("(%s) / FB5",TOF_cut_names[iCut]));
        DivideBinomial(hTOFmatchEff,rec[0]);
        hTOFmatchEff->Draw("same PLC PMC");

        cv_tof_eta.cd();
        TH1D* hTOFmatchEffEta = (TH1D*)recEta[iCut]->Clone(Form("TOFmatchEffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        if(iCut==5){
          hTOFmatchEffEta->Add(recEta[3],-1);
          hTOFmatchEffEta->Scale(-1);
        }
        hTOFmatchEffEta->SetTitle(Form("(%s) / FB5",TOF_cut_names[iCut]));
        DivideBinomial(hTOFmatchEffEta,recEta[0]);
        hTOFmatchEffEta->Draw("same PLC PMC");

      }

      cv_tof.cd();
      cv_tof.BuildLegend();
      cv_tof.Print((filename + "_tof_y.pdf").data(),"pdf");

      cv_tof_eta.cd();
      cv_tof_eta.BuildLegend();
      cv_tof_eta.Print((filename + "_tof_eta.pdf").data(),"pdf");
    }
  }
  cv.Print((filename + "_y.pdf]").data(),"pdf");
  cv_eta.Print((filename + "_eta.pdf]").data(),"pdf");

  cv_tof.Print((filename + "_tof_y.pdf]").data(),"pdf");
  cv_tof_eta.Print((filename + "_tof_eta.pdf]").data(),"pdf");

  output_file.Close();
  return vec;
}

void ComputeLFefficiencies(std::string filename0, std::string filename1) {
  std::array<std::string, 2> filenames { filename0, filename1 };
  std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> efficiencies[2];

  for (size_t iFile = 0; iFile < filenames.size(); ++iFile) {
    std::string& fname = filenames[iFile];
    efficiencies[iFile] = ComputeLFefficiencies(fname);
  }

  TCanvas cv_y("canvas_y");
  TCanvas cv_eta("canvas_eta");
  cv_y.Print("Comparison_y.pdf[","pdf");
  cv_eta.Print("Comparison_eta.pdf[","pdf");

  for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
    for (int iCharge = 0; iCharge < 2; ++iCharge) {
      cv_y.cd();
      cv_y.DrawFrame(0.,0.,6.,2.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      cv_eta.cd();
      cv_eta.DrawFrame(0.,0.,6.,2.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      for (size_t iHist = 0; iHist < efficiencies[0].first[(iSpecies-2)*2+iCharge].size(); ++iHist) {
        cv_y.cd();
        efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].first[(iSpecies-2)*2+iCharge][iHist]);
        efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");

        cv_eta.cd();
        efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].second[(iSpecies-2)*2+iCharge][iHist]);
        efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");

      }
      cv_y.BuildLegend();
      cv_eta.BuildLegend();
      cv_y.Print("Comparison_y.pdf","pdf");
      cv_eta.Print("Comparison_eta.pdf","pdf");

    }
  }

  cv_y.Print("Comparison_y.pdf]","pdf");
  cv_eta.Print("Comparison_eta.pdf]","pdf");
}
<commit_msg>Modify macro for Nuclei QA in MC<commit_after>#include <array>
#include <cmath>
#include <iostream>
#include <string>
#include <utility>

#include <TCanvas.h>
#include <TEfficiency.h>
#include <TFile.h>
#include <TList.h>
#include <TH1D.h>
#include <TH3D.h>

#include <AliPID.h>

#include "AliAnalysisTaskLFefficiencies.h"

const char* TOF_cut_names[7] = {"","","","FB5 + TOF matching", "FB5 + TOF pid", "FB5 + TOF matching - TOF mismatch","FB5 + TOF matching - TOF mismatch + TOF pid"};
const int kNoCheckTOFmismatch = 5;

void DivideBinomial(TH1* num, const TH1* den) {
  for (int iBin = 1; iBin <= num->GetNbinsX(); ++iBin) {
    const double n = num->GetBinContent(iBin);
    const double d = den->GetBinContent(iBin);
    const double eff = (d > 1.e-24) ? n / d : 0.;
    const double err_eff = (d > 1.e-24 && eff < 1) ? std::sqrt(eff * (1. - eff) / d) : 0.;
    num->SetBinContent(iBin, eff);
    num->SetBinError(iBin, err_eff);
  }
}

bool endsWith(const std::string &mainStr, const std::string &&toMatch)
{
	if(mainStr.size() >= toMatch.size() &&
			mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
			return true;
		else
			return false;
}

std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>>
ComputeLFefficiencies(std::string filename = "AnalysisResults") {
  if (endsWith(filename,".root")) {
    for (int i = 0; i < 5; ++i) filename.pop_back();
  }

  TFile input_file((filename + ".root").data());
  TList* input_list = static_cast<TList*>(input_file.Get("PWGLF_QA/efficiencies"));
  if (!input_list) {
    ::Fatal("ComputeLFefficiencies","Missing input list, check the input file.");
  }

  std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> vec;
  TCanvas cv("canvas");
  TCanvas cv_eta("canvas_eta");
  TCanvas cv_rec("reconstructed");
  TCanvas cv_gen("generated");
  cv.Print((filename + "_y.pdf[").data(),"pdf");
  cv_eta.Print((filename + "_eta.pdf[").data(),"pdf");

  TCanvas cv_tof("canvas_tof");
  cv_tof.Print((filename + "_tof_y.pdf[").data(),"pdf");
  TCanvas cv_tof_eta("canvas_tof_eta");
  cv_tof_eta.Print((filename + "_tof_eta.pdf[").data(),"pdf");

  TFile output_file((filename + "_out.root").data(),"recreate");

  for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
    for (int iCharge = 0; iCharge < 2; ++iCharge) {
      cv.cd();
      cv.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      TH3D* gen3D = static_cast<TH3D*>(input_list->FindObject(Form("Gen_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
      TH1D* gen = gen3D->ProjectionZ(Form("Gen_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),3,7);

      cv_eta.cd();
      cv_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      TH3D* gen3Deta = static_cast<TH3D*>(input_list->FindObject(Form("GenEta_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
      TH1D* genEta = gen3Deta->ProjectionZ(Form("GenEta_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),2,9);

      TH1D *rec[AliAnalysisTaskLFefficiencies::fNcuts];
      TH1D *recEta[AliAnalysisTaskLFefficiencies::fNcuts];

      for (int iCut = 0; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
        cv.cd();
        TH3D* rec3D = static_cast<TH3D*>(input_list->FindObject(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
        rec[iCut] = rec3D->ProjectionZ(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),3,7);
        TH1D* eff = (TH1D*)rec[iCut]->Clone(Form("Eff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        if(iCut==5){
          eff->SetTitle("FB5 + TOF matching - mismatch");
        }
        DivideBinomial(eff,gen);
        if(iCut < kNoCheckTOFmismatch) eff->Draw("same PLC PMC");
        vec.first[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
        vec.first[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);

        cv_eta.cd();
        TH3D* rec3Deta = static_cast<TH3D*>(input_list->FindObject(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
        recEta[iCut] = rec3Deta->ProjectionZ(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),2,9);
        TH1D* effEta = (TH1D*)recEta[iCut]->Clone(Form("EffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        DivideBinomial(effEta,genEta);
        if(iCut < kNoCheckTOFmismatch) effEta->Draw("same PLC PMC");

        output_file.cd();
        eff->Write();
        effEta->Write();
        vec.second[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
        vec.second[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);
      }

      cv.cd();
      cv.BuildLegend();
      cv.Print((filename + "_y.pdf").data(),"pdf");

      cv_eta.cd();
      cv_eta.BuildLegend();
      cv_eta.Print((filename + "_eta.pdf").data(),"pdf");

      // TOF matching efficiency

      cv_tof.cd();
      cv_tof.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); TOF Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      cv_tof_eta.cd();
      cv_tof_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); TOF Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      for(int iCut = 3; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
        cv_tof.cd();
        TH1D* hTOFmatchEff = (TH1D*)rec[iCut]->Clone(Form("TOFmatchEff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        hTOFmatchEff->SetTitle(Form("(%s) / FB5",TOF_cut_names[iCut]));
        DivideBinomial(hTOFmatchEff,rec[0]);
        hTOFmatchEff->Draw("same PLC PMC");

        cv_tof_eta.cd();
        TH1D* hTOFmatchEffEta = (TH1D*)recEta[iCut]->Clone(Form("TOFmatchEffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut));
        if(iCut==5){
          hTOFmatchEffEta->Add(recEta[3],-1);
          hTOFmatchEffEta->Scale(-1);
        }
        hTOFmatchEffEta->SetTitle(Form("(%s) / FB5",TOF_cut_names[iCut]));
        DivideBinomial(hTOFmatchEffEta,recEta[0]);
        hTOFmatchEffEta->Draw("same PLC PMC");

      }

      cv_tof.cd();
      cv_tof.BuildLegend();
      cv_tof.Print((filename + "_tof_y.pdf").data(),"pdf");

      cv_tof_eta.cd();
      cv_tof_eta.BuildLegend();
      cv_tof_eta.Print((filename + "_tof_eta.pdf").data(),"pdf");
    }
  }
  cv.Print((filename + "_y.pdf]").data(),"pdf");
  cv_eta.Print((filename + "_eta.pdf]").data(),"pdf");

  cv_tof.Print((filename + "_tof_y.pdf]").data(),"pdf");
  cv_tof_eta.Print((filename + "_tof_eta.pdf]").data(),"pdf");

  output_file.Close();
  return vec;
}

void ComputeLFefficiencies(std::string filename0, std::string filename1) {
  std::array<std::string, 2> filenames { filename0, filename1 };
  std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> efficiencies[2];

  for (size_t iFile = 0; iFile < filenames.size(); ++iFile) {
    std::string& fname = filenames[iFile];
    efficiencies[iFile] = ComputeLFefficiencies(fname);
  }

  TCanvas cv_y("canvas_y");
  TCanvas cv_eta("canvas_eta");
  cv_y.Print("Comparison_y.pdf[","pdf");
  cv_eta.Print("Comparison_eta.pdf[","pdf");

  for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
    for (int iCharge = 0; iCharge < 2; ++iCharge) {
      cv_y.cd();
      cv_y.DrawFrame(0.,0.,6.,2.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
      cv_eta.cd();
      cv_eta.DrawFrame(0.,0.,6.,2.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));

      for (size_t iHist = 0; iHist < efficiencies[0].first[(iSpecies-2)*2+iCharge].size(); ++iHist) {
        cv_y.cd();
        efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].first[(iSpecies-2)*2+iCharge][iHist]);
        efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");

        cv_eta.cd();
        efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].second[(iSpecies-2)*2+iCharge][iHist]);
        efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");

      }
      cv_y.BuildLegend();
      cv_eta.BuildLegend();
      cv_y.Print("Comparison_y.pdf","pdf");
      cv_eta.Print("Comparison_eta.pdf","pdf");

    }
  }

  cv_y.Print("Comparison_y.pdf]","pdf");
  cv_eta.Print("Comparison_eta.pdf]","pdf");
}
<|endoftext|>


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

#include <grpc/support/port_platform.h>

#include "src/core/lib/http/httpcli.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/tsi/ssl_transport_security.h"

class grpc_httpcli_ssl_channel_security_connector final
    : public grpc_channel_security_connector {
 public:
  explicit grpc_httpcli_ssl_channel_security_connector(char* secure_peer_name)
      : grpc_channel_security_connector(
            /*url_scheme=*/nullptr,
            /*channel_creds=*/nullptr,
            /*request_metadata_creds=*/nullptr),
        secure_peer_name_(secure_peer_name) {}

  ~grpc_httpcli_ssl_channel_security_connector() override {
    if (handshaker_factory_ != nullptr) {
      tsi_ssl_client_handshaker_factory_unref(handshaker_factory_);
    }
    if (secure_peer_name_ != nullptr) {
      gpr_free(secure_peer_name_);
    }
  }

  tsi_result InitHandshakerFactory(const char* pem_root_certs,
                                   const tsi_ssl_root_certs_store* root_store) {
    tsi_ssl_client_handshaker_options options;
    memset(&options, 0, sizeof(options));
    options.pem_root_certs = pem_root_certs;
    options.root_store = root_store;
    return tsi_create_ssl_client_handshaker_factory_with_options(
        &options, &handshaker_factory_);
  }

  void add_handshakers(grpc_pollset_set* interested_parties,
                       grpc_core::HandshakeManager* handshake_mgr) override {
    tsi_handshaker* handshaker = nullptr;
    if (handshaker_factory_ != nullptr) {
      tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker(
          handshaker_factory_, secure_peer_name_, &handshaker);
      if (result != TSI_OK) {
        gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.",
                tsi_result_to_string(result));
      }
    }
    handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(handshaker, this));
  }

  tsi_ssl_client_handshaker_factory* handshaker_factory() const {
    return handshaker_factory_;
  }

  void check_peer(tsi_peer peer, grpc_endpoint* ep,
                  grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/,
                  grpc_closure* on_peer_checked) override {
    grpc_error* error = GRPC_ERROR_NONE;

    /* Check the peer name. */
    if (secure_peer_name_ != nullptr &&
        !tsi_ssl_peer_matches_name(&peer, secure_peer_name_)) {
      char* msg;
      gpr_asprintf(&msg, "Peer name %s is not in peer certificate",
                   secure_peer_name_);
      error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
      gpr_free(msg);
    }
    GRPC_CLOSURE_SCHED(on_peer_checked, error);
    tsi_peer_destruct(&peer);
  }

  int cmp(const grpc_security_connector* other_sc) const override {
    auto* other =
        reinterpret_cast<const grpc_httpcli_ssl_channel_security_connector*>(
            other_sc);
    return strcmp(secure_peer_name_, other->secure_peer_name_);
  }

  bool check_call_host(const char* host, grpc_auth_context* auth_context,
                       grpc_closure* on_call_host_checked,
                       grpc_error** error) override {
    *error = GRPC_ERROR_NONE;
    return true;
  }

  void cancel_check_call_host(grpc_closure* on_call_host_checked,
                              grpc_error* error) override {
    GRPC_ERROR_UNREF(error);
  }

  const char* secure_peer_name() const { return secure_peer_name_; }

 private:
  tsi_ssl_client_handshaker_factory* handshaker_factory_ = nullptr;
  char* secure_peer_name_;
};

static grpc_core::RefCountedPtr<grpc_channel_security_connector>
httpcli_ssl_channel_security_connector_create(
    const char* pem_root_certs, const tsi_ssl_root_certs_store* root_store,
    const char* secure_peer_name) {
  if (secure_peer_name != nullptr && pem_root_certs == nullptr) {
    gpr_log(GPR_ERROR,
            "Cannot assert a secure peer name without a trust root.");
    return nullptr;
  }
  grpc_core::RefCountedPtr<grpc_httpcli_ssl_channel_security_connector> c =
      grpc_core::MakeRefCounted<grpc_httpcli_ssl_channel_security_connector>(
          secure_peer_name == nullptr ? nullptr : gpr_strdup(secure_peer_name));
  tsi_result result = c->InitHandshakerFactory(pem_root_certs, root_store);
  if (result != TSI_OK) {
    gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
            tsi_result_to_string(result));
    return nullptr;
  }
  return c;
}

/* handshaker */

typedef struct {
  void (*func)(void* arg, grpc_endpoint* endpoint);
  void* arg;
  grpc_core::RefCountedPtr<grpc_core::HandshakeManager> handshake_mgr;
} on_done_closure;

static void on_handshake_done(void* arg, grpc_error* error) {
  auto* args = static_cast<grpc_core::HandshakerArgs*>(arg);
  on_done_closure* c = static_cast<on_done_closure*>(args->user_data);
  if (error != GRPC_ERROR_NONE) {
    const char* msg = grpc_error_string(error);
    gpr_log(GPR_ERROR, "Secure transport setup failed: %s", msg);

    c->func(c->arg, nullptr);
  } else {
    grpc_channel_args_destroy(args->args);
    grpc_slice_buffer_destroy_internal(args->read_buffer);
    gpr_free(args->read_buffer);
    c->func(c->arg, args->endpoint);
  }
  grpc_core::Delete<on_done_closure>(c);
}

static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
                          grpc_millis deadline,
                          void (*on_done)(void* arg, grpc_endpoint* endpoint)) {
  auto* c = grpc_core::New<on_done_closure>();
  const char* pem_root_certs =
      grpc_core::DefaultSslRootStore::GetPemRootCerts();
  const tsi_ssl_root_certs_store* root_store =
      grpc_core::DefaultSslRootStore::GetRootStore();
  if (root_store == nullptr) {
    gpr_log(GPR_ERROR, "Could not get default pem root certs.");
    on_done(arg, nullptr);
    gpr_free(c);
    return;
  }
  c->func = on_done;
  c->arg = arg;
  grpc_core::RefCountedPtr<grpc_channel_security_connector> sc =
      httpcli_ssl_channel_security_connector_create(pem_root_certs, root_store,
                                                    host);
  GPR_ASSERT(sc != nullptr);
  grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get());
  grpc_channel_args args = {1, &channel_arg};
  c->handshake_mgr = grpc_core::MakeRefCounted<grpc_core::HandshakeManager>();
  grpc_core::HandshakerRegistry::AddHandshakers(
      grpc_core::HANDSHAKER_CLIENT, &args, /*interested_parties=*/nullptr,
      c->handshake_mgr.get());
  c->handshake_mgr->DoHandshake(tcp, /*channel_args=*/nullptr, deadline,
                                /*acceptor=*/nullptr, on_handshake_done,
                                /*user_data=*/c);
  sc.reset(DEBUG_LOCATION, "httpcli");
}

const grpc_httpcli_handshaker grpc_httpcli_ssl = {"https", ssl_handshake};
<commit_msg>Removing a few more non-trivial struct memsets, part 3.<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/http/httpcli.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/tsi/ssl_transport_security.h"

class grpc_httpcli_ssl_channel_security_connector final
    : public grpc_channel_security_connector {
 public:
  explicit grpc_httpcli_ssl_channel_security_connector(char* secure_peer_name)
      : grpc_channel_security_connector(
            /*url_scheme=*/nullptr,
            /*channel_creds=*/nullptr,
            /*request_metadata_creds=*/nullptr),
        secure_peer_name_(secure_peer_name) {}

  ~grpc_httpcli_ssl_channel_security_connector() override {
    if (handshaker_factory_ != nullptr) {
      tsi_ssl_client_handshaker_factory_unref(handshaker_factory_);
    }
    if (secure_peer_name_ != nullptr) {
      gpr_free(secure_peer_name_);
    }
  }

  tsi_result InitHandshakerFactory(const char* pem_root_certs,
                                   const tsi_ssl_root_certs_store* root_store) {
    tsi_ssl_client_handshaker_options options;
    options.pem_root_certs = pem_root_certs;
    options.root_store = root_store;
    return tsi_create_ssl_client_handshaker_factory_with_options(
        &options, &handshaker_factory_);
  }

  void add_handshakers(grpc_pollset_set* interested_parties,
                       grpc_core::HandshakeManager* handshake_mgr) override {
    tsi_handshaker* handshaker = nullptr;
    if (handshaker_factory_ != nullptr) {
      tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker(
          handshaker_factory_, secure_peer_name_, &handshaker);
      if (result != TSI_OK) {
        gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.",
                tsi_result_to_string(result));
      }
    }
    handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(handshaker, this));
  }

  tsi_ssl_client_handshaker_factory* handshaker_factory() const {
    return handshaker_factory_;
  }

  void check_peer(tsi_peer peer, grpc_endpoint* ep,
                  grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/,
                  grpc_closure* on_peer_checked) override {
    grpc_error* error = GRPC_ERROR_NONE;

    /* Check the peer name. */
    if (secure_peer_name_ != nullptr &&
        !tsi_ssl_peer_matches_name(&peer, secure_peer_name_)) {
      char* msg;
      gpr_asprintf(&msg, "Peer name %s is not in peer certificate",
                   secure_peer_name_);
      error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
      gpr_free(msg);
    }
    GRPC_CLOSURE_SCHED(on_peer_checked, error);
    tsi_peer_destruct(&peer);
  }

  int cmp(const grpc_security_connector* other_sc) const override {
    auto* other =
        reinterpret_cast<const grpc_httpcli_ssl_channel_security_connector*>(
            other_sc);
    return strcmp(secure_peer_name_, other->secure_peer_name_);
  }

  bool check_call_host(const char* host, grpc_auth_context* auth_context,
                       grpc_closure* on_call_host_checked,
                       grpc_error** error) override {
    *error = GRPC_ERROR_NONE;
    return true;
  }

  void cancel_check_call_host(grpc_closure* on_call_host_checked,
                              grpc_error* error) override {
    GRPC_ERROR_UNREF(error);
  }

  const char* secure_peer_name() const { return secure_peer_name_; }

 private:
  tsi_ssl_client_handshaker_factory* handshaker_factory_ = nullptr;
  char* secure_peer_name_;
};

static grpc_core::RefCountedPtr<grpc_channel_security_connector>
httpcli_ssl_channel_security_connector_create(
    const char* pem_root_certs, const tsi_ssl_root_certs_store* root_store,
    const char* secure_peer_name) {
  if (secure_peer_name != nullptr && pem_root_certs == nullptr) {
    gpr_log(GPR_ERROR,
            "Cannot assert a secure peer name without a trust root.");
    return nullptr;
  }
  grpc_core::RefCountedPtr<grpc_httpcli_ssl_channel_security_connector> c =
      grpc_core::MakeRefCounted<grpc_httpcli_ssl_channel_security_connector>(
          secure_peer_name == nullptr ? nullptr : gpr_strdup(secure_peer_name));
  tsi_result result = c->InitHandshakerFactory(pem_root_certs, root_store);
  if (result != TSI_OK) {
    gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
            tsi_result_to_string(result));
    return nullptr;
  }
  return c;
}

/* handshaker */

typedef struct {
  void (*func)(void* arg, grpc_endpoint* endpoint);
  void* arg;
  grpc_core::RefCountedPtr<grpc_core::HandshakeManager> handshake_mgr;
} on_done_closure;

static void on_handshake_done(void* arg, grpc_error* error) {
  auto* args = static_cast<grpc_core::HandshakerArgs*>(arg);
  on_done_closure* c = static_cast<on_done_closure*>(args->user_data);
  if (error != GRPC_ERROR_NONE) {
    const char* msg = grpc_error_string(error);
    gpr_log(GPR_ERROR, "Secure transport setup failed: %s", msg);

    c->func(c->arg, nullptr);
  } else {
    grpc_channel_args_destroy(args->args);
    grpc_slice_buffer_destroy_internal(args->read_buffer);
    gpr_free(args->read_buffer);
    c->func(c->arg, args->endpoint);
  }
  grpc_core::Delete<on_done_closure>(c);
}

static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
                          grpc_millis deadline,
                          void (*on_done)(void* arg, grpc_endpoint* endpoint)) {
  auto* c = grpc_core::New<on_done_closure>();
  const char* pem_root_certs =
      grpc_core::DefaultSslRootStore::GetPemRootCerts();
  const tsi_ssl_root_certs_store* root_store =
      grpc_core::DefaultSslRootStore::GetRootStore();
  if (root_store == nullptr) {
    gpr_log(GPR_ERROR, "Could not get default pem root certs.");
    on_done(arg, nullptr);
    gpr_free(c);
    return;
  }
  c->func = on_done;
  c->arg = arg;
  grpc_core::RefCountedPtr<grpc_channel_security_connector> sc =
      httpcli_ssl_channel_security_connector_create(pem_root_certs, root_store,
                                                    host);
  GPR_ASSERT(sc != nullptr);
  grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get());
  grpc_channel_args args = {1, &channel_arg};
  c->handshake_mgr = grpc_core::MakeRefCounted<grpc_core::HandshakeManager>();
  grpc_core::HandshakerRegistry::AddHandshakers(
      grpc_core::HANDSHAKER_CLIENT, &args, /*interested_parties=*/nullptr,
      c->handshake_mgr.get());
  c->handshake_mgr->DoHandshake(tcp, /*channel_args=*/nullptr, deadline,
                                /*acceptor=*/nullptr, on_handshake_done,
                                /*user_data=*/c);
  sc.reset(DEBUG_LOCATION, "httpcli");
}

const grpc_httpcli_handshaker grpc_httpcli_ssl = {"https", ssl_handshake};
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTimerLog.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkTimerLog - Maintains timing table for performance analysis
// .SECTION Description
// vtkTimerLog contains walltime and cputime measurements associated
// with a given event.  These results can be later analyzed when
// "dumping out" the table.
//
// In addition, vtkTimerLog allows the user to simply get the current
// time, and to start/stop a simple timer separate from the timing
// table logging.

#include "vtkTimerLog.h"
#ifndef _WIN32
#include <limits.h>     // for CLK_TCK
#endif

// initialze the class variables
int vtkTimerLog::MaxEntries = 100;
int vtkTimerLog::NextEntry = 0;
int vtkTimerLog::WrapFlag = 0;
vtkTimerLogEntry *vtkTimerLog::TimerLog = NULL;
#ifdef _WIN32
int vtkTimerLog::TicksPerSecond = 60;
#else
int vtkTimerLog::TicksPerSecond = CLK_TCK;
#endif

#ifdef _WIN32
timeb vtkTimerLog::FirstWallTime;
timeb vtkTimerLog::CurrentWallTime;
#else
timeval vtkTimerLog::FirstWallTime;
timeval vtkTimerLog::CurrentWallTime;
tms     vtkTimerLog::FirstCpuTicks;
tms     vtkTimerLog::CurrentCpuTicks;
#endif

// Description:
// Allocate timing table with MaxEntries elements.
void vtkTimerLog::AllocateLog()
{
  if (vtkTimerLog::TimerLog != NULL) delete [] vtkTimerLog::TimerLog;
  vtkTimerLog::TimerLog = new vtkTimerLogEntry[vtkTimerLog::MaxEntries];
}

// Description:
// Clear the timing table.  walltime and cputime will also be set
// to zero when the first new event is recorded.
void vtkTimerLog::ResetLog()
{
  vtkTimerLog::WrapFlag = 0;
  vtkTimerLog::NextEntry = 0;
  // may want to free TimerLog to force realloc so
  // that user can resize the table by changing MaxEntries.
}

// Description:
// Record a timing event.  The event is represented by a formatted
// string.
void vtkTimerLog::FormatAndMarkEvent(char *format, ...)
{
  char event[80];

  va_list var_args;
  va_start(var_args, format);
  vsprintf(event, format, var_args);
  va_end(var_args);

  vtkTimerLog::MarkEvent(event);
}

// Description:
// Record a timing event and capture walltime and cputicks.
void vtkTimerLog::MarkEvent(char *event)
{
  int strsize;
  double time_diff;
  int ticks_diff;

  strsize = (strlen(event)) > VTK_LOG_EVENT_LENGTH - 1 ? VTK_LOG_EVENT_LENGTH-1 : strlen(event);

  // If this the first event we're recording, allocate the
  // internal timing table and initialize WallTime and CpuTicks
  // for this first event to zero.
  if (vtkTimerLog::NextEntry == 0 && ! vtkTimerLog::WrapFlag)
    {
    if (vtkTimerLog::TimerLog == NULL)
      {
      vtkTimerLog::AllocateLog();
      }

#ifdef _WIN32
    ftime( &(vtkTimerLog::FirstWallTime) );
#else
    gettimeofday( &(vtkTimerLog::FirstWallTime), NULL );
    times(&FirstCpuTicks);
#endif

    TimerLog[0].WallTime = 0.0;
    TimerLog[0].CpuTicks = 0;
    strncpy(TimerLog[0].Event, event, strsize);
    TimerLog[0].Event[strsize] = '\0';
    NextEntry = 1;
    return;
    }

#ifdef _WIN32
  static double scale = 1.0/1000.0;
  ftime( &(vtkTimerLog::CurrentWallTime) );
  time_diff  =  vtkTimerLog::CurrentWallTime.time - vtkTimerLog::FirstWallTime.time;
  time_diff +=
    (vtkTimerLog::CurrentWallTime.millitm - vtkTimerLog::FirstWallTime.millitm) * scale;
  ticks_diff = 0;
#else
  static double scale = 1.0/1000000.0;
  gettimeofday( &(vtkTimerLog::CurrentWallTime), NULL );
  time_diff  =  vtkTimerLog::CurrentWallTime.tv_sec - vtkTimerLog::FirstWallTime.tv_sec;
  time_diff +=
    (vtkTimerLog::CurrentWallTime.tv_usec - vtkTimerLog::FirstWallTime.tv_usec) * scale;

  times(&CurrentCpuTicks);
  ticks_diff = (CurrentCpuTicks.tms_utime + CurrentCpuTicks.tms_stime) -
                (FirstCpuTicks.tms_utime + FirstCpuTicks.tms_stime);
#endif

  TimerLog[NextEntry].WallTime = (float)time_diff;
  TimerLog[NextEntry].CpuTicks = ticks_diff;
  strncpy(TimerLog[NextEntry].Event, event, strsize);
  TimerLog[NextEntry].Event[strsize] = '\0';

  NextEntry++;
  if (NextEntry == MaxEntries)
    {
    NextEntry = 0;
    WrapFlag = 1;
    }
}

// Description:
// Write the timing table out to a file.  Calculate some helpful
// statistics (deltas and  percentages) in the process.
void vtkTimerLog::DumpLog(char *filename)
{
  ofstream os(filename);
  int i;

  os << " Entry   Wall Time (sec)  Delta   CPU Time (sec)  Delta  %CPU   Event\n";
  os << "----------------------------------------------------------------------\n";

  if ( WrapFlag )
    {
    DumpEntry(os, 0, TimerLog[NextEntry].WallTime, 0,
              TimerLog[NextEntry].CpuTicks, 0, TimerLog[NextEntry].Event);
    for (i=NextEntry+1; i<MaxEntries; i++)
      {
      DumpEntry(os, i-NextEntry, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    DumpEntry(os, MaxEntries-NextEntry, TimerLog[0].WallTime,
              TimerLog[0].WallTime - TimerLog[MaxEntries-1].WallTime,
              TimerLog[0].CpuTicks,
              TimerLog[0].CpuTicks - TimerLog[MaxEntries-1].CpuTicks,
              TimerLog[0].Event);
    for (i=1; i<NextEntry; i++)
      {
      DumpEntry(os, MaxEntries-NextEntry+i, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    }
  else
    {
    DumpEntry(os, 0, TimerLog[0].WallTime, 0,
              TimerLog[0].CpuTicks, 0, TimerLog[0].Event);
    for (i=1; i<NextEntry; i++)
      {
      DumpEntry(os, i, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    }

  os.close();
}

// Description:
// Print method for vtkTimerLog.
void vtkTimerLog::PrintSelf(ostream& os, vtkIndent indent)
{
  int i;

  vtkObject::PrintSelf(os, indent);

  os << indent << "MaxEntries: " << vtkTimerLog::MaxEntries << "\n";
  os << indent << "NextEntry: " << vtkTimerLog::NextEntry << "\n";
  os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n";
  os << indent << "TicksPerSecond: " << vtkTimerLog::TicksPerSecond << "\n";
  os << "\n";

  os << indent << "Entry \tWall Time\tCpuTicks\tEvent\n";
  os << indent << "----------------------------------------------\n";

  if ( WrapFlag )
    {
    for (i=NextEntry; i<MaxEntries; i++)
      {
      os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" <<
	TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n";
      }
    }

  for (i=0; i<NextEntry; i++)
    {
    os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" <<
      TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n";
    }

  os << "\n" << indent << "StartTime: " << this->StartTime << "\n";
  os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n";
}

// Methods to support simple timer functionality, separate from
// timer table logging.

// Description:
// Returns the elapsed number of seconds since January 1, 1970. This
// is also called Universal Coordinated Time.
double vtkTimerLog::GetCurrentTime()
{
  double currentTimeInSeconds;

#ifdef _WIN32
  timeb CurrentTime;
  static double scale = 1.0/1000.0;
  ftime( &CurrentTime );
  currentTimeInSeconds = CurrentTime.time + scale * CurrentTime.millitm;
#else
  timeval CurrentTime;
  static double scale = 1.0/1000000.0;
  gettimeofday( &CurrentTime, NULL );
  currentTimeInSeconds = CurrentTime.tv_sec + scale * CurrentTime.tv_usec;
#endif

  return (currentTimeInSeconds);
}

// Description:
// Set the StartTime to the current time. Used with GetElapsedTime().
void vtkTimerLog::StartTimer()
{
  this->StartTime = vtkTimerLog::GetCurrentTime();
}

// Description:
// Sets EndTime to the current time. Used with GetElapsedTime().
void vtkTimerLog::StopTimer()
{
  this->EndTime = vtkTimerLog::GetCurrentTime();
}

// Description:
// Returns the difference between StartTime and EndTime as
// a floating point value indicating the elapsed time in seconds.
double vtkTimerLog::GetElapsedTime()
{
  return (this->EndTime - this->StartTime);
}

void vtkTimerLog::DumpEntry(ostream& os, int index, float time,
			    float deltatime,
			    int tick, int deltatick, char *event)
{
  os << index << "   "
     << time << "  "
     << deltatime << "   "
     << (float)tick/TicksPerSecond << "  "
     << (float)deltatick/TicksPerSecond << "  ";
  if (deltatime == 0.0)
    os << "0.0   ";
  else
    os << 100.0*deltatick/TicksPerSecond/deltatime << "   ";
  os << event << "\n";
}

void vtkTimerLog::SetMaxEntries(int a)
{
  vtkTimerLog::MaxEntries = a;
}

int vtkTimerLog::GetMaxEntries()
{
  return vtkTimerLog::MaxEntries;
}
<commit_msg>ERR: In FormatAndMarkEvent, event was declared with 80 character limit. Increased to 4096 and made static.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTimerLog.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkTimerLog - Maintains timing table for performance analysis
// .SECTION Description
// vtkTimerLog contains walltime and cputime measurements associated
// with a given event.  These results can be later analyzed when
// "dumping out" the table.
//
// In addition, vtkTimerLog allows the user to simply get the current
// time, and to start/stop a simple timer separate from the timing
// table logging.

#include "vtkTimerLog.h"
#ifndef _WIN32
#include <limits.h>     // for CLK_TCK
#endif

// initialze the class variables
int vtkTimerLog::MaxEntries = 100;
int vtkTimerLog::NextEntry = 0;
int vtkTimerLog::WrapFlag = 0;
vtkTimerLogEntry *vtkTimerLog::TimerLog = NULL;
#ifdef _WIN32
int vtkTimerLog::TicksPerSecond = 60;
#else
int vtkTimerLog::TicksPerSecond = CLK_TCK;
#endif

#ifdef _WIN32
timeb vtkTimerLog::FirstWallTime;
timeb vtkTimerLog::CurrentWallTime;
#else
timeval vtkTimerLog::FirstWallTime;
timeval vtkTimerLog::CurrentWallTime;
tms     vtkTimerLog::FirstCpuTicks;
tms     vtkTimerLog::CurrentCpuTicks;
#endif

// Description:
// Allocate timing table with MaxEntries elements.
void vtkTimerLog::AllocateLog()
{
  if (vtkTimerLog::TimerLog != NULL) delete [] vtkTimerLog::TimerLog;
  vtkTimerLog::TimerLog = new vtkTimerLogEntry[vtkTimerLog::MaxEntries];
}

// Description:
// Clear the timing table.  walltime and cputime will also be set
// to zero when the first new event is recorded.
void vtkTimerLog::ResetLog()
{
  vtkTimerLog::WrapFlag = 0;
  vtkTimerLog::NextEntry = 0;
  // may want to free TimerLog to force realloc so
  // that user can resize the table by changing MaxEntries.
}

// Description:
// Record a timing event.  The event is represented by a formatted
// string.
void vtkTimerLog::FormatAndMarkEvent(char *format, ...)
{
static  char event[4096];

  va_list var_args;
  va_start(var_args, format);
  vsprintf(event, format, var_args);
  va_end(var_args);

  vtkTimerLog::MarkEvent(event);
}

// Description:
// Record a timing event and capture walltime and cputicks.
void vtkTimerLog::MarkEvent(char *event)
{
  int strsize;
  double time_diff;
  int ticks_diff;

  strsize = (strlen(event)) > VTK_LOG_EVENT_LENGTH - 1 ? VTK_LOG_EVENT_LENGTH-1 : strlen(event);

  // If this the first event we're recording, allocate the
  // internal timing table and initialize WallTime and CpuTicks
  // for this first event to zero.
  if (vtkTimerLog::NextEntry == 0 && ! vtkTimerLog::WrapFlag)
    {
    if (vtkTimerLog::TimerLog == NULL)
      {
      vtkTimerLog::AllocateLog();
      }

#ifdef _WIN32
    ftime( &(vtkTimerLog::FirstWallTime) );
#else
    gettimeofday( &(vtkTimerLog::FirstWallTime), NULL );
    times(&FirstCpuTicks);
#endif

    TimerLog[0].WallTime = 0.0;
    TimerLog[0].CpuTicks = 0;
    strncpy(TimerLog[0].Event, event, strsize);
    TimerLog[0].Event[strsize] = '\0';
    NextEntry = 1;
    return;
    }

#ifdef _WIN32
  static double scale = 1.0/1000.0;
  ftime( &(vtkTimerLog::CurrentWallTime) );
  time_diff  =  vtkTimerLog::CurrentWallTime.time - vtkTimerLog::FirstWallTime.time;
  time_diff +=
    (vtkTimerLog::CurrentWallTime.millitm - vtkTimerLog::FirstWallTime.millitm) * scale;
  ticks_diff = 0;
#else
  static double scale = 1.0/1000000.0;
  gettimeofday( &(vtkTimerLog::CurrentWallTime), NULL );
  time_diff  =  vtkTimerLog::CurrentWallTime.tv_sec - vtkTimerLog::FirstWallTime.tv_sec;
  time_diff +=
    (vtkTimerLog::CurrentWallTime.tv_usec - vtkTimerLog::FirstWallTime.tv_usec) * scale;

  times(&CurrentCpuTicks);
  ticks_diff = (CurrentCpuTicks.tms_utime + CurrentCpuTicks.tms_stime) -
                (FirstCpuTicks.tms_utime + FirstCpuTicks.tms_stime);
#endif

  TimerLog[NextEntry].WallTime = (float)time_diff;
  TimerLog[NextEntry].CpuTicks = ticks_diff;
  strncpy(TimerLog[NextEntry].Event, event, strsize);
  TimerLog[NextEntry].Event[strsize] = '\0';

  NextEntry++;
  if (NextEntry == MaxEntries)
    {
    NextEntry = 0;
    WrapFlag = 1;
    }
}

// Description:
// Write the timing table out to a file.  Calculate some helpful
// statistics (deltas and  percentages) in the process.
void vtkTimerLog::DumpLog(char *filename)
{
  ofstream os(filename);
  int i;

  os << " Entry   Wall Time (sec)  Delta   CPU Time (sec)  Delta  %CPU   Event\n";
  os << "----------------------------------------------------------------------\n";

  if ( WrapFlag )
    {
    DumpEntry(os, 0, TimerLog[NextEntry].WallTime, 0,
              TimerLog[NextEntry].CpuTicks, 0, TimerLog[NextEntry].Event);
    for (i=NextEntry+1; i<MaxEntries; i++)
      {
      DumpEntry(os, i-NextEntry, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    DumpEntry(os, MaxEntries-NextEntry, TimerLog[0].WallTime,
              TimerLog[0].WallTime - TimerLog[MaxEntries-1].WallTime,
              TimerLog[0].CpuTicks,
              TimerLog[0].CpuTicks - TimerLog[MaxEntries-1].CpuTicks,
              TimerLog[0].Event);
    for (i=1; i<NextEntry; i++)
      {
      DumpEntry(os, MaxEntries-NextEntry+i, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    }
  else
    {
    DumpEntry(os, 0, TimerLog[0].WallTime, 0,
              TimerLog[0].CpuTicks, 0, TimerLog[0].Event);
    for (i=1; i<NextEntry; i++)
      {
      DumpEntry(os, i, TimerLog[i].WallTime,
                TimerLog[i].WallTime - TimerLog[i-1].WallTime,
                TimerLog[i].CpuTicks,
                TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks,
                TimerLog[i].Event);
      }
    }

  os.close();
}

// Description:
// Print method for vtkTimerLog.
void vtkTimerLog::PrintSelf(ostream& os, vtkIndent indent)
{
  int i;

  vtkObject::PrintSelf(os, indent);

  os << indent << "MaxEntries: " << vtkTimerLog::MaxEntries << "\n";
  os << indent << "NextEntry: " << vtkTimerLog::NextEntry << "\n";
  os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n";
  os << indent << "TicksPerSecond: " << vtkTimerLog::TicksPerSecond << "\n";
  os << "\n";

  os << indent << "Entry \tWall Time\tCpuTicks\tEvent\n";
  os << indent << "----------------------------------------------\n";

  if ( WrapFlag )
    {
    for (i=NextEntry; i<MaxEntries; i++)
      {
      os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" <<
	TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n";
      }
    }

  for (i=0; i<NextEntry; i++)
    {
    os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" <<
      TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n";
    }

  os << "\n" << indent << "StartTime: " << this->StartTime << "\n";
  os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n";
}

// Methods to support simple timer functionality, separate from
// timer table logging.

// Description:
// Returns the elapsed number of seconds since January 1, 1970. This
// is also called Universal Coordinated Time.
double vtkTimerLog::GetCurrentTime()
{
  double currentTimeInSeconds;

#ifdef _WIN32
  timeb CurrentTime;
  static double scale = 1.0/1000.0;
  ftime( &CurrentTime );
  currentTimeInSeconds = CurrentTime.time + scale * CurrentTime.millitm;
#else
  timeval CurrentTime;
  static double scale = 1.0/1000000.0;
  gettimeofday( &CurrentTime, NULL );
  currentTimeInSeconds = CurrentTime.tv_sec + scale * CurrentTime.tv_usec;
#endif

  return (currentTimeInSeconds);
}

// Description:
// Set the StartTime to the current time. Used with GetElapsedTime().
void vtkTimerLog::StartTimer()
{
  this->StartTime = vtkTimerLog::GetCurrentTime();
}

// Description:
// Sets EndTime to the current time. Used with GetElapsedTime().
void vtkTimerLog::StopTimer()
{
  this->EndTime = vtkTimerLog::GetCurrentTime();
}

// Description:
// Returns the difference between StartTime and EndTime as
// a floating point value indicating the elapsed time in seconds.
double vtkTimerLog::GetElapsedTime()
{
  return (this->EndTime - this->StartTime);
}

void vtkTimerLog::DumpEntry(ostream& os, int index, float time,
			    float deltatime,
			    int tick, int deltatick, char *event)
{
  os << index << "   "
     << time << "  "
     << deltatime << "   "
     << (float)tick/TicksPerSecond << "  "
     << (float)deltatick/TicksPerSecond << "  ";
  if (deltatime == 0.0)
    os << "0.0   ";
  else
    os << 100.0*deltatick/TicksPerSecond/deltatime << "   ";
  os << event << "\n";
}

void vtkTimerLog::SetMaxEntries(int a)
{
  vtkTimerLog::MaxEntries = a;
}

int vtkTimerLog::GetMaxEntries()
{
  return vtkTimerLog::MaxEntries;
}
<|endoftext|>


<commit_before>#include "../test_module.hpp"
#include "../test_container.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestAbstractClassImpl(Container, Container<T>)
{
    NNRunAbstractTest(Module, Container, nnImpl.copy());

    NNTestMethod(forget)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
            {
                Module<T> &component = *nnImpl.component(i);
                component.state().fill(i);
                auto oldState = component.state().copy();
                nnImpl.forget();
                forEach([&](T oldState, T newState)
                {
                    NNTestAlmostEquals(oldState, i, 1e-12);
                    NNTestAlmostEquals(newState, 0, 1e-12);
                }, oldState, component.state());
            }
        }
    }

    NNTestMethod(save)
    {
        NNTestParams(Serialized &)
        {
            Serialized s;
            nnImpl.save(s);

            RandomEngine::sharedEngine().seed(0);
            auto input = math::rand(Tensor<T>(nnImpl.inputShape(), true));
            auto output = math::rand(Tensor<T>(nnImpl.outputShape(), true));

            auto copy = Serialized(nnImpl).get<Container<T> *>();
            NNTestEquals(nnImpl.components(), copy->components());

            RandomEngine::sharedEngine().seed(0);
            nnImpl.forget();
            nnImpl.grad().fill(0);
            nnImpl.forward(input);
            nnImpl.backward(input, output);

            RandomEngine::sharedEngine().seed(0);
            copy->forget();
            copy->grad().fill(0);
            copy->forward(input);
            copy->backward(input, output);

            forEach([&](T origOutput, T copyOutput)
            {
                NNTestAlmostEquals(origOutput, copyOutput, 1e-12);
            }, nnImpl.output(), copy->output());

            forEach([&](T origInGrad, T copyInGrad)
            {
                NNTestAlmostEquals(origInGrad, copyInGrad, 1e-12);
            }, nnImpl.inGrad(), copy->inGrad());

            forEach([&](T origParamGrad, T copyParamGrad)
            {
                NNTestAlmostEquals(origParamGrad, copyParamGrad, 1e-12);
            }, nnImpl.grad(), copy->grad());

            delete copy;
        }
    }

    NNTestMethod(add)
    {
        NNTestParams(Module *)
        {
            size_t count = nnImpl.components();
            auto last = nnImpl.remove(count - 1);
            NNTestEquals(count - 1, nnImpl.components());
            nnImpl.add(last);
            NNTestEquals(count, nnImpl.components());
        }
    }

    NNTestMethod(remove)
    {
        NNTestParams(Module *)
        {
            size_t count = nnImpl.components();
            auto last = nnImpl.remove(count - 1);
            NNTestEquals(count - 1, nnImpl.components());
            nnImpl.add(last);
            NNTestEquals(count, nnImpl.components());
        }
    }

    NNTestMethod(clear)
    {
        NNTestParams(Module *)
        {
            auto copy = (Container<T> *) nnImpl.copy();
            copy->clear();
            NNTestEquals(copy->components(), 0);
            delete copy;
        }
    }

    NNTestMethod(paramsList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->params().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.params());
        }
    }

    NNTestMethod(gradList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->grad().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.grad());
        }
    }

    NNTestMethod(stateList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->state().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.state());
        }
    }
}
<commit_msg>Fixed Container tests.<commit_after>#include "../test_module.hpp"
#include "../test_container.hpp"
#include "nnlib/nn/batchnorm.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestAbstractClassImpl(Container, Container<T>)
{
    NNRunAbstractTest(Module, Container, nnImpl.copy());

    NNTestMethod(training)
    {
        auto component = new BatchNorm<T>(10);
        auto copy = (Container<T> *) nnImpl.copy();
        copy->clear();
        copy->add(component);
        copy->training(true);
        NNTest(component->isTraining());
        copy->training(false);
        NNTest(!component->isTraining());
        delete copy;
    }

    NNTestMethod(forget)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
            {
                Module<T> &component = *nnImpl.component(i);
                component.state().fill(i);
                auto oldState = component.state().copy();
                nnImpl.forget();
                forEach([&](T oldState, T newState)
                {
                    NNTestAlmostEquals(oldState, i, 1e-12);
                    NNTestAlmostEquals(newState, 0, 1e-12);
                }, oldState, component.state());
            }
        }
    }

    NNTestMethod(save)
    {
        NNTestParams(Serialized &)
        {
            Serialized s;
            nnImpl.save(s);

            RandomEngine::sharedEngine().seed(0);
            auto input = math::rand(Tensor<T>(nnImpl.inputShape(), true));
            auto output = math::rand(Tensor<T>(nnImpl.outputShape(), true));

            auto copy = Serialized(nnImpl).get<Container<T> *>();
            NNTestEquals(nnImpl.components(), copy->components());

            RandomEngine::sharedEngine().seed(0);
            nnImpl.forget();
            nnImpl.grad().fill(0);
            nnImpl.forward(input);
            nnImpl.backward(input, output);

            RandomEngine::sharedEngine().seed(0);
            copy->forget();
            copy->grad().fill(0);
            copy->forward(input);
            copy->backward(input, output);

            forEach([&](T origOutput, T copyOutput)
            {
                NNTestAlmostEquals(origOutput, copyOutput, 1e-12);
            }, nnImpl.output(), copy->output());

            forEach([&](T origInGrad, T copyInGrad)
            {
                NNTestAlmostEquals(origInGrad, copyInGrad, 1e-12);
            }, nnImpl.inGrad(), copy->inGrad());

            forEach([&](T origParamGrad, T copyParamGrad)
            {
                NNTestAlmostEquals(origParamGrad, copyParamGrad, 1e-12);
            }, nnImpl.grad(), copy->grad());

            delete copy;
        }
    }

    NNTestMethod(add)
    {
        NNTestParams(Module *)
        {
            size_t count = nnImpl.components();
            auto last = nnImpl.remove(count - 1);
            NNTestEquals(count - 1, nnImpl.components());
            nnImpl.add(last);
            NNTestEquals(count, nnImpl.components());
        }
    }

    NNTestMethod(remove)
    {
        NNTestParams(Module *)
        {
            size_t count = nnImpl.components();
            auto last = nnImpl.remove(count - 1);
            NNTestEquals(count - 1, nnImpl.components());
            nnImpl.add(last);
            NNTestEquals(count, nnImpl.components());
        }
    }

    NNTestMethod(clear)
    {
        NNTestParams(Module *)
        {
            auto copy = (Container<T> *) nnImpl.copy();
            copy->clear();
            NNTestEquals(copy->components(), 0);
            delete copy;
        }
    }

    NNTestMethod(paramsList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->params().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.params());
        }
    }

    NNTestMethod(gradList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->grad().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.grad());
        }
    }

    NNTestMethod(stateList)
    {
        NNTestParams()
        {
            for(size_t i = 0; i < nnImpl.components(); ++i)
                nnImpl.component(i)->state().fill(1);
            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 1, 1e-12);
            }, nnImpl.state());
        }
    }
}
<|endoftext|>