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

#pragma hdrstop

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _HFFRM_HXX
#include <hffrm.hxx>
#endif

#ifndef _ACCHEADERFOOTER_HXX
#include "accheaderfooter.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

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

const sal_Char sServiceNameHeader[] = "com.sun.star.text.AccessibleHeaderView";
const sal_Char sServiceNameFooter[] = "com.sun.star.text.AccessibleFooterView";
const sal_Char sImplementationNameHeader[] = "com.sun.star.comp.Writer.SwAccessibleHeaderView";
const sal_Char sImplementationNameFooter[] = "com.sun.star.comp.Writer.SwAccessibleFooterView";

SwAccessibleHeaderFooter::SwAccessibleHeaderFooter(
        SwAccessibleMap *pMap,
        const SwHeaderFrm *pHdFrm   ) :
    SwAccessibleContext( pMap, AccessibleRole::HEADER, pHdFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    OUString sArg( OUString::valueOf( (sal_Int32)pHdFrm->GetPhyPageNum() ) );
    SetName( GetResource( STR_ACCESS_HEADER_NAME, &sArg ) );
}

SwAccessibleHeaderFooter::SwAccessibleHeaderFooter(
        SwAccessibleMap *pMap,
        const SwFooterFrm *pFtFrm   ) :
    SwAccessibleContext( pMap, AccessibleRole::FOOTER, pFtFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    OUString sArg( OUString::valueOf( (sal_Int32)pFtFrm->GetPhyPageNum() ) );
    SetName( GetResource( STR_ACCESS_FOOTER_NAME, &sArg ) );
}

SwAccessibleHeaderFooter::~SwAccessibleHeaderFooter()
{
}

OUString SAL_CALL SwAccessibleHeaderFooter::getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::HEADER == GetRole()
        ? STR_ACCESS_HEADER_DESC
        : STR_ACCESS_FOOTER_DESC ;

    OUString sArg( GetFormattedPageNumber() );

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleHeaderFooter::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::HEADER == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameHeader));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFooter));
}

sal_Bool SAL_CALL SwAccessibleHeaderFooter::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (::com::sun::star::uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::HEADER == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameHeader, sizeof(sServiceNameHeader)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFooter, sizeof(sServiceNameFooter)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleHeaderFooter::getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::HEADER == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameHeader) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFooter) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleHeaderFooter::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.10.1112); FILE MERGED 2005/09/13 12:57:39 tra 1.10.1112.3: RESYNC: (1.10-1.11); FILE MERGED 2005/06/07 14:13:03 fme 1.10.1112.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:26:43 tra 1.10.1112.1: Unnecessary includes removed #i50348#<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accheaderfooter.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:44:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _HFFRM_HXX
#include <hffrm.hxx>
#endif

#ifndef _ACCHEADERFOOTER_HXX
#include "accheaderfooter.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

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

const sal_Char sServiceNameHeader[] = "com.sun.star.text.AccessibleHeaderView";
const sal_Char sServiceNameFooter[] = "com.sun.star.text.AccessibleFooterView";
const sal_Char sImplementationNameHeader[] = "com.sun.star.comp.Writer.SwAccessibleHeaderView";
const sal_Char sImplementationNameFooter[] = "com.sun.star.comp.Writer.SwAccessibleFooterView";

SwAccessibleHeaderFooter::SwAccessibleHeaderFooter(
        SwAccessibleMap *pMap,
        const SwHeaderFrm *pHdFrm   ) :
    SwAccessibleContext( pMap, AccessibleRole::HEADER, pHdFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    OUString sArg( OUString::valueOf( (sal_Int32)pHdFrm->GetPhyPageNum() ) );
    SetName( GetResource( STR_ACCESS_HEADER_NAME, &sArg ) );
}

SwAccessibleHeaderFooter::SwAccessibleHeaderFooter(
        SwAccessibleMap *pMap,
        const SwFooterFrm *pFtFrm   ) :
    SwAccessibleContext( pMap, AccessibleRole::FOOTER, pFtFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    OUString sArg( OUString::valueOf( (sal_Int32)pFtFrm->GetPhyPageNum() ) );
    SetName( GetResource( STR_ACCESS_FOOTER_NAME, &sArg ) );
}

SwAccessibleHeaderFooter::~SwAccessibleHeaderFooter()
{
}

OUString SAL_CALL SwAccessibleHeaderFooter::getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::HEADER == GetRole()
        ? STR_ACCESS_HEADER_DESC
        : STR_ACCESS_FOOTER_DESC ;

    OUString sArg( GetFormattedPageNumber() );

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleHeaderFooter::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::HEADER == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameHeader));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFooter));
}

sal_Bool SAL_CALL SwAccessibleHeaderFooter::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (::com::sun::star::uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::HEADER == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameHeader, sizeof(sServiceNameHeader)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFooter, sizeof(sServiceNameFooter)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleHeaderFooter::getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::HEADER == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameHeader) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFooter) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleHeaderFooter::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}
<|endoftext|>


<commit_before>//
// Created by kunjesh virani on 13/2/17.
// On the platform Linux (Ubuntu Xenial Xerus) 64bit
//

/** Description
*   This file is about to definitions of customly declared functions in header "linedraw.hpp"
*   This file contains various functions that can able to draw a multiple line according to given instructions in c++.
*/

#include "linedraw.h"

// in below function do not use keyword "static" because declaration in main header will generate error due to same typw with
// two time.

 void linedraw::draw() {

    // For First Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, lineVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, lineColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glClear(GL_COLOR_BUFFER_BIT); // clear the rendering buffers
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.

    // For Second Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, linefVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, linefColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.

    // For Third Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, linelVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, linelColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.
}

<commit_msg>Update linedraw.cpp<commit_after>//
// Created by KV on 13 February, 17.
// On the platform Linux (Ubuntu Xenial Xerus) 64bit
//
// hellowwoor@gmail.com
//

/** Description
*   This file is about to definitions of customly declared functions in header "linedraw.hpp"
*   This file contains various functions that can able to draw a multiple line according to given instructions in c++.
*/

#include "linedraw.h"

// in below function do not use keyword "static" because declaration in main header will generate error due to same typw with
// two time.

 void linedraw::draw() {

    // For First Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, lineVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, lineColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glClear(GL_COLOR_BUFFER_BIT); // clear the rendering buffers
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.

    // For Second Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, linefVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, linefColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.

    // For Third Line

    glShadeModel(GL_SMOOTH); // select a flat or smooth shading
    glVertexPointer(3, GL_FLOAT, 0, linelVertices);  // define the array of vertex data.
    glColorPointer(4, GL_FLOAT, 0, linelColor);   // define the array of color.
    glEnableClientState(GL_VERTEX_ARRAY);  // enable client side capability.
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawArrays(GL_LINES, 0, 2);
    glFlush(); // force execution of GL commands in a finite time.
}

<|endoftext|>


<commit_before>

CalibratePeriod(TString lPeriodName = "LHC10h"){

    //Load ALICE stuff
    TString gLibs[] =   {"STEER",
        "ANALYSIS", "ANALYSISalice", "ANALYSIScalib"};
    TString thislib = "lib";
    for(Int_t ilib = 0; ilib<4; ilib++){
        thislib="lib";
        thislib.Append(gLibs[ilib].Data());
        cout<<"Will load "<<thislib.Data()<<endl;
        gSystem->Load(thislib.Data());
    }
    gSystem->SetIncludePath("-I$ROOTSYS/include  -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include");

    cout<<"Alive! "<<endl;

    //All fine, let's try the calibrator
    AliMultSelectionCalibrator *lCalib = new AliMultSelectionCalibrator("lCalib");

    //============================================================
    // --- Definition of Boundaries ---
    //============================================================

    //Set Adaptive Percentile Boundaries, adjust if finer selection desired
    Double_t lDesiredBoundaries[1000];
    Long_t   lNDesiredBoundaries=0;
    lDesiredBoundaries[0] = 100;
    //From Low To High Multiplicity
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 1.0;
    }
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.1;
    }
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.01;
    }
    for( Int_t ib = 1; ib < 101; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.001;
    }
    lNDesiredBoundaries++;
    lDesiredBoundaries[lNDesiredBoundaries] = 0;

    lCalib->SetBoundaries( lNDesiredBoundaries, lDesiredBoundaries );
    cout<<"Boundaries set. Will attempt calibration now... "<<endl;

    if ( lPeriodName.Contains("LHC10h") ){
        cout<<"Setting event selection criteria for Pb-Pb..."<<endl;
        lCalib->GetEventCuts()->SetVzCut(1e+6);
        lCalib->GetEventCuts()->SetTriggerCut                (kTRUE );
        lCalib->GetEventCuts()->SetINELgtZEROCut             (kFALSE);
        lCalib->GetEventCuts()->SetTrackletsVsClustersCut    (kTRUE );
        lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE);
        lCalib->GetEventCuts()->SetVertexConsistencyCut      (kFALSE);
    }

    //============================================================
    // --- Definition of Input Variables ---
    //============================================================

    lCalib->SetupStandardInput();

    //============================================================
    // --- Definition of Estimators ---
    //============================================================

    AliMultEstimator *fEstV0M = new AliMultEstimator("V0M", "", "(fAmplitude_V0A)+(fAmplitude_V0C)");
    AliMultEstimator *fEstV0A = new AliMultEstimator("V0A", "", "(fAmplitude_V0A)");
    AliMultEstimator *fEstV0C = new AliMultEstimator("V0C", "", "(fAmplitude_V0C)");

    AliMultEstimator *fEstOnlineV0M = new AliMultEstimator("OnlineV0M", "", "(fAmplitude_OnlineV0A)+(fAmplitude_OnlineV0C)");
    AliMultEstimator *fEstOnlineV0A = new AliMultEstimator("OnlineV0A", "", "(fAmplitude_OnlineV0A)");
    AliMultEstimator *fEstOnlineV0C = new AliMultEstimator("OnlineV0C", "", "(fAmplitude_OnlineV0C)");

    AliMultEstimator *fEstADM = new AliMultEstimator("ADM", "", "(fMultiplicity_ADA)+(fMultiplicity_ADC)");
    AliMultEstimator *fEstADA = new AliMultEstimator("ADA", "", "(fMultiplicity_ADA)");
    AliMultEstimator *fEstADC = new AliMultEstimator("ADC", "", "(fMultiplicity_ADC)");

    //Integer estimators
    AliMultEstimator *fEstnSPDClusters = new AliMultEstimator("SPDClusters", "", "(fnSPDClusters)");
    fEstnSPDClusters->SetIsInteger(kTRUE);
    AliMultEstimator *fEstnSPDTracklets = new AliMultEstimator("SPDTracklets", "", "(fnTracklets)");
    fEstnSPDTracklets->SetIsInteger(kTRUE);
    AliMultEstimator *fEstRefMultEta5 = new AliMultEstimator("RefMult05", "", "(fRefMultEta5)");
    fEstRefMultEta5->SetIsInteger(kTRUE);
    AliMultEstimator *fEstRefMultEta8 = new AliMultEstimator("RefMult08", "", "(fRefMultEta8)");
    fEstRefMultEta8->SetIsInteger(kTRUE);

    //Univeral: V0
    lCalib->GetMultSelection() -> AddEstimator( fEstV0M );
    lCalib->GetMultSelection() -> AddEstimator( fEstV0A );
    lCalib->GetMultSelection() -> AddEstimator( fEstV0C );

    //Testing!
    AliMultEstimator *fEstV0MAnchored = new AliMultEstimator("V0MAnchored", "", "(fAmplitude_V0A)+(fAmplitude_V0C)");
    fEstV0MAnchored -> SetUseAnchor        ( kTRUE   ) ;
    fEstV0MAnchored -> SetAnchorPoint      ( 81.0    ) ;
    fEstV0MAnchored -> SetAnchorPercentile ( 90.0    ) ;
    lCalib->GetMultSelection() -> AddEstimator( fEstV0MAnchored );

    //Anchoring test

    //Only do this in run 2, AD didn't exist in Run 1
    //Will also save space in the OADB for old datasets!
    if( lPeriodName.Contains("LHC15") ){
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0M );
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0A );
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0C );
        lCalib->GetMultSelection() -> AddEstimator( fEstADM );
        lCalib->GetMultSelection() -> AddEstimator( fEstADA );
        lCalib->GetMultSelection() -> AddEstimator( fEstADC );
    }

    //Universal: Tracking, etc
    lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClusters  );
    lCalib->GetMultSelection() -> AddEstimator( fEstnSPDTracklets );
    lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta5 );
    lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta8 );

    //============================================================
    // --- Definition of Input/Output ---
    //============================================================

    if( !lPeriodName.Contains("test") ){
        //Per Period calibration: standard locations...
        lCalib -> SetInputFile  ( Form("/home/daviddc/Dropbox/MultSelCalib/%s/Merged%s.root",lPeriodName.Data(), lPeriodName.Data() ) );
        lCalib -> SetBufferFile ( Form("/home/daviddc/work/fast/buffer-%s.root", lPeriodName.Data() ) );
        lCalib -> SetOutputFile ( Form("OADB-%s.root", lPeriodName.Data() ) );
        lCalib -> Calibrate     ();
    }else{
        lCalib -> SetInputFile  ( "../MultSelCalib/LHC10h/files/AnalysisResults_137161.root");
        lCalib -> SetBufferFile ( "buffer-test.root" );
        lCalib -> SetOutputFile ( "OADB-testing.root" );
        lCalib -> Calibrate     ();
    }
}
<commit_msg>Update macro used for actual calibration at the moment<commit_after>

CalibratePeriod(TString lPeriodName = "LHC10h"){

    //Load ALICE stuff
    TString gLibs[] =   {"STEER",
        "ANALYSIS", "ANALYSISalice", "ANALYSIScalib"};
    TString thislib = "lib";
    for(Int_t ilib = 0; ilib<4; ilib++){
        thislib="lib";
        thislib.Append(gLibs[ilib].Data());
        cout<<"Will load "<<thislib.Data()<<endl;
        gSystem->Load(thislib.Data());
    }
    gSystem->SetIncludePath("-I$ROOTSYS/include  -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include");

    cout<<"Alive! "<<endl;

    //All fine, let's try the calibrator
    AliMultSelectionCalibrator *lCalib = new AliMultSelectionCalibrator("lCalib");

    //============================================================
    // --- Definition of Boundaries ---
    //============================================================

    //Set Adaptive Percentile Boundaries, adjust if finer selection desired
    Double_t lDesiredBoundaries[1000];
    Long_t   lNDesiredBoundaries=0;
    lDesiredBoundaries[0] = 100;
    //From Low To High Multiplicity
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 1.0;
    }
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.1;
    }
    for( Int_t ib = 1; ib < 91; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.01;
    }
    for( Int_t ib = 1; ib < 101; ib++) {
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.001;
    }
    lNDesiredBoundaries++;
    lDesiredBoundaries[lNDesiredBoundaries] = 0;

    lCalib->SetBoundaries( lNDesiredBoundaries, lDesiredBoundaries );
    cout<<"Boundaries set. Will attempt calibration now... "<<endl;

    if ( lPeriodName.Contains("LHC10h") ){
        cout<<"Setting event selection criteria for Pb-Pb..."<<endl;
        lCalib->GetEventCuts()->SetVzCut(10.0);
        lCalib->GetEventCuts()->SetTriggerCut                (kTRUE );
        lCalib->GetEventCuts()->SetINELgtZEROCut             (kFALSE);
        lCalib->GetEventCuts()->SetTrackletsVsClustersCut    (kTRUE );
        lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE);
        lCalib->GetEventCuts()->SetVertexConsistencyCut      (kFALSE);
        lCalib->GetEventCuts()->SetNonZeroNContribs          (kTRUE);
    }

    if ( lPeriodName.Contains("LHC15m") ){
        cout<<"Setting event selection criteria for Pb-Pb..."<<endl;
        lCalib->GetEventCuts()->SetVzCut(10.0);
        lCalib->GetEventCuts()->SetTriggerCut                (kFALSE );
        lCalib->GetEventCuts()->SetINELgtZEROCut             (kFALSE);
        lCalib->GetEventCuts()->SetTrackletsVsClustersCut    (kTRUE );
        lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE);
        lCalib->GetEventCuts()->SetVertexConsistencyCut      (kFALSE);
        lCalib->GetEventCuts()->SetNonZeroNContribs          (kTRUE);
    }

    //============================================================
    // --- Definition of Input Variables ---
    //============================================================

    lCalib->SetupStandardInput();

    //============================================================
    // --- Definition of Estimators ---
    //============================================================

    AliMultEstimator *fEstV0M = new AliMultEstimator("V0M", "", "(fAmplitude_V0A)+(fAmplitude_V0C)");
    if( lPeriodName.Contains("LHC10h") ) {
        fEstV0M -> SetUseAnchor        ( kTRUE   ) ;
        fEstV0M -> SetAnchorPoint      ( 81.0    ) ;
        fEstV0M -> SetAnchorPercentile ( 90.0    ) ;
    }
    if( lPeriodName.Contains("LHC15m") ) {
        fEstV0M -> SetUseAnchor        ( kTRUE   ) ;
        fEstV0M -> SetAnchorPoint      ( 115.0    ) ;
        fEstV0M -> SetAnchorPercentile ( 87.5    ) ;
    }

    AliMultEstimator *fEstV0A = new AliMultEstimator("V0A", "", "(fAmplitude_V0A)");
    AliMultEstimator *fEstV0C = new AliMultEstimator("V0C", "", "(fAmplitude_V0C)");

    AliMultEstimator *fEstOnlineV0M = new AliMultEstimator("OnlineV0M", "", "(fAmplitude_OnlineV0A)+(fAmplitude_OnlineV0C)");
    AliMultEstimator *fEstOnlineV0A = new AliMultEstimator("OnlineV0A", "", "(fAmplitude_OnlineV0A)");
    AliMultEstimator *fEstOnlineV0C = new AliMultEstimator("OnlineV0C", "", "(fAmplitude_OnlineV0C)");

    AliMultEstimator *fEstADM = new AliMultEstimator("ADM", "", "(fMultiplicity_ADA)+(fMultiplicity_ADC)");
    AliMultEstimator *fEstADA = new AliMultEstimator("ADA", "", "(fMultiplicity_ADA)");
    AliMultEstimator *fEstADC = new AliMultEstimator("ADC", "", "(fMultiplicity_ADC)");

    //Integer estimators
    AliMultEstimator *fEstnSPDClusters = new AliMultEstimator("SPDClusters", "", "(fnSPDClusters)");
    fEstnSPDClusters->SetIsInteger(kTRUE);
    AliMultEstimator *fEstnSPDTracklets = new AliMultEstimator("SPDTracklets", "", "(fnTracklets)");
    fEstnSPDTracklets->SetIsInteger(kTRUE);
    AliMultEstimator *fEstRefMultEta5 = new AliMultEstimator("RefMult05", "", "(fRefMultEta5)");
    fEstRefMultEta5->SetIsInteger(kTRUE);
    AliMultEstimator *fEstRefMultEta8 = new AliMultEstimator("RefMult08", "", "(fRefMultEta8)");
    fEstRefMultEta8->SetIsInteger(kTRUE);

    //Changes in new version: create AliMultSelection here
    AliMultSelection *lMultSel = new AliMultSelection();
    lCalib->SetMultSelection(lMultSel);

    //Univeral: V0
    lCalib->GetMultSelection() -> AddEstimator( fEstV0M );
    lCalib->GetMultSelection() -> AddEstimator( fEstV0A );
    lCalib->GetMultSelection() -> AddEstimator( fEstV0C );

    //Testing!
    if( lPeriodName.Contains("LHC10h") ){
        AliMultEstimator *fEstV0MNonAnchored = new AliMultEstimator("V0MNonAnchored", "", "(fAmplitude_V0A)+(fAmplitude_V0C)");
        lCalib->GetMultSelection() -> AddEstimator( fEstV0MNonAnchored );
    }

    //Anchoring test

    //Only do this in run 2, AD didn't exist in Run 1
    //Will also save space in the OADB for old datasets!
    if( lPeriodName.Contains("LHC15") ){
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0M );
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0A );
        lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0C );
        lCalib->GetMultSelection() -> AddEstimator( fEstADM );
        lCalib->GetMultSelection() -> AddEstimator( fEstADA );
        lCalib->GetMultSelection() -> AddEstimator( fEstADC );
    }

    //Universal: Tracking, etc
    lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClusters  );
    lCalib->GetMultSelection() -> AddEstimator( fEstnSPDTracklets );
    lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta5 );
    lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta8 );

    //============================================================
    // --- Definition of Input/Output ---
    //============================================================

    if( !lPeriodName.Contains("test") ){
        //Per Period calibration: standard locations...
        lCalib -> SetInputFile  ( Form("~/Dropbox/MultSelCalib/%s/Merged%s.root",lPeriodName.Data(), lPeriodName.Data() ) );
        lCalib -> SetBufferFile ( Form("~/work/fast/buffer-%s.root", lPeriodName.Data() ) );
        lCalib -> SetOutputFile ( Form("OADB-%s.root", lPeriodName.Data() ) );
        lCalib -> Calibrate     ();
    }else{
        lCalib -> SetInputFile  ( "../MultSelCalib/LHC10h/files/AnalysisResults_137161.root");
        lCalib -> SetBufferFile ( "buffer-test.root" );
        lCalib -> SetOutputFile ( "OADB-testing.root" );
        lCalib -> Calibrate     ();
    }
}
<|endoftext|>


<commit_before>#include "Utils/Logging.hpp"

#include "Settings.hpp"

using Dissent::Utils::Logging;

namespace Dissent {
namespace Applications {
  Settings::Settings(const QString &file, bool actions) :
    _use_file(true),
    _settings(new QSettings(file, QSettings::IniFormat))
  {
    Init(actions);
  }

  Settings::Settings() :
    _use_file(false),
    _settings(new QSettings())
  {
    Init();
  }

  Settings::Settings(const QSharedPointer<QSettings> &settings,
      bool file, bool actions) :
    _use_file(file),
    _settings(settings)
  {
    Init(actions);
  }

  void Settings::Init(bool actions)
  {
    if(_settings->value(Param<Params::Help>(), false).toBool()) {
      Help = true;
      return;
    }
    Help = false;

    Console = false;
    EntryTunnel = false;
    ExitTunnel = false;
    LeaderId = Id::Zero();
    LocalId = Id::Zero();
    LocalNodeCount = 1;
    SessionType = "null";
    WebServer = false;

    QVariant peers = _settings->value(Param<Params::RemotePeers>());
    ParseUrlList("RemotePeer", peers, RemotePeers);

    QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());
    ParseUrlList("EndPoint", endpoints, LocalEndPoints);

    DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();

    if(_settings->contains(Param<Params::LocalNodeCount>())) {
      LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();
    }

    Console = _settings->value(Param<Params::Console>()).toBool();
    WebServer = _settings->value(Param<Params::WebServer>()).toBool();
    EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();
    ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();
    Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();

    WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http");
    EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp");

    if(_settings->contains(Param<Params::SessionType>())) {
      SessionType = _settings->value(Param<Params::SessionType>()).toString();
    }

    if(_settings->contains(Param<Params::SubgroupPolicy>())) {
      QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();
      SubgroupPolicy = Group::StringToPolicyType(ptype);
    }

    if(_settings->contains(Param<Params::Log>())) {
      Log = _settings->value(Param<Params::Log>()).toString();
      QString lower = Log.toLower();

      if(actions) {
        if(lower == "stderr") {
          Logging::UseStderr();
        } else if(lower == "stdout") {
          Logging::UseStdout();
        } else if(Log.isEmpty()) {
          Logging::Disable();
        } else {
          Logging::UseFile(Log);
        }
      }
    }

    if(_settings->contains(Param<Params::LocalId>())) {
      LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());
    }

    if(_settings->contains(Param<Params::LeaderId>())) {
      LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());
    }

    if(_settings->contains(Param<Params::SuperPeer>())) {
      SuperPeer = _settings->value(Param<Params::SuperPeer>()).toBool();
    }
  }

  bool Settings::IsValid()
  {
    if(_use_file && (_settings->status() != QSettings::NoError)) {
      _reason = "File error";
      return false;
    }

    if(LocalEndPoints.count() == 0) {
      _reason = "No locally defined end points";
      return false;
    }

    if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {
      _reason = "Invalid WebServerUrl: " + WebServerUrl.toString();
      return false;
    }

    if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {
      _reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString();
      return false;
    }

    if(LeaderId == Id::Zero()) {
      _reason = "No leader Id";
      return false;
    }

    if(SubgroupPolicy == -1) {
      _reason = "Invalid subgroup policy";
      return false;
    }

    return true;
  }

  QString Settings::GetError()
  {
    IsValid();
    return _reason;
  }

  void Settings::ParseUrlList(const QString &name, const QVariant &values,
          QList<QUrl> &list)
  {
    if(values.isNull()) {
      return;
    }

    QVariantList varlist = values.toList();
    if(!varlist.empty()) {
      foreach(QVariant value, varlist) {
        ParseUrl(name, value, list);
      }
    } else {
      ParseUrl(name, values, list);
    }
  }

  inline void Settings::ParseUrl(const QString &name, const QVariant &value,
          QList<QUrl> &list)
  {
    QUrl url(value.toString());
    if(url.isValid()) {
      list << url;
    } else {
      qCritical() << "Invalid " << name << ": " << value.toString();
    }
  }

  QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)
  {
    QUrl url = QUrl(string_rep);
    if(url.toString() != string_rep) {
      return QUrl();
    }

    if(url.scheme() != scheme) {
      return QUrl();
    }
    return url;
  }

  void Settings::Save()
  {
    if(!_use_file) {
      return;
    }

    QStringList peers;
    foreach(QUrl peer, RemotePeers) {
      peers << peer.toString();
    }

    if(!peers.empty()) {
      _settings->setValue(Param<Params::RemotePeers>(), peers);
    }

    QStringList endpoints;
    foreach(QUrl endpoint, LocalEndPoints) {
      endpoints << endpoint.toString();
    }

    if(!endpoints.empty()) {
      _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);
    }

    _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);
    _settings->setValue(Param<Params::WebServer>(), WebServer);
    _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);
    _settings->setValue(Param<Params::Console>(), Console);
    _settings->setValue(Param<Params::DemoMode>(), DemoMode);
    _settings->setValue(Param<Params::Log>(), Log);
    _settings->setValue(Param<Params::Multithreading>(), Multithreading);
    _settings->setValue(Param<Params::LocalId>(), LocalId.ToString());
    _settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());
    _settings->setValue(Param<Params::SubgroupPolicy>(),
        Group::PolicyTypeToString(SubgroupPolicy));
  }

  Settings Settings::CommandLineParse(const QStringList &params, bool actions)
  {
    QSharedPointer<QxtCommandOptions> options = GetOptions();
    options->parse(params);
    QSharedPointer<QSettings> settings;
    bool file = (options->positional().count() > 0);

    if(file) {
      settings = QSharedPointer<QSettings>(
          new QSettings(options->positional()[0], QSettings::IniFormat));
    } else {
      settings = QSharedPointer<QSettings>(new QSettings());
      // Bug in other platforms?? I do not know...
      settings->clear();
      if(params.size() == 1) {
        settings->setValue(Param<Params::Help>(), true);
      }
    }

    QMultiHash<QString, QVariant> kv_params = options->parameters();

    if(kv_params.value(Param<Params::Help>(), false).toBool() && file) {
      file = false;
      settings = QSharedPointer<QSettings>(new QSettings());
    }

    foreach(const QString &key, kv_params.uniqueKeys()) {
      if(options->value(key).type() == QVariant::String &&
          options->value(key).toString().isEmpty())
      {
        settings->setValue(key, true);
      } else {
        settings->setValue(key, options->value(key));
      }
    }

    if(options->count(Param<Params::WebServerUrl>()) == 1) {
      settings->setValue(Param<Params::WebServer>(), true);
    }

    if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {
      settings->setValue(Param<Params::EntryTunnel>(), true);
    }

    return Settings(settings, file, actions);
  }

  QSharedPointer<QxtCommandOptions> Settings::GetOptions()
  {
    QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());

    options->add(Param<Params::Help>(),
        "help (this screen)",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::RemotePeers>(),
        "list of remote peers",
        QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);

    options->add(Param<Params::LocalEndPoints>(),
        "list of local end points",
        QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);

    options->add(Param<Params::LocalNodeCount>(),
        "number of virtual nodes to start",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::DemoMode>(),
        "start in demo mode",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::SessionType>(),
        "the type of session",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::Log>(),
        "logging mechanism: stderr, stdout, or a file path",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::Console>(),
        "enable console",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::WebServerUrl>(),
        "web server url (enables web server)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::EntryTunnelUrl>(),
        "entry tunnel url (enables entry tunnel)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::ExitTunnel>(),
        "enables exit tunnel",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::Multithreading>(),
        "enables multithreading",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::LocalId>(),
        "160-bit base64 local id",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::LeaderId>(),
        "160-bit base64 leader id",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::SubgroupPolicy>(),
        "subgroup policy (defining servers)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::SuperPeer>(),
        "sets this peer as a capable super peer",
        QxtCommandOptions::NoValue);

    return options;
  }
}
}
<commit_msg>[Applications] Made SuperPeer default to false<commit_after>#include "Utils/Logging.hpp"

#include "Settings.hpp"

using Dissent::Utils::Logging;

namespace Dissent {
namespace Applications {
  Settings::Settings(const QString &file, bool actions) :
    _use_file(true),
    _settings(new QSettings(file, QSettings::IniFormat))
  {
    Init(actions);
  }

  Settings::Settings() :
    _use_file(false),
    _settings(new QSettings())
  {
    Init();
  }

  Settings::Settings(const QSharedPointer<QSettings> &settings,
      bool file, bool actions) :
    _use_file(file),
    _settings(settings)
  {
    Init(actions);
  }

  void Settings::Init(bool actions)
  {
    if(_settings->value(Param<Params::Help>(), false).toBool()) {
      Help = true;
      return;
    }
    Help = false;

    Console = false;
    EntryTunnel = false;
    ExitTunnel = false;
    LeaderId = Id::Zero();
    LocalId = Id::Zero();
    LocalNodeCount = 1;
    SessionType = "null";
    WebServer = false;

    QVariant peers = _settings->value(Param<Params::RemotePeers>());
    ParseUrlList("RemotePeer", peers, RemotePeers);

    QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());
    ParseUrlList("EndPoint", endpoints, LocalEndPoints);

    DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();

    if(_settings->contains(Param<Params::LocalNodeCount>())) {
      LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();
    }

    Console = _settings->value(Param<Params::Console>()).toBool();
    WebServer = _settings->value(Param<Params::WebServer>()).toBool();
    EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();
    ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();
    Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();

    WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http");
    EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp");

    if(_settings->contains(Param<Params::SessionType>())) {
      SessionType = _settings->value(Param<Params::SessionType>()).toString();
    }

    if(_settings->contains(Param<Params::SubgroupPolicy>())) {
      QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();
      SubgroupPolicy = Group::StringToPolicyType(ptype);
    }

    if(_settings->contains(Param<Params::Log>())) {
      Log = _settings->value(Param<Params::Log>()).toString();
      QString lower = Log.toLower();

      if(actions) {
        if(lower == "stderr") {
          Logging::UseStderr();
        } else if(lower == "stdout") {
          Logging::UseStdout();
        } else if(Log.isEmpty()) {
          Logging::Disable();
        } else {
          Logging::UseFile(Log);
        }
      }
    }

    if(_settings->contains(Param<Params::LocalId>())) {
      LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());
    }

    if(_settings->contains(Param<Params::LeaderId>())) {
      LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());
    }

    SuperPeer = _settings->value(Param<Params::SuperPeer>(), false).toBool();
  }

  bool Settings::IsValid()
  {
    if(_use_file && (_settings->status() != QSettings::NoError)) {
      _reason = "File error";
      return false;
    }

    if(LocalEndPoints.count() == 0) {
      _reason = "No locally defined end points";
      return false;
    }

    if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {
      _reason = "Invalid WebServerUrl: " + WebServerUrl.toString();
      return false;
    }

    if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {
      _reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString();
      return false;
    }

    if(LeaderId == Id::Zero()) {
      _reason = "No leader Id";
      return false;
    }

    if(SubgroupPolicy == -1) {
      _reason = "Invalid subgroup policy";
      return false;
    }

    return true;
  }

  QString Settings::GetError()
  {
    IsValid();
    return _reason;
  }

  void Settings::ParseUrlList(const QString &name, const QVariant &values,
          QList<QUrl> &list)
  {
    if(values.isNull()) {
      return;
    }

    QVariantList varlist = values.toList();
    if(!varlist.empty()) {
      foreach(QVariant value, varlist) {
        ParseUrl(name, value, list);
      }
    } else {
      ParseUrl(name, values, list);
    }
  }

  inline void Settings::ParseUrl(const QString &name, const QVariant &value,
          QList<QUrl> &list)
  {
    QUrl url(value.toString());
    if(url.isValid()) {
      list << url;
    } else {
      qCritical() << "Invalid " << name << ": " << value.toString();
    }
  }

  QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)
  {
    QUrl url = QUrl(string_rep);
    if(url.toString() != string_rep) {
      return QUrl();
    }

    if(url.scheme() != scheme) {
      return QUrl();
    }
    return url;
  }

  void Settings::Save()
  {
    if(!_use_file) {
      return;
    }

    QStringList peers;
    foreach(QUrl peer, RemotePeers) {
      peers << peer.toString();
    }

    if(!peers.empty()) {
      _settings->setValue(Param<Params::RemotePeers>(), peers);
    }

    QStringList endpoints;
    foreach(QUrl endpoint, LocalEndPoints) {
      endpoints << endpoint.toString();
    }

    if(!endpoints.empty()) {
      _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);
    }

    _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);
    _settings->setValue(Param<Params::WebServer>(), WebServer);
    _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);
    _settings->setValue(Param<Params::Console>(), Console);
    _settings->setValue(Param<Params::DemoMode>(), DemoMode);
    _settings->setValue(Param<Params::Log>(), Log);
    _settings->setValue(Param<Params::Multithreading>(), Multithreading);
    _settings->setValue(Param<Params::LocalId>(), LocalId.ToString());
    _settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());
    _settings->setValue(Param<Params::SubgroupPolicy>(),
        Group::PolicyTypeToString(SubgroupPolicy));
  }

  Settings Settings::CommandLineParse(const QStringList &params, bool actions)
  {
    QSharedPointer<QxtCommandOptions> options = GetOptions();
    options->parse(params);
    QSharedPointer<QSettings> settings;
    bool file = (options->positional().count() > 0);

    if(file) {
      settings = QSharedPointer<QSettings>(
          new QSettings(options->positional()[0], QSettings::IniFormat));
    } else {
      settings = QSharedPointer<QSettings>(new QSettings());
      // Bug in other platforms?? I do not know...
      settings->clear();
      if(params.size() == 1) {
        settings->setValue(Param<Params::Help>(), true);
      }
    }

    QMultiHash<QString, QVariant> kv_params = options->parameters();

    if(kv_params.value(Param<Params::Help>(), false).toBool() && file) {
      file = false;
      settings = QSharedPointer<QSettings>(new QSettings());
    }

    foreach(const QString &key, kv_params.uniqueKeys()) {
      if(options->value(key).type() == QVariant::String &&
          options->value(key).toString().isEmpty())
      {
        settings->setValue(key, true);
      } else {
        settings->setValue(key, options->value(key));
      }
    }

    if(options->count(Param<Params::WebServerUrl>()) == 1) {
      settings->setValue(Param<Params::WebServer>(), true);
    }

    if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {
      settings->setValue(Param<Params::EntryTunnel>(), true);
    }

    return Settings(settings, file, actions);
  }

  QSharedPointer<QxtCommandOptions> Settings::GetOptions()
  {
    QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());

    options->add(Param<Params::Help>(),
        "help (this screen)",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::RemotePeers>(),
        "list of remote peers",
        QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);

    options->add(Param<Params::LocalEndPoints>(),
        "list of local end points",
        QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);

    options->add(Param<Params::LocalNodeCount>(),
        "number of virtual nodes to start",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::DemoMode>(),
        "start in demo mode",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::SessionType>(),
        "the type of session",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::Log>(),
        "logging mechanism: stderr, stdout, or a file path",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::Console>(),
        "enable console",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::WebServerUrl>(),
        "web server url (enables web server)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::EntryTunnelUrl>(),
        "entry tunnel url (enables entry tunnel)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::ExitTunnel>(),
        "enables exit tunnel",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::Multithreading>(),
        "enables multithreading",
        QxtCommandOptions::NoValue);

    options->add(Param<Params::LocalId>(),
        "160-bit base64 local id",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::LeaderId>(),
        "160-bit base64 leader id",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::SubgroupPolicy>(),
        "subgroup policy (defining servers)",
        QxtCommandOptions::ValueRequired);

    options->add(Param<Params::SuperPeer>(),
        "sets this peer as a capable super peer",
        QxtCommandOptions::NoValue);

    return options;
  }
}
}
<|endoftext|>


<commit_before>#include "CardiacMechanicsPressureBC.h"
#include "Function.h"
#include "MooseError.h"

template<>
InputParameters validParams<CardiacMechanicsPressureBC>()
{
  InputParameters params = validParams<IntegratedBC>();
  params.addRequiredParam<int>("component", "The component for the pressure, i.e. the index of the displacement component this BC works on.");
  params.addParam<Real>("value", 0.0, "The factor to use in computing the pressure");
  params.addParam<FunctionName>("function", "The function that describes the pressure");
  params.addParam<bool>("use_current_configuration", false, "If set to true, the pressure is prescribed in the current (deformed) configuration, otherwise in the reference configuration.");
  params.set<bool>("use_displaced_mesh") = false;
  return params;
}

CardiacMechanicsPressureBC::CardiacMechanicsPressureBC(const std::string & name, InputParameters parameters)
  :IntegratedBC(name, parameters),
   _component(getParam<int>("component")),
   _value(getParam<Real>("value")),
   _function( isParamValid("function") ? &getFunction("function") : NULL ),
   _current_config(getParam<bool>("use_current_configuration")),
   _J(getMaterialProperty<Real>("det_displacement_gradient")),
   _Finv(getMaterialProperty<RealTensorValue>("inv_displacement_gradient"))
{

  if (_component < 0 || _component > 2)
    mooseError( "CardiacMechanicsPressureBC: Invalid component given for " << name << ": " << _component << "." << std::endl);
}

Real
CardiacMechanicsPressureBC::computeQpResidual()
{
  Real pressure(_value);

  if (_function)
    pressure *= _function->value(_t, _q_point[_qp]);

  if (_current_config)
    return - _test[_i][_qp] * pressure * _J[_qp] * (_normals[_qp](0)*_Finv[_qp](0,_component)
                                                   +_normals[_qp](1)*_Finv[_qp](1,_component)
                                                   +_normals[_qp](2)*_Finv[_qp](2,_component));
  else
    return - _test[_i][_qp] * pressure * _normals[_qp](_component);
}
<commit_msg>swapped sign convention for pressure BC<commit_after>#include "CardiacMechanicsPressureBC.h"
#include "Function.h"
#include "MooseError.h"

template<>
InputParameters validParams<CardiacMechanicsPressureBC>()
{
  InputParameters params = validParams<IntegratedBC>();
  params.addRequiredParam<int>("component", "The component for the pressure, i.e. the index of the displacement component this BC works on.");
  params.addParam<Real>("value", 0.0, "The factor to use in computing the pressure");
  params.addParam<FunctionName>("function", "The function that describes the pressure");
  params.addParam<bool>("use_current_configuration", false, "If set to true, the pressure is prescribed in the current (deformed) configuration, otherwise in the reference configuration.");
  params.set<bool>("use_displaced_mesh") = false;
  return params;
}

CardiacMechanicsPressureBC::CardiacMechanicsPressureBC(const std::string & name, InputParameters parameters)
  :IntegratedBC(name, parameters),
   _component(getParam<int>("component")),
   _value(getParam<Real>("value")),
   _function( isParamValid("function") ? &getFunction("function") : NULL ),
   _current_config(getParam<bool>("use_current_configuration")),
   _J(getMaterialProperty<Real>("det_displacement_gradient")),
   _Finv(getMaterialProperty<RealTensorValue>("inv_displacement_gradient"))
{

  if (_component < 0 || _component > 2)
    mooseError( "CardiacMechanicsPressureBC: Invalid component given for " << name << ": " << _component << "." << std::endl);
}

Real
CardiacMechanicsPressureBC::computeQpResidual()
{
  Real pressure(_value);

  if (_function)
    pressure *= _function->value(_t, _q_point[_qp]);

  if (_current_config)
    return _test[_i][_qp] * pressure * _J[_qp] * (_normals[_qp](0)*_Finv[_qp](0,_component)
                                                 +_normals[_qp](1)*_Finv[_qp](1,_component)
                                                 +_normals[_qp](2)*_Finv[_qp](2,_component));
  else
    return _test[_i][_qp] * pressure * _normals[_qp](_component);
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <sstream>
#include <string>

#include <stdio.h>
#include <string.h>
#include "config.h"

// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION	"0025"
#endif

// version numbers - also update:
//  ChangeLog
//  README
//  package/win32/nsis/*.nsi
//  package/win32/*.nsi
//  src/platform/MacOSX/BZFlag-Info.plist
//  tools/TextTool-W32/TextTool.rc
//  win32/VC6/installer.dsp
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION	1
#endif

#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION	11
#endif

#ifndef BZ_REV
#define BZ_REV			41
#endif

// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE		"STABLE"
#endif

const char *bzfcopyright = "Copyright (c) 1993 - 2005 Tim Riker";

#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};

int getBuildDate()
{
  int year = 1900, month = 0, day = 0;
  char monthStr[512];
  sscanf(buildDate, "%s %d %d", monthStr, &day, &year);

  // we want it not as a name but a number
  if (strcmp(monthStr, "Jan") == 0)
    month = 1;
  else if (strcmp(monthStr, "Feb") == 0)
    month = 2;
  else if (strcmp(monthStr, "Mar") == 0)
    month = 3;
  else if (strcmp(monthStr, "Apr") == 0)
    month = 4;
  else if (strcmp(monthStr, "May") == 0)
    month = 5;
  else if (strcmp(monthStr, "Jun") == 0)
    month = 6;
  else if (strcmp(monthStr, "Jul") == 0)
    month = 7;
  else if (strcmp(monthStr, "Aug") == 0)
    month = 8;
  else if (strcmp(monthStr, "Sep") == 0)
    month = 9;
  else if (strcmp(monthStr, "Oct") == 0)
    month = 10;
  else if (strcmp(monthStr, "Nov") == 0)
    month = 11;
  else if (strcmp(monthStr, "Dec") == 0)
    month = 12;

  return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"

const char*		getProtocolVersion()
{
  static std::string protVersion = BZ_PROTO_VERSION;
  return protVersion.c_str();
}

const char*		getServerVersion()
{
  static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
  return serverVersion.c_str();
}

const char*		getMajorMinorVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getMajorMinorRevVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getAppVersion()
{
  static std::string	appVersion = "";
  if (!appVersion.size()){
    std::ostringstream	appVersionStream;
    // TODO add current platform, release, cpu, etc
    appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
	<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
    appVersionStream << "-SDL";
#endif
    appVersion = appVersionStream.str();
  }
  return appVersion.c_str();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>sneak in a comment change<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <sstream>
#include <string>

#include <stdio.h>
#include <string.h>
#include "config.h"

// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION	"0025"
#endif

// version numbers - also update:
//  ChangeLog
//  README
//  package/win32/nsis/*.nsi
//  package/win32/*.nsi
//  tools/TextTool-W32/TextTool.rc
//  win32/VC6/installer.dsp
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION	1
#endif

#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION	11
#endif

#ifndef BZ_REV
#define BZ_REV			41
#endif

// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE		"STABLE"
#endif

const char *bzfcopyright = "Copyright (c) 1993 - 2005 Tim Riker";

#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};

int getBuildDate()
{
  int year = 1900, month = 0, day = 0;
  char monthStr[512];
  sscanf(buildDate, "%s %d %d", monthStr, &day, &year);

  // we want it not as a name but a number
  if (strcmp(monthStr, "Jan") == 0)
    month = 1;
  else if (strcmp(monthStr, "Feb") == 0)
    month = 2;
  else if (strcmp(monthStr, "Mar") == 0)
    month = 3;
  else if (strcmp(monthStr, "Apr") == 0)
    month = 4;
  else if (strcmp(monthStr, "May") == 0)
    month = 5;
  else if (strcmp(monthStr, "Jun") == 0)
    month = 6;
  else if (strcmp(monthStr, "Jul") == 0)
    month = 7;
  else if (strcmp(monthStr, "Aug") == 0)
    month = 8;
  else if (strcmp(monthStr, "Sep") == 0)
    month = 9;
  else if (strcmp(monthStr, "Oct") == 0)
    month = 10;
  else if (strcmp(monthStr, "Nov") == 0)
    month = 11;
  else if (strcmp(monthStr, "Dec") == 0)
    month = 12;

  return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"

const char*		getProtocolVersion()
{
  static std::string protVersion = BZ_PROTO_VERSION;
  return protVersion.c_str();
}

const char*		getServerVersion()
{
  static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
  return serverVersion.c_str();
}

const char*		getMajorMinorVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getMajorMinorRevVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getAppVersion()
{
  static std::string	appVersion = "";
  if (!appVersion.size()){
    std::ostringstream	appVersionStream;
    // TODO add current platform, release, cpu, etc
    appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
	<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
    appVersionStream << "-SDL";
#endif
    appVersion = appVersionStream.str();
  }
  return appVersion.c_str();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include "MultipleExpressions.h"

MultipleExpressions::MultipleExpressions(string s){
    this->type = "multiple";
    this->expressions = s;
    this->exp = s;
    this->vectorExpressions = this->parseBySpaces(s);
    if (this->vectorExpressions.size() > 1) {
        if (this->vectorExpressions.at(1) == "+" || this->vectorExpressions.at(1) == "-") {
            this->meType = "as";
        }else if(this->vectorExpressions.at(1) == "*" || this->vectorExpressions.at(1) == "/"){
            this->meType = "md";
        }else{
            throw runtime_error("Error: Multiple Expression does not have a type");
        }
    }
}
MultipleExpressions::~MultipleExpressions(){
    delete this;
}
string MultipleExpressions:: getExpressions()
{
	string s = this->toString();
	return s;
}
Expression* MultipleExpressions::add(Expression* a)
{
    Solver *s = new Solver();
    size_t aSize = this->vectorExpressions.size();
    bool changed = false;
    Expression *result;

    if (a->type == "multiple") {
        MultipleExpressions *b = (MultipleExpressions *)a;
        if (b->vectorExpressions.size() == 3 && this->vectorExpressions.size() == 3
            && b->vectorExpressions.at(1) == "*" && this->vectorExpressions.at(1) == "*") {

            Expression *eB0 = s->bindToExpressionType(b->vectorExpressions.at(0));
            Expression *eThis0 = s->bindToExpressionType(this->vectorExpressions.at(0));
            Expression *eB1 = s->bindToExpressionType(b->vectorExpressions.at(2));
            Expression *eThis1 = s->bindToExpressionType(this->vectorExpressions.at(2));
            if (eB0->type == eThis0->type || eB0->canAdd(eThis0)) {
                if (eB0->toString() == eThis0->toString()) {
                    s = new Solver(eB0->toString() + " * " + eB1->add(eThis1)->toString());
                    result = s->bindToExpressionType(s->solve(false));
                    vectorExpressions = this->parseBySpaces(result->toString());
                    return this;
                }else{
                    s = new Solver(eB1->toString() + " * " + eB0->add(eThis0)->toString());
                    result = s->bindToExpressionType(s->solve(false));
                    vectorExpressions = this->parseBySpaces(result->toString());
                    return this;

                }
            }
        }
    }

    for (int i = 0; i < aSize; i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if ((i == aSize-1 && vectorExpressions.at(i-1) != "*" && vectorExpressions.at(i-1) != "/")) {
                changed = true;
                if (vectorExpressions.at(i-1) == "-") {
                    result = a->subtract(operand1);
                    vectorExpressions.at(i-1) = "+";
                }else{
                    result = operand1->add(a);
                }
                vectorExpressions.at(i) = result->toString();
            }
            else if (operand1->canAdd(a) && vectorExpressions.at(i) != "*" && vectorExpressions.at(i) != "/") {
                changed = true;
                Expression *result = operand1->add(a);
                vectorExpressions.at(i) = result->toString();
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("+");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::subtract(Expression* a)
{
    Solver *s = new Solver();
    size_t aSize = this->vectorExpressions.size();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if ((i == aSize-1 && vectorExpressions.at(i-1) != "*" && vectorExpressions.at(i-1) != "/")) {
                changed = true;
                Expression *result = operand1->subtract(a);
                vectorExpressions.at(i) = result->toString();
            }
            else if (operand1->canSubtract(a) && vectorExpressions.at(i) != "*" && vectorExpressions.at(i) != "/") {
                changed = true;
                Expression *result = operand1->subtract(a);
                vectorExpressions.at(i) = result->toString();
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("-");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::multiply(Expression* a)
{
    Solver *s = new Solver();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if (operand1->canMultiply(a)) {
                changed = true;
                Expression *result = operand1->multiply(a);
                if (result->type == "integer") {
                    Integer *t = (Integer *)result;
                    if (t->getValue() == 1) {
                        vectorExpressions.at(i) = result->toString();
                        vectorExpressions.erase(vectorExpressions.begin() + i-1,vectorExpressions.begin() + i+1);
                    }
                }else{
                    vectorExpressions.at(i) = result->toString();
                }
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("*");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::divide(Expression* a)
{
    Solver *s = new Solver();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if (operand1->canDivide(a)) {
                if (vectorExpressions.at(i-1) == "/") {
                    Rational *t = new Rational(new Integer(1),a);
                    this->multiply(t);
                }
                changed = true;
                Expression *result = operand1->divide(a);
                if (result->type == "integer") {
                    Integer *t = (Integer *)result;
                    if (t->getValue() == 1) {
                        vectorExpressions.at(i) = result->toString();
                        vectorExpressions.erase(vectorExpressions.begin() + i-1,vectorExpressions.begin() + i+1);
                    }
                }else if(result->type == "rational"){
                    Rational *t = (Rational *)result;
                    vectorExpressions.at(i) = t->geteNumerator()->toString();
                    Expression *n = s->bindToExpressionType(vectorExpressions.at(i+2));
                    if (t->geteDenominator()->canMultiply(n)) {
                        vectorExpressions.at(i+2) = t->geteDenominator()->multiply(n)->toString();
                    }else{
                        vectorExpressions.at(i) = result->toString();
                    }
                }else{
                    vectorExpressions.at(i) = result->toString();
                }
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("/");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}
vector<string> MultipleExpressions::parseBySpaces(string expression){
    int count = 0;
    string temp = "";
    vector<string> expressions = *new vector<string>();
    for(int i = 0; i < expression.size(); i ++){       //creates an array of expressions and operations
        if (expression.at(i) == 'l' && expression.at(i+1) == 'o' && expression.at(i+2) == 'g') {
            temp = "";
            for (int j = i; j < expression.size(); j++) {
                temp.push_back(expression.at(j));
                if (expression.at(j) == ')') {
                    i = j+1;
                    expressions.push_back(temp);
                    count = j + 2;
                    break;
                }
            }
        }
        else if(expression.at(i) == ' '){
            temp = "";
            for (int j = count; j < i; j++) {
                temp.push_back(expression.at(j));
            }
            expressions.push_back(temp);
            count = i+1;

        }else if(i == expression.size()-1){
            temp = "";
            for (int j = count; j <= i; j++) {
                temp.push_back(expression.at(j));
            }
            expressions.push_back(temp);
            count = i+1;
        }
    }
    return expressions;
}
vector<string> MultipleExpressions::getVectorExpressions(){
    return this->vectorExpressions;
}

string MultipleExpressions:: toString(){
    this->expressions = "";
    for (int i = 0; i < vectorExpressions.size(); i++) {
        this->expressions += vectorExpressions.at(i);
        if (i != vectorExpressions.size()-1) {
            this->expressions += " ";
        }
    }
    stringstream s;
	s<<this->expressions;
	return s.str();
}

ostream& MultipleExpressions::print(std::ostream& output) const{
    MultipleExpressions *a = (MultipleExpressions *)this;
    output << a->toString();
    return output;
}

bool MultipleExpressions::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type && this->type != "logarithm") {
        if (this->type == "nthRoot") {
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }
    else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool MultipleExpressions::canSubtract(Expression* b){
    if (this->type == b->type) {
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool MultipleExpressions::canMultiply(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;

}
bool MultipleExpressions::canDivide(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer"){
        if( b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}

<commit_msg>changes<commit_after>#include "MultipleExpressions.h"

MultipleExpressions::MultipleExpressions(string s){
    this->type = "multiple";
    this->expressions = s;
    this->exp = s;
    this->vectorExpressions = this->parseBySpaces(s);
    if (this->vectorExpressions.size() > 1) {
        if (this->vectorExpressions.at(1) == "+" || this->vectorExpressions.at(1) == "-") {
            this->meType = "as";
        }else if(this->vectorExpressions.at(1) == "*" || this->vectorExpressions.at(1) == "/"){
            this->meType = "md";
        }else{
            throw runtime_error("Error: Multiple Expression does not have a type");
        }
    }
}
MultipleExpressions::~MultipleExpressions(){
    delete this;
}
string MultipleExpressions:: getExpressions()
{
	string s = this->toString();
	return s;
}
Expression* MultipleExpressions::add(Expression* a)
{
    Solver *s = new Solver();
    size_t aSize = this->vectorExpressions.size();
    bool changed = false;
    Expression *result;

    if (a->type == "multiple") {
        MultipleExpressions *b = (MultipleExpressions *)a;
        if (b->vectorExpressions.size() == 3 && this->vectorExpressions.size() == 3
            && b->vectorExpressions.at(1) == "*" && this->vectorExpressions.at(1) == "*") {

            Expression *eB0 = s->bindToExpressionType(b->vectorExpressions.at(0));
            Expression *eThis0 = s->bindToExpressionType(this->vectorExpressions.at(0));
            Expression *eB1 = s->bindToExpressionType(b->vectorExpressions.at(2));
            Expression *eThis1 = s->bindToExpressionType(this->vectorExpressions.at(2));
            if (eB0->type == eThis0->type || eB0->canAdd(eThis0)) {
                if (eB0->toString() == eThis0->toString()) {
                    s = new Solver(eB0->toString() + " * " + eB1->add(eThis1)->toString());
                    result = s->bindToExpressionType(s->solve(false));
                    vectorExpressions = this->parseBySpaces(result->toString());
                    return this;
                }else{
                    s = new Solver(eB1->toString() + " * " + eB0->add(eThis0)->toString());
                    result = s->bindToExpressionType(s->solve(false));
                    vectorExpressions = this->parseBySpaces(result->toString());
                    return this;

                }
            }
        }
    }

    for (int i = 0; i < aSize; i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if ((i == aSize-1 && vectorExpressions.at(i-1) != "*" && vectorExpressions.at(i-1) != "/")) {
                changed = true;
                if (vectorExpressions.at(i-1) == "-") {
                    result = a->subtract(operand1);
                    vectorExpressions.at(i-1) = "+";
                }else{
                    result = operand1->add(a);
                }
                vectorExpressions.at(i) = result->toString();
            }
            else if (operand1->canAdd(a) && vectorExpressions.at(i) != "*" && vectorExpressions.at(i) != "/") {
                changed = true;
                Expression *result = operand1->add(a);
                vectorExpressions.at(i) = result->toString();
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("+");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::subtract(Expression* a)
{
    Solver *s = new Solver();
    size_t aSize = this->vectorExpressions.size();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if ((i == aSize-1 && vectorExpressions.at(i-1) != "*" && vectorExpressions.at(i-1) != "/")) {
                changed = true;
                Expression *result = operand1->subtract(a);
                vectorExpressions.at(i) = result->toString();
            }
            else if (operand1->canSubtract(a) && vectorExpressions.at(i) != "*" && vectorExpressions.at(i) != "/") {
                changed = true;
                Expression *result = operand1->subtract(a);
                vectorExpressions.at(i) = result->toString();
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("-");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::multiply(Expression* a)
{
    Solver *s = new Solver();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if (operand1->canMultiply(a)) {
                changed = true;
                Expression *result = operand1->multiply(a);
                if (result->type == "integer") {
                    Integer *t = (Integer *)result;
                    if (t->getValue() == 1) {
                        vectorExpressions.at(i) = result->toString();
                        vectorExpressions.erase(vectorExpressions.begin() + i-1,vectorExpressions.begin() + i+1);
                    }
                }else{
                    vectorExpressions.at(i) = result->toString();
                }
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("*");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}

Expression* MultipleExpressions::divide(Expression* a)
{
    Solver *s = new Solver();
    bool changed = false;
    for (int i = 0; i < this->vectorExpressions.size(); i++) {
        if ((i % 2 == 0  || i == 0 ) && i != 1) {   //odd numbers only
            Expression *operand1 = s->bindToExpressionType(this->vectorExpressions.at(i));
            if (operand1->canDivide(a)) {
                if (i >1 && vectorExpressions.at(i-1) == "/") {
                    Rational *t = new Rational(new Integer(1),a);
                    this->multiply(t);
                }
                changed = true;
                Expression *result = operand1->divide(a);
                if (result->type == "integer") {
                    Integer *t = (Integer *)result;
                    if (t->getValue() == 1) {
                        vectorExpressions.at(i) = result->toString();
                        vectorExpressions.erase(vectorExpressions.begin() + i-1,vectorExpressions.begin() + i+1);
                    }
                }else if(result->type == "rational"){
                    Rational *t = (Rational *)result;
                    vectorExpressions.at(i) = t->geteNumerator()->toString();
                    Expression *n;
                    size_t j = (size_t)i+2;
                    if(vectorExpressions.size() >= j){
                        s->bindToExpressionType(vectorExpressions.at(i+2));
                    }else{
                        s->bindToExpressionType(vectorExpressions.at(i-2));
                    }
                    if (t->geteDenominator()->canMultiply(n)) {
                        vectorExpressions.at(i+2) = t->geteDenominator()->multiply(n)->toString();
                    }else{
                        vectorExpressions.at(i) = result->toString();
                    }
                }else{
                    vectorExpressions.at(i) = result->toString();
                }
            }
        }
    }
    if (!changed) {
        this->vectorExpressions.push_back("/");
        this->vectorExpressions.push_back(a->toString());
    }
    return this;
}
vector<string> MultipleExpressions::parseBySpaces(string expression){
    int count = 0;
    string temp = "";
    vector<string> expressions = *new vector<string>();
    for(int i = 0; i < expression.size(); i ++){       //creates an array of expressions and operations
        if (expression.at(i) == 'l' && expression.at(i+1) == 'o' && expression.at(i+2) == 'g') {
            temp = "";
            for (int j = i; j < expression.size(); j++) {
                temp.push_back(expression.at(j));
                if (expression.at(j) == ')') {
                    i = j+1;
                    expressions.push_back(temp);
                    count = j + 2;
                    break;
                }
            }
        }
        else if(expression.at(i) == ' '){
            temp = "";
            for (int j = count; j < i; j++) {
                temp.push_back(expression.at(j));
            }
            expressions.push_back(temp);
            count = i+1;

        }else if(i == expression.size()-1){
            temp = "";
            for (int j = count; j <= i; j++) {
                temp.push_back(expression.at(j));
            }
            expressions.push_back(temp);
            count = i+1;
        }
    }
    return expressions;
}
vector<string> MultipleExpressions::getVectorExpressions(){
    return this->vectorExpressions;
}

string MultipleExpressions:: toString(){
    this->expressions = "";
    for (int i = 0; i < vectorExpressions.size(); i++) {
        this->expressions += vectorExpressions.at(i);
        if (i != vectorExpressions.size()-1) {
            this->expressions += " ";
        }
    }
    stringstream s;
	s<<this->expressions;
	return s.str();
}

ostream& MultipleExpressions::print(std::ostream& output) const{
    MultipleExpressions *a = (MultipleExpressions *)this;
    output << a->toString();
    return output;
}

bool MultipleExpressions::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type && this->type != "logarithm") {
        if (this->type == "nthRoot") {
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }
    else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool MultipleExpressions::canSubtract(Expression* b){
    if (this->type == b->type) {
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool MultipleExpressions::canMultiply(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;

}
bool MultipleExpressions::canDivide(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer"){
        if( b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((this->meType == "as" && m->meType == "as") || (this->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}

<|endoftext|>