<commit_before>/*
 * Copyright (c) 2015 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE BundleProcessor.cpp
 * AUTHOR Blackcatn13
 * DATE Dec 17, 2015
 * VERSION 1
 *
 */

#include "Node/BundleProcessor/BundleProcessor.h"
#include <memory>
#include <string>
#include <vector>
#include "Node/BundleQueue/BundleQueue.h"
#include "Node/Neighbour/NeighbourTable.h"
#include "Node/Config.h"
#include "Node/BundleQueue/BundleContainer.h"
#include "Bundle/Bundle.h"

BundleProcessor::BundleProcessor(
    Config config, std::shared_ptr<BundleQueue> bundleQueue,
    std::shared_ptr<NeighbourTable> neighbourTable
    /*, std::shared_ptr<ListeningAppsTable> listeningAppsTable*/)
    : m_config(config),
      m_bundleQueue(bundleQueue),
      m_neighbourTable(neighbourTable) {
}

BundleProcessor::~BundleProcessor() {
}

void BundleProcessor::processBundles() {
}

void BundleProcessor::receiveBundles() {
}

void dispatch(std::shared_ptr<Bundle> bundle,
              std::vector<std::string> destinations) {
}

void forward(std::shared_ptr<Bundle> bundle, std::vector<std::string> nextHop) {
}

void discard(std::shared_ptr<Bundle> bundle) {
}

void restore(std::shared_ptr<Bundle> bundle) {
}
<commit_msg>Implements constructor and processBundles.<commit_after>/*
 * Copyright (c) 2015 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE BundleProcessor.cpp
 * AUTHOR Blackcatn13
 * DATE Dec 17, 2015
 * VERSION 1
 *
 */

#include "Node/BundleProcessor/BundleProcessor.h"
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include "Node/BundleQueue/BundleQueue.h"
#include "Node/Neighbour/NeighbourTable.h"
#include "Node/Config.h"
#include "Node/BundleQueue/BundleContainer.h"
#include "Bundle/Bundle.h"
#include "Utils/globals.h"

BundleProcessor::BundleProcessor(
    Config config, std::shared_ptr<BundleQueue> bundleQueue,
    std::shared_ptr<NeighbourTable> neighbourTable
    /*, std::shared_ptr<ListeningAppsTable> listeningAppsTable*/)
    : m_config(config),
      m_bundleQueue(bundleQueue),
      m_neighbourTable(neighbourTable) {
  std::thread t = std::thread(&BundleProcessor::processBundles, this);
  t.detach();
  t = std::thread(&BundleProcessor::receiveBundles, this);
  t.detach();
}

BundleProcessor::~BundleProcessor() {
}

void BundleProcessor::processBundles() {
  while (!g_stop.load()) {
    try {
      std::shared_ptr<BundleContainer> bc = m_bundleQueue->dequeue();
      processBundle(bc);
    } catch (const std::exception &e) {
    }
  }
}

void BundleProcessor::receiveBundles() {
}

void BundleProcessor::dispatch(std::shared_ptr<Bundle> bundle,
                               std::vector<std::string> destinations) {
}

void BundleProcessor::forward(std::shared_ptr<Bundle> bundle,
                              std::vector<std::string> nextHop) {
}

void BundleProcessor::discard(std::shared_ptr<Bundle> bundle) {
}

void BundleProcessor::restore(std::shared_ptr<Bundle> bundle) {
}
<|endoftext|>


<commit_before>// Important do not use this FilterTask for final Filtered AOD productions!
// Due to the variability of the used config file, it is to easy to loose track of the used settings!

AliAnalysisTask *AddTask_caklein_LMEEFilter_PbPb(
  TString cfg="ConfigLMEE_nano_PbPb.C",
  Bool_t gridconf=kFALSE,
  TString period="",
  Bool_t storeLS = kFALSE,
  Bool_t hasMC_aod = kFALSE,
  // ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE
  ULong64_t triggers=AliVEvent::kINT7
  ){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskLMEEFilter", "No analysis manager found.");
    return 0;
  }

  //check for output aod handler
  if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {
    Warning("AddTaskLMEEFilter","No AOD output handler available. Not adding the task!");
    return 0;
  }

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;

  //Do we run on AOD?
  Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();

  //Allow merging of the filtered aods on grid trains
  if(mgr->GetGridHandler()) {
    printf(" SET MERGE FILTERED AODs \n");
    //mgr->GetGridHandler()->SetMergeAOD(kTRUE);
  }

  TString configFile("");
  printf("pwd:        %s \n",gSystem->pwd());
  if(cfg.IsNull()) cfg="ConfigLMEE_nano_PbPb.C";

  TString alienPath("alien:///alice/cern.ch/user/c/cklein/PWGDQ/dielectron/macrosLMEE/");
  TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");

  ////////// >>>>>>>>>> alien config
  if(gridconf) {
    if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) {
      gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
      configFile=gSystem->pwd();
    }
    else {
      printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() );
      return;
    }
  }
  ///////// >>>>>>>>> aliroot config
  else if(!gridconf) configFile=alirootPath.Data();
  ///////// add config to path
  configFile+="/";
  configFile+=cfg.Data();

  //load dielectron configuration file (only once)
  TString checkconfig="ConfigLMEE_nano_PbPb";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period);

  if(isAOD) {
    //add options to AliAODHandler to duplicate input event
    AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();
    aodHandler->SetCreateNonStandardAOD();
    aodHandler->SetNeedsHeaderReplication();

   if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication();
    aodHandler->SetNeedsVZEROReplication();
    /*aodHandler->SetNeedsTracksBranchReplication();
    aodHandler->SetNeedsCaloClustersBranchReplication();
    aodHandler->SetNeedsVerticesBranchReplication();
    aodHandler->SetNeedsCascadesBranchReplication();
    aodHandler->SetNeedsTrackletsBranchReplication();
    aodHandler->SetNeedsPMDClustersBranchReplication();
    aodHandler->SetNeedsJetsBranchReplication();
    aodHandler->SetNeedsFMDClustersBranchReplication();
    //aodHandler->SetNeedsMCParticlesBranchReplication();
    aodHandler->SetNeedsDimuonsBranchReplication();*/ // deactivates several branches
    //    if(hasMC) aodHandler->SetNeedsV0sBranchReplication();
    if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();
    diEle->SetHasMC(hasMC);
  }

  //Create task and add it to the analysis manager
  AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("LMEE_DielectronFilter");
  task->SetTriggerMask(triggers);
  if (!hasMC) task->UsePhysicsSelection();

  task->SetDielectron(diEle);
  if(storeLS) task->SetStoreLikeSignCandidates(storeLS);
  task->SetCreateNanoAODs(kTRUE);
  task->SetStoreEventplanes(kTRUE);
  task->SetStoreEventsWithSingleTracks(kTRUE);
  // task->SetStoreHeader(kTRUE);
  mgr->AddTask(task);

  //----------------------
  //create data containers
  //----------------------

  TString containerName = mgr->GetCommonFileName();
  containerName += ":PWGDQ_dielectronFilter";

  //create output container

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("LMEE_FilterQA",
                         THashList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         containerName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("LMEE_FilterEventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         containerName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);

  return task;
}
<commit_msg>correcting macro name<commit_after>// Important do not use this FilterTask for final Filtered AOD productions!
// Due to the variability of the used config file, it is to easy to loose track of the used settings!

AliAnalysisTask *AddTaskLMEEFilter_PbPb(
  TString cfg="ConfigLMEE_nano_PbPb.C",
  Bool_t gridconf=kFALSE,
  TString period="",
  Bool_t storeLS = kFALSE,
  Bool_t hasMC_aod = kFALSE,
  // ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE
  ULong64_t triggers=AliVEvent::kINT7
  ){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskLMEEFilter", "No analysis manager found.");
    return 0;
  }

  //check for output aod handler
  if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {
    Warning("AddTaskLMEEFilter","No AOD output handler available. Not adding the task!");
    return 0;
  }

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;

  //Do we run on AOD?
  Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();

  //Allow merging of the filtered aods on grid trains
  if(mgr->GetGridHandler()) {
    printf(" SET MERGE FILTERED AODs \n");
    //mgr->GetGridHandler()->SetMergeAOD(kTRUE);
  }

  TString configFile("");
  printf("pwd:        %s \n",gSystem->pwd());
  if(cfg.IsNull()) cfg="ConfigLMEE_nano_PbPb.C";

  TString alienPath("alien:///alice/cern.ch/user/c/cklein/PWGDQ/dielectron/macrosLMEE/");
  TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");

  ////////// >>>>>>>>>> alien config
  if(gridconf) {
    if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) {
      gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
      configFile=gSystem->pwd();
    }
    else {
      printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() );
      return;
    }
  }
  ///////// >>>>>>>>> aliroot config
  else if(!gridconf) configFile=alirootPath.Data();
  ///////// add config to path
  configFile+="/";
  configFile+=cfg.Data();

  //load dielectron configuration file (only once)
  TString checkconfig="ConfigLMEE_nano_PbPb";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period);

  if(isAOD) {
    //add options to AliAODHandler to duplicate input event
    AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();
    aodHandler->SetCreateNonStandardAOD();
    aodHandler->SetNeedsHeaderReplication();

   if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication();
    aodHandler->SetNeedsVZEROReplication();
    /*aodHandler->SetNeedsTracksBranchReplication();
    aodHandler->SetNeedsCaloClustersBranchReplication();
    aodHandler->SetNeedsVerticesBranchReplication();
    aodHandler->SetNeedsCascadesBranchReplication();
    aodHandler->SetNeedsTrackletsBranchReplication();
    aodHandler->SetNeedsPMDClustersBranchReplication();
    aodHandler->SetNeedsJetsBranchReplication();
    aodHandler->SetNeedsFMDClustersBranchReplication();
    //aodHandler->SetNeedsMCParticlesBranchReplication();
    aodHandler->SetNeedsDimuonsBranchReplication();*/ // deactivates several branches
    //    if(hasMC) aodHandler->SetNeedsV0sBranchReplication();
    if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();
    diEle->SetHasMC(hasMC);
  }

  //Create task and add it to the analysis manager
  AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("LMEE_DielectronFilter");
  task->SetTriggerMask(triggers);
  if (!hasMC) task->UsePhysicsSelection();

  task->SetDielectron(diEle);
  if(storeLS) task->SetStoreLikeSignCandidates(storeLS);
  task->SetCreateNanoAODs(kTRUE);
  task->SetStoreEventplanes(kTRUE);
  task->SetStoreEventsWithSingleTracks(kTRUE);
  // task->SetStoreHeader(kTRUE);
  mgr->AddTask(task);

  //----------------------
  //create data containers
  //----------------------

  TString containerName = mgr->GetCommonFileName();
  containerName += ":PWGDQ_dielectronFilter";

  //create output container

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("LMEE_FilterQA",
                         THashList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         containerName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("LMEE_FilterEventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         containerName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);

  return task;
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS tl01 (1.2.38); FILE MERGED 2004/04/20 14:41:59 tl 1.2.38.5: RESYNC: (1.2-1.3); FILE MERGED 2004/04/02 10:29:22 tl 1.2.38.4: #110762# change in Hangul/Hanja text conversion API 2004/03/22 11:18:21 tl 1.2.38.3: #111082# eDirection for Hangul/Hanja conversion fixed 2003/07/31 10:57:30 tl 1.2.38.2: #110762# make use of Hangul/Hanja user dictionaries 2003/07/31 10:56:09 tl 1.2.38.1: #110763# make use of Hangul/Hanja user dictionaries<commit_after><|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_set_fsi_gp_shadow.C
///
/// @brief --IPL step 0.8 proc_prep_ipl
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Brian Silver <bsilver@us.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_set_fsi_gp_shadow.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9n2_perv_scom_addresses_fld.H>

fapi2::ReturnCode p9_set_fsi_gp_shadow(const
                                       fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    fapi2::buffer<uint8_t> l_read_attr;
    fapi2::buffer<uint32_t> l_cfam_data;
    FAPI_INF("p9_set_fsi_gp_shadow: Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,
                           l_read_attr));

    if ( l_read_attr )
    {
        FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers");
        //Setting ROOT_CTRL0_COPY register value
        //CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));

        //Setting ROOT_CTRL1_COPY register value
        //CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));

        //Setting ROOT_CTRL2_COPY register value
        //CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));

        //Setting ROOT_CTRL3_COPY register value
        //CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));

        //Setting ROOT_CTRL4_COPY register value
        //CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));

        //Setting ROOT_CTRL5_COPY register value
        //CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
                                        l_cfam_data));

        //Setting ROOT_CTRL6_COPY register value
        //CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
                                        l_cfam_data));

        //Setting ROOT_CTRL7_COPY register value
        //CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));

        //Setting ROOT_CTRL8_COPY register value
        //CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
                                        l_cfam_data));

        //Setting PERV_CTRL0_COPY register value
        //CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,
                                        p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));

        //Setting PERV_CTRL1_COPY register value
        //CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,
                                        p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));
    }

    /* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 */
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_read_attr));
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));

    if (l_read_attr)
    {
        l_cfam_data.setBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
    }
    else
    {
        l_cfam_data.clearBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
    }

    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));

    FAPI_INF("p9_set_fsi_gp_shadow: Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_set_fsi_gp_shadow.C
///
/// @brief --IPL step 0.8 proc_prep_ipl
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Brian Silver <bsilver@us.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_set_fsi_gp_shadow.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9n2_perv_scom_addresses_fld.H>

fapi2::ReturnCode p9_set_fsi_gp_shadow(const
                                       fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    fapi2::buffer<uint8_t> l_read_attr;
    fapi2::buffer<uint32_t> l_cfam_data;
    FAPI_INF("p9_set_fsi_gp_shadow: Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,
                           l_read_attr));

    if ( l_read_attr )
    {
        FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers");
        //Setting ROOT_CTRL0_COPY register value
        //CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));

        //Setting ROOT_CTRL1_COPY register value
        //CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));

        //Setting ROOT_CTRL2_COPY register value
        //CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));

        //Setting ROOT_CTRL3_COPY register value
        //CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));

        //Setting ROOT_CTRL4_COPY register value
        //CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));

        //Setting ROOT_CTRL5_COPY register value
        //CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
                                        l_cfam_data));

        //Setting ROOT_CTRL6_COPY register value
        //CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
                                        l_cfam_data));

        //Setting ROOT_CTRL7_COPY register value
        //CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,
                                        p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));

        //Setting ROOT_CTRL8_COPY register value
        //CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
                                        l_cfam_data));
        l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |
                      p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
                                        l_cfam_data));

        //Setting PERV_CTRL0_COPY register value
        //CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,
                                        p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));

        //Setting PERV_CTRL1_COPY register value
        //CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE
        FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,
                                        p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));
    }

    /* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 */
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_read_attr));
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));

    if (l_read_attr)
    {
        l_cfam_data.setBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
    }
    else
    {
        l_cfam_data.clearBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
    }

    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));

    FAPI_INF("p9_set_fsi_gp_shadow: Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before><commit_msg>ProjectionToPlaneMultiMapping: minor improvments<commit_after><|endoftext|>


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

#include <cstdint>
#include <iostream>
#include <memory>
#include <thread>

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "gflags/gflags.h"
#include "modules/common/proto/error_code.pb.h"
#include "modules/common/time/time.h"
#include "modules/common/util/factory.h"
#include "modules/drivers/canbus/can_client/can_client.h"
#include "modules/drivers/canbus/can_client/can_client_factory.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/proto/can_card_parameter.pb.h"

DEFINE_bool(only_one_send, false, "only send test.");
DEFINE_string(can_client_conf_file_a,
              "modules/canbus/conf/can_client_conf_a.pb.txt",
              "can client conf for client a");
DEFINE_string(can_client_conf_file_b,
              "modules/canbus/conf/can_client_conf_b.pb.txt",
              "can client conf for client b");
DEFINE_int64(agent_mutual_send_frames, 1000, "Every agent send frame num");

const int32_t MAX_CAN_SEND_FRAME_LEN = 1;
const int32_t MAX_CAN_RECV_FRAME_LEN = 10;

namespace apollo {
namespace drivers {
namespace canbus {

struct TestCanParam {
  CANCardParameter conf;
  bool is_first_agent = false;
  int32_t recv_cnt = 0;
  int32_t recv_err_cnt = 0;
  int32_t send_cnt = 0;
  int32_t send_err_cnt = 0;
  int32_t send_lost_cnt = 0;
  int32_t send_time = 0;
  int32_t recv_time = 0;
  CanClient *can_client = nullptr;

  TestCanParam() = default;

  void print() {
    AINFO << "conf: " << conf.ShortDebugString()
          << ", total send: " << send_cnt + send_err_cnt << "/"
          << FLAGS_agent_mutual_send_frames << ", send_ok: " << send_cnt
          << " , send_err_cnt: " << send_err_cnt
          << ", send_lost_cnt: " << send_lost_cnt << ", recv_cnt: " << recv_cnt
          << ", send_time: " << send_time << ", recv_time: " << recv_time;
  }
};

class CanAgent {
 public:
  explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {}

  TestCanParam *param_ptr() { return param_ptr_; }

  CanAgent *other_agent() { return other_agent_; }

  bool Start() {
    thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); }));
    if (thread_recv_ == nullptr) {
      AERROR << "Unable to create recv thread.";
      return false;
    }
    thread_send_.reset(new std::thread([this] { SendThreadFunc(); }));
    if (thread_send_ == nullptr) {
      AERROR << "Unable to create send thread.";
      return false;
    }
    return true;
  }

  void SendThreadFunc() {
    using common::ErrorCode;
    using common::time::AsInt64;
    using common::time::Clock;
    using common::time::micros;
    AINFO << "Send thread starting...";
    TestCanParam *param = param_ptr();
    CanClient *client = param->can_client;
    std::vector<CanFrame> frames;
    frames.resize(MAX_CAN_SEND_FRAME_LEN);

    int32_t count = 0;
    int32_t start_id = 0;
    int32_t end_id = 0;
    int32_t id = 0;
    if (param->is_first_agent) {
      start_id = 1;
      end_id = 128;
    } else {
      start_id = 129;
      end_id = start_id + 127;
    }
    id = start_id;
    int32_t send_id = id;
    AINFO << "port:" << param->conf.ShortDebugString()
          << ", start_id:" << start_id << ", end_id:" << end_id;

    // wait for other agent receiving is ok.
    while (!other_agent()->is_receiving()) {
      std::this_thread::yield();
    }
    int64_t start = AsInt64<micros>(Clock::Now());
    while (true) {
      // param->print();
      if (count >= FLAGS_agent_mutual_send_frames) {
        break;
      }
      for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) {
        // frames[i].id = id_count & 0x3FF;
        send_id = id;
        frames[i].id = id;
        frames[i].len = 8;
        frames[i].data[7] = static_cast<uint8_t>(count % 256);
        for (uint8_t j = 0; j < 7; ++j) {
          frames[i].data[j] = j;
        }
        ++count;
        ++id;
        if (id > end_id) {
          id = start_id;
        }
      }
      int32_t frame_num = MAX_CAN_SEND_FRAME_LEN;
      if (client->Send(frames, &frame_num) != ErrorCode::OK) {
        param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN;
        AERROR << "send_thread send msg failed!, id:" << send_id
               << ", conf:" << param->conf.ShortDebugString();
      } else {
        param->send_cnt += frame_num;
        param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num;
        AINFO << "send_frames: " << frame_num << "send_frame#"
              << frames[0].CanFrameString()
              << " send lost:" << MAX_CAN_SEND_FRAME_LEN - frame_num
              << ", conf:" << param->conf.ShortDebugString();
      }
    }
    int64_t end = AsInt64<micros>(Clock::Now());
    param->send_time = static_cast<int32_t>(end - start);
    // In case for finish too quick to receiver miss some msg
    sleep(2);
    AINFO << "Send thread stopping..." << param->conf.ShortDebugString();
    is_sending_finish(true);
    return;
  }

  void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; }

  bool is_receiving() const { return is_receiving_; }

  void is_receiving(bool val) { is_receiving_ = val; }

  bool is_sending_finish() const { return is_sending_finish_; }

  void is_sending_finish(bool val) { is_sending_finish_ = val; }

  void RecvThreadFunc() {
    using common::ErrorCode;
    using common::time::AsInt64;
    using common::time::Clock;
    using common::time::micros;
    AINFO << "Receive thread starting...";
    TestCanParam *param = param_ptr();
    CanClient *client = param->can_client;
    int64_t start = 0;
    std::vector<CanFrame> buf;

    bool first = true;
    while (!other_agent()->is_sending_finish()) {
      is_receiving(true);
      int32_t len = MAX_CAN_RECV_FRAME_LEN;
      ErrorCode ret = client->Receive(&buf, &len);
      if (len == 0) {
        AINFO << "recv frame:0";
        continue;
      }
      if (first) {
        start = AsInt64<micros>(Clock::Now());
        first = false;
      }
      if (ret != ErrorCode::OK || len == 0) {
        // AINFO << "channel:" << param->conf.channel_id()
        //      << ", recv frame:failed, code:" << ret;
        AINFO << "recv error:" << ret;
        continue;
      }
      for (int32_t i = 0; i < len; ++i) {
        param->recv_cnt = param->recv_cnt + 1;
        AINFO << "recv_frame#" << buf[i].CanFrameString()
              << " conf:" << param->conf.ShortDebugString()
              << ",recv_cnt: " << param->recv_cnt;
      }
    }
    int64_t end = AsInt64<micros>(Clock::Now());
    param->recv_time = static_cast<int32_t>(end - start);
    AINFO << "Recv thread stopping..., conf:" << param->conf.ShortDebugString();
    return;
  }

  void WaitForFinish() {
    if (thread_send_ != nullptr && thread_send_->joinable()) {
      thread_send_->join();
      thread_send_.reset();
      AINFO << "Send thread stopped. conf:"
            << param_ptr_->conf.ShortDebugString();
    }
    if (thread_recv_ != nullptr && thread_recv_->joinable()) {
      thread_recv_->join();
      thread_recv_.reset();
      AINFO << "Recv thread stopped. conf:"
            << param_ptr_->conf.ShortDebugString();
    }
  }

 private:
  bool is_receiving_ = false;
  bool is_sending_finish_ = false;
  CanAgent *other_agent_ = nullptr;
  TestCanParam *param_ptr_ = nullptr;
  std::unique_ptr<std::thread> thread_recv_;
  std::unique_ptr<std::thread> thread_send_;
};

}  // namespace canbus
}  // namespace drivers
}  // namespace apollo

int main(int32_t argc, char **argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  using apollo::common::ErrorCode;
  using apollo::drivers::canbus::CanAgent;
  using apollo::drivers::canbus::CANCardParameter;
  using apollo::drivers::canbus::CanClient;
  using apollo::drivers::canbus::CanClientFactory;
  using apollo::drivers::canbus::TestCanParam;
  CANCardParameter can_client_conf_a;
  std::shared_ptr<TestCanParam> param_ptr_a(new TestCanParam());
  std::shared_ptr<TestCanParam> param_ptr_b(new TestCanParam());

  auto can_client_factory = CanClientFactory::Instance();
  can_client_factory->RegisterCanClients();

  if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a,
                                               &can_client_conf_a)) {
    AERROR << "Unable to load canbus conf file: "
           << FLAGS_can_client_conf_file_a;
    return 1;
  } else {
    AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_a;
  }
  AINFO << can_client_conf_a.ShortDebugString();
  auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand());
  if (!client_a || !client_a->Init(can_client_conf_a) ||
      client_a->Start() != ErrorCode::OK) {
    AERROR << "Create can client a failed.";
    return 1;
  }
  param_ptr_a->can_client = client_a.get();
  param_ptr_a->is_first_agent = true;
  param_ptr_a->conf = can_client_conf_a;

  CANCardParameter can_client_conf_b;
  std::unique_ptr<CanClient> client_b;
  if (!FLAGS_only_one_send) {
    if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b,
                                                 &can_client_conf_b)) {
      AERROR << "Unable to load canbus conf file: "
             << FLAGS_can_client_conf_file_b;
      return 1;
    } else {
      AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_b;
    }
    AINFO << can_client_conf_b.ShortDebugString();
    client_b = can_client_factory->CreateObject(can_client_conf_b.brand());
    if (!client_b || !client_b->Init(can_client_conf_b) ||
        client_b->Start() != ErrorCode::OK) {
      AERROR << "Create can client b failed.";
      return 1;
    }
    param_ptr_b->can_client = client_b.get();
    param_ptr_b->conf = can_client_conf_b;
  }

  CanAgent agent_a(param_ptr_a.get());
  CanAgent agent_b(param_ptr_b.get());
  agent_a.AddOtherAgent(&agent_b);
  agent_b.AddOtherAgent(&agent_a);
  if (!agent_a.Start()) {
    AERROR << "Agent a start failed.";
    return -1;
  }
  if (FLAGS_only_one_send) {
    agent_b.is_receiving(true);
    agent_b.is_sending_finish(true);
  } else {
    if (!agent_b.Start()) {
      AERROR << "Agent b start failed.";
      return -1;
    }
  }

  agent_a.WaitForFinish();
  if (!FLAGS_only_one_send) {
    agent_b.WaitForFinish();
  }
  param_ptr_a->print();
  if (!FLAGS_only_one_send) {
    param_ptr_b->print();
  }

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

#include <cstdint>
#include <iostream>
#include <memory>
#include <thread>

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "gflags/gflags.h"
#include "modules/common/proto/error_code.pb.h"
#include "modules/common/time/time.h"
#include "modules/common/util/factory.h"
#include "modules/drivers/canbus/can_client/can_client.h"
#include "modules/drivers/canbus/can_client/can_client_factory.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/proto/can_card_parameter.pb.h"

DEFINE_bool(only_one_send, false, "only send test.");
DEFINE_string(can_client_conf_file_a,
              "modules/canbus/conf/can_client_conf_a.pb.txt",
              "can client conf for client a");
DEFINE_string(can_client_conf_file_b,
              "modules/canbus/conf/can_client_conf_b.pb.txt",
              "can client conf for client b");
DEFINE_int64(agent_mutual_send_frames, 1000, "Every agent send frame num");

const int32_t MAX_CAN_SEND_FRAME_LEN = 1;
const int32_t MAX_CAN_RECV_FRAME_LEN = 10;

namespace apollo {
namespace drivers {
namespace canbus {

struct TestCanParam {
  CANCardParameter conf;
  bool is_first_agent = false;
  int32_t recv_cnt = 0;
  int32_t recv_err_cnt = 0;
  int32_t send_cnt = 0;
  int32_t send_err_cnt = 0;
  int32_t send_lost_cnt = 0;
  int32_t send_time = 0;
  int32_t recv_time = 0;
  CanClient *can_client = nullptr;

  TestCanParam() = default;

  void print() {
    AINFO << "conf: " << conf.ShortDebugString()
          << ", total send: " << send_cnt + send_err_cnt << "/"
          << FLAGS_agent_mutual_send_frames << ", send_ok: " << send_cnt
          << " , send_err_cnt: " << send_err_cnt
          << ", send_lost_cnt: " << send_lost_cnt << ", recv_cnt: " << recv_cnt
          << ", send_time: " << send_time << ", recv_time: " << recv_time;
  }
};

class CanAgent {
 public:
  explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {}

  TestCanParam *param_ptr() { return param_ptr_; }

  CanAgent *other_agent() { return other_agent_; }

  bool Start() {
    thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); }));
    if (thread_recv_ == nullptr) {
      AERROR << "Unable to create recv thread.";
      return false;
    }
    thread_send_.reset(new std::thread([this] { SendThreadFunc(); }));
    if (thread_send_ == nullptr) {
      AERROR << "Unable to create send thread.";
      return false;
    }
    return true;
  }

  void SendThreadFunc() {
    using common::ErrorCode;
    using common::time::AsInt64;
    using common::time::Clock;
    using common::time::micros;
    AINFO << "Send thread starting...";
    TestCanParam *param = param_ptr();
    CanClient *client = param->can_client;
    std::vector<CanFrame> frames;
    frames.resize(MAX_CAN_SEND_FRAME_LEN);

    int32_t count = 0;
    int32_t start_id = 0;
    int32_t end_id = 0;
    int32_t id = 0;
    if (param->is_first_agent) {
      start_id = 1;
      end_id = 128;
    } else {
      start_id = 129;
      end_id = start_id + 127;
    }
    id = start_id;
    int32_t send_id = id;
    AINFO << "port:" << param->conf.ShortDebugString()
          << ", start_id:" << start_id << ", end_id:" << end_id;

    // wait for other agent receiving is ok.
    while (!other_agent()->is_receiving()) {
      std::this_thread::yield();
    }
    int64_t start = AsInt64<micros>(Clock::Now());
    while (true) {
      // param->print();
      if (count >= FLAGS_agent_mutual_send_frames) {
        break;
      }
      for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) {
        // frames[i].id = id_count & 0x3FF;
        send_id = id;
        frames[i].id = id;
        frames[i].len = 8;
        frames[i].data[7] = static_cast<uint8_t>(count % 256);
        for (uint8_t j = 0; j < 7; ++j) {
          frames[i].data[j] = j;
        }
        ++count;
        ++id;
        if (id > end_id) {
          id = start_id;
        }
      }
      int32_t frame_num = MAX_CAN_SEND_FRAME_LEN;
      if (client->Send(frames, &frame_num) != ErrorCode::OK) {
        param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN;
        AERROR << "send_thread send msg failed!, id:" << send_id
               << ", conf:" << param->conf.ShortDebugString();
      } else {
        param->send_cnt += frame_num;
        param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num;
        AINFO << "send_frames: " << frame_num << "send_frame#"
              << frames[0].CanFrameString()
              << " send lost:" << MAX_CAN_SEND_FRAME_LEN - frame_num
              << ", conf:" << param->conf.ShortDebugString();
      }
    }
    int64_t end = AsInt64<micros>(Clock::Now());
    param->send_time = static_cast<int32_t>(end - start);
    // In case for finish too quick to receiver miss some msg
    sleep(2);
    AINFO << "Send thread stopping..." << param->conf.ShortDebugString();
    is_sending_finish(true);
    return;
  }

  void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; }

  bool is_receiving() const { return is_receiving_; }

  void is_receiving(bool val) { is_receiving_ = val; }

  bool is_sending_finish() const { return is_sending_finish_; }

  void is_sending_finish(bool val) { is_sending_finish_ = val; }

  void RecvThreadFunc() {
    using common::ErrorCode;
    using common::time::AsInt64;
    using common::time::Clock;
    using common::time::micros;
    AINFO << "Receive thread starting...";
    TestCanParam *param = param_ptr();
    CanClient *client = param->can_client;
    int64_t start = 0;
    std::vector<CanFrame> buf;

    bool first = true;
    while (!other_agent()->is_sending_finish()) {
      is_receiving(true);
      int32_t len = MAX_CAN_RECV_FRAME_LEN;
      ErrorCode ret = client->Receive(&buf, &len);
      if (len == 0) {
        AINFO << "recv frame:0";
        continue;
      }
      if (first) {
        start = AsInt64<micros>(Clock::Now());
        first = false;
      }
      if (ret != ErrorCode::OK || len == 0) {
        // AINFO << "channel:" << param->conf.channel_id()
        //      << ", recv frame:failed, code:" << ret;
        AINFO << "recv error:" << ret;
        continue;
      }
      for (int32_t i = 0; i < len; ++i) {
        param->recv_cnt = param->recv_cnt + 1;
        AINFO << "recv_frame#" << buf[i].CanFrameString()
              << " conf:" << param->conf.ShortDebugString()
              << ",recv_cnt: " << param->recv_cnt;
      }
    }
    int64_t end = AsInt64<micros>(Clock::Now());
    param->recv_time = static_cast<int32_t>(end - start);
    AINFO << "Recv thread stopping..., conf:" << param->conf.ShortDebugString();
    return;
  }

  void WaitForFinish() {
    if (thread_send_ != nullptr && thread_send_->joinable()) {
      thread_send_->join();
      thread_send_.reset();
      AINFO << "Send thread stopped. conf:"
            << param_ptr_->conf.ShortDebugString();
    }
    if (thread_recv_ != nullptr && thread_recv_->joinable()) {
      thread_recv_->join();
      thread_recv_.reset();
      AINFO << "Recv thread stopped. conf:"
            << param_ptr_->conf.ShortDebugString();
    }
  }

 private:
  bool is_receiving_ = false;
  bool is_sending_finish_ = false;
  CanAgent *other_agent_ = nullptr;
  TestCanParam *param_ptr_ = nullptr;
  std::unique_ptr<std::thread> thread_recv_;
  std::unique_ptr<std::thread> thread_send_;
};

}  // namespace canbus
}  // namespace drivers
}  // namespace apollo

int main(int32_t argc, char **argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  using apollo::common::ErrorCode;
  using apollo::drivers::canbus::CanAgent;
  using apollo::drivers::canbus::CANCardParameter;
  using apollo::drivers::canbus::CanClient;
  using apollo::drivers::canbus::CanClientFactory;
  using apollo::drivers::canbus::TestCanParam;
  CANCardParameter can_client_conf_a;
  std::shared_ptr<TestCanParam> param_ptr_a(new TestCanParam());
  std::shared_ptr<TestCanParam> param_ptr_b(new TestCanParam());

  auto can_client_factory = CanClientFactory::Instance();
  can_client_factory->RegisterCanClients();

  if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a,
                                               &can_client_conf_a)) {
    AERROR << "Unable to load canbus conf file: "
           << FLAGS_can_client_conf_file_a;
    return -1;
  }
  AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_a;
  AINFO << can_client_conf_a.ShortDebugString();
  auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand());
  if (!client_a || !client_a->Init(can_client_conf_a) ||
      client_a->Start() != ErrorCode::OK) {
    AERROR << "Create can client a failed.";
    return -1;
  }
  param_ptr_a->can_client = client_a.get();
  param_ptr_a->is_first_agent = true;
  param_ptr_a->conf = can_client_conf_a;

  CANCardParameter can_client_conf_b;
  std::unique_ptr<CanClient> client_b;
  if (!FLAGS_only_one_send) {
    if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b,
                                                 &can_client_conf_b)) {
      AERROR << "Unable to load canbus conf file: "
             << FLAGS_can_client_conf_file_b;
      return -1;
    }
    AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_b;
    AINFO << can_client_conf_b.ShortDebugString();
    client_b = can_client_factory->CreateObject(can_client_conf_b.brand());
    if (!client_b || !client_b->Init(can_client_conf_b) ||
        client_b->Start() != ErrorCode::OK) {
      AERROR << "Create can client b failed.";
      return -1;
    }
    param_ptr_b->can_client = client_b.get();
    param_ptr_b->conf = can_client_conf_b;
  }

  CanAgent agent_a(param_ptr_a.get());
  CanAgent agent_b(param_ptr_b.get());
  agent_a.AddOtherAgent(&agent_b);
  agent_b.AddOtherAgent(&agent_a);
  if (!agent_a.Start()) {
    AERROR << "Agent a start failed.";
    return -1;
  }
  if (FLAGS_only_one_send) {
    agent_b.is_receiving(true);
    agent_b.is_sending_finish(true);
  } else {
    if (!agent_b.Start()) {
      AERROR << "Agent b start failed.";
      return -1;
    }
  }

  agent_a.WaitForFinish();
  if (!FLAGS_only_one_send) {
    agent_b.WaitForFinish();
  }
  param_ptr_a->print();
  if (!FLAGS_only_one_send) {
    param_ptr_b->print();
  }

  return 0;
}
<|endoftext|>


<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2005 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/Thread/UncaughtThreadException.h>

namespace vpr
{

UncaughtThreadException::UncaughtThreadException(const std::string& msg,
                                 const std::string& location) throw()
   : Exception(msg, location)
{
   /* Do nothing. */ ;
}

UncaughtThreadException::~UncaughtThreadException() throw()
{
   /* Do nothing. */ ;
}

void UncaughtThreadException::setException(const vpr::Exception& ex)
{
   mDescription = ex.getExceptionName() + ": " + ex.getDescription();
   mLocation = ex.getLocation();
   mStackTrace = ex.getStackTrace();
}

void UncaughtThreadException::setException(const std::exception& ex)
{
   mDescription = ex.what();
   mLocation = "Location not availible with std::exception.";
   mStackTrace = "Stacktrace not availible with std::exception.";
}

}
<commit_msg>Fixed Visual C++ 7.0 compile error.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2005 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#include <sstream>

#include <vpr/Thread/UncaughtThreadException.h>

namespace vpr
{

UncaughtThreadException::UncaughtThreadException(const std::string& msg,
                                                 const std::string& location)
   throw()
   : Exception(msg, location)
{
   /* Do nothing. */ ;
}

UncaughtThreadException::~UncaughtThreadException() throw()
{
   /* Do nothing. */ ;
}

void UncaughtThreadException::setException(const vpr::Exception& ex)
{
   std::stringstream desc_stream;
   desc_stream << ex.getExceptionName() << ": " + ex.getDescription();

   mDescription = desc_stream.str();
   mLocation = ex.getLocation();
   mStackTrace = ex.getStackTrace();
}

void UncaughtThreadException::setException(const std::exception& ex)
{
   mDescription = ex.what();
   mLocation = "Location not availible with std::exception.";
   mStackTrace = "Stacktrace not availible with std::exception.";
}

}
<|endoftext|>


<commit_before><commit_msg>new_client: updated xtfs_send against Yield changes<commit_after><|endoftext|>


<commit_before>
#pragma once

#include <cppassist/logging/logging.h>

#include <cppexpose/typed/Typed.h>

#include <gloperate/pipeline/Stage.h>
#include <gloperate/pipeline/Slot.h>

namespace gloperate
{

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U>::pointer(U * value) -> Pointer
{
    return value;
}

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U*>::pointer(U ** value) -> Pointer
{
    return *value;
}

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U*>::pointer(U * const * value) -> Pointer
{
    return *value;
}

template <typename T>
Slot<T>::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value)
: cppexpose::DirectValue<T, AbstractSlot>(value)
, m_valid(true)
, m_source(nullptr)
{
    // Do not add property to object, yet. Just initialize the property itself
    this->initProperty(name, nullptr);

    // Initialize slot, will also add slot as a property
    this->initSlot(slotType, parent);
}

template <typename T>
Slot<T>::Slot(SlotType slotType, const std::string & name, const T & value)
: cppexpose::DirectValue<T, AbstractSlot>(value)
, m_valid(true)
, m_source(nullptr)
{
    // Make as a dynamic slot
    this->m_dynamic = true;

    // Do not add property to object, yet. Just initialize the property itself
    this->initProperty(name, nullptr);

    // Initialize slot
    this->initSlot(slotType, nullptr);
}

template <typename T>
Slot<T>::~Slot()
{
}

template <typename T>
bool Slot<T>::connect(Slot<T> * source)
{
    assert(source != nullptr);

    cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot " << source->qualifiedName();

    // Check if source is valid
    if (!source) {
        return false;
    }

    // Set source
    m_source = source;

    // Connect to data container; no direct binding of member function to achive virtual lookup
    m_valueConnection = m_source->valueChanged.connect([this] (const T & value)
    {
        this->onValueChanged(value);
    } );
    m_validConnection = m_source->valueInvalidated.connect([this] ()
    {
        this->onValueInvalidated();
    } );

    // Emit events
    this->promoteConnection();
    this->promoteRequired();
    this->onValueChanged(m_source->value());

    // Success
    return true;
}

template <typename T>
Slot<T> & Slot<T>::operator<<(Slot<T> & source)
{
    this->connect(&source);
    return *this;
}

template <typename T>
const T & Slot<T>::operator*() const
{
    return *this->ptr();
}

template <typename T>
auto Slot<T>::operator->() -> typename DereferenceHelper<T>::Pointer
{
    return DereferenceHelper<T>::pointer(this->ptr());
}

template <typename T>
auto Slot<T>::operator->() const -> const typename DereferenceHelper<T>::Pointer
{
    return DereferenceHelper<T>::pointer(this->ptr());
}

template <typename T>
bool Slot<T>::isCompatible(const AbstractSlot * source) const
{
    // Check if source is valid and compatible data container
    if (!source)
    {
        return false;
    }

    // Check if types are equal
    return this->type() == source->type();
}

template <typename T>
bool Slot<T>::connect(AbstractSlot * source)
{
    // Check if source is valid and compatible data container
    if (!source || !isCompatible(source))
    {
        cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot failed for " << source->qualifiedName();
        return false;
    }

    // Connect to source data
    return connect(static_cast< Slot<T> * >(source));
}

template <typename T>
void Slot<T>::disconnect()
{
    // Reset source property
    m_source     = nullptr;
    m_valueConnection = cppexpose::ScopedConnection();
    m_validConnection = cppexpose::ScopedConnection();

    cppassist::debug(2, "gloperate") << this->qualifiedName() << ": disconnect slot";

    // Emit events
    this->promoteConnection();
    this->onValueChanged(this->m_value);
}

template <typename T>
const AbstractSlot * Slot<T>::source() const
{
    return m_source;
}

template <typename T>
bool Slot<T>::isValid() const
{
    // If connected, return validity of source slot
    if (m_source)
    {
        return m_source->isValid();
    }

    // Return validity of own data
    return m_valid;
}

template <typename T>
void Slot<T>::invalidate()
{
    if (!m_valid)
    {
        return;
    }

    // If connected, abort function
    if (!m_source)
    {
        m_valid = false;
    }

    // Emit signal if it was invalidated
    this->onValueInvalidated();
}

template <typename T>
bool Slot<T>::hasChanged() const
{
    return m_changed;
}

template <typename T>
void Slot<T>::setChanged(bool hasChanged)
{
    m_changed = hasChanged;
}

template <typename T>
void Slot<T>::onRequiredChanged()
{
    promoteRequired();
}

template <typename T>
T Slot<T>::value() const
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->value();
    }

    // Return own data
    return this->m_value;
}

template <typename T>
void Slot<T>::setValue(const T & value)
{
    // If connected, abort function
    if (m_source)
    {
        return;
    }

    // Set own data
    this->m_value = value;
    this->m_valid = true;

    // Emit signal
    this->onValueChanged(this->m_value);
}

template <typename T>
const T * Slot<T>::ptr() const
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->ptr();
    }

    // Return own data
    return &this->m_value;
}

template <typename T>
T * Slot<T>::ptr()
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->ptr();
    }

    // Return own data
    return &this->m_value;
}

template <typename T>
std::unique_ptr<cppexpose::AbstractTyped> Slot<T>::clone() const
{
    return nullptr;
}

template <typename T>
bool Slot<T>::isObject() const
{
    return false;
}

template <typename T>
void Slot<T>::promoteConnection()
{
    // Emit signal
    this->connectionChanged();
    this->parentStage()->invalidateInputConnections();
}

template <typename T>
void Slot<T>::promoteRequired()
{
    // Check if input slot is connected
    if (!m_source)
    {
        return;
    }

    // Promote required-flag to connected slot
    m_source->setRequired(this->m_required);
}

} // namespace gloperate
<commit_msg>Fix Slot<T>::promoteConnection behavior<commit_after>
#pragma once

#include <cppassist/logging/logging.h>

#include <cppexpose/typed/Typed.h>

#include <gloperate/pipeline/Stage.h>
#include <gloperate/pipeline/Slot.h>

namespace gloperate
{

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U>::pointer(U * value) -> Pointer
{
    return value;
}

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U*>::pointer(U ** value) -> Pointer
{
    return *value;
}

template <typename T>
template <typename U>
auto Slot<T>::DereferenceHelper<U*>::pointer(U * const * value) -> Pointer
{
    return *value;
}

template <typename T>
Slot<T>::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value)
: cppexpose::DirectValue<T, AbstractSlot>(value)
, m_valid(true)
, m_source(nullptr)
{
    // Do not add property to object, yet. Just initialize the property itself
    this->initProperty(name, nullptr);

    // Initialize slot, will also add slot as a property
    this->initSlot(slotType, parent);
}

template <typename T>
Slot<T>::Slot(SlotType slotType, const std::string & name, const T & value)
: cppexpose::DirectValue<T, AbstractSlot>(value)
, m_valid(true)
, m_source(nullptr)
{
    // Make as a dynamic slot
    this->m_dynamic = true;

    // Do not add property to object, yet. Just initialize the property itself
    this->initProperty(name, nullptr);

    // Initialize slot
    this->initSlot(slotType, nullptr);
}

template <typename T>
Slot<T>::~Slot()
{
}

template <typename T>
bool Slot<T>::connect(Slot<T> * source)
{
    assert(source != nullptr);

    cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot " << source->qualifiedName();

    // Check if source is valid
    if (!source) {
        return false;
    }

    // Set source
    m_source = source;

    // Connect to data container; no direct binding of member function to achive virtual lookup
    m_valueConnection = m_source->valueChanged.connect([this] (const T & value)
    {
        this->onValueChanged(value);
    } );
    m_validConnection = m_source->valueInvalidated.connect([this] ()
    {
        this->onValueInvalidated();
    } );

    // Emit events
    this->promoteConnection();
    this->promoteRequired();
    this->onValueChanged(m_source->value());

    // Success
    return true;
}

template <typename T>
Slot<T> & Slot<T>::operator<<(Slot<T> & source)
{
    this->connect(&source);
    return *this;
}

template <typename T>
const T & Slot<T>::operator*() const
{
    return *this->ptr();
}

template <typename T>
auto Slot<T>::operator->() -> typename DereferenceHelper<T>::Pointer
{
    return DereferenceHelper<T>::pointer(this->ptr());
}

template <typename T>
auto Slot<T>::operator->() const -> const typename DereferenceHelper<T>::Pointer
{
    return DereferenceHelper<T>::pointer(this->ptr());
}

template <typename T>
bool Slot<T>::isCompatible(const AbstractSlot * source) const
{
    // Check if source is valid and compatible data container
    if (!source)
    {
        return false;
    }

    // Check if types are equal
    return this->type() == source->type();
}

template <typename T>
bool Slot<T>::connect(AbstractSlot * source)
{
    // Check if source is valid and compatible data container
    if (!source || !isCompatible(source))
    {
        cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot failed for " << source->qualifiedName();
        return false;
    }

    // Connect to source data
    return connect(static_cast< Slot<T> * >(source));
}

template <typename T>
void Slot<T>::disconnect()
{
    // Reset source property
    m_source     = nullptr;
    m_valueConnection = cppexpose::ScopedConnection();
    m_validConnection = cppexpose::ScopedConnection();

    cppassist::debug(2, "gloperate") << this->qualifiedName() << ": disconnect slot";

    // Emit events
    this->promoteConnection();
    this->onValueChanged(this->m_value);
}

template <typename T>
const AbstractSlot * Slot<T>::source() const
{
    return m_source;
}

template <typename T>
bool Slot<T>::isValid() const
{
    // If connected, return validity of source slot
    if (m_source)
    {
        return m_source->isValid();
    }

    // Return validity of own data
    return m_valid;
}

template <typename T>
void Slot<T>::invalidate()
{
    if (!m_valid)
    {
        return;
    }

    // If connected, abort function
    if (!m_source)
    {
        m_valid = false;
    }

    // Emit signal if it was invalidated
    this->onValueInvalidated();
}

template <typename T>
bool Slot<T>::hasChanged() const
{
    return m_changed;
}

template <typename T>
void Slot<T>::setChanged(bool hasChanged)
{
    m_changed = hasChanged;
}

template <typename T>
void Slot<T>::onRequiredChanged()
{
    promoteRequired();
}

template <typename T>
T Slot<T>::value() const
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->value();
    }

    // Return own data
    return this->m_value;
}

template <typename T>
void Slot<T>::setValue(const T & value)
{
    // If connected, abort function
    if (m_source)
    {
        return;
    }

    // Set own data
    this->m_value = value;
    this->m_valid = true;

    // Emit signal
    this->onValueChanged(this->m_value);
}

template <typename T>
const T * Slot<T>::ptr() const
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->ptr();
    }

    // Return own data
    return &this->m_value;
}

template <typename T>
T * Slot<T>::ptr()
{
    // If connected, return value of source slot
    if (m_source)
    {
        return m_source->ptr();
    }

    // Return own data
    return &this->m_value;
}

template <typename T>
std::unique_ptr<cppexpose::AbstractTyped> Slot<T>::clone() const
{
    return nullptr;
}

template <typename T>
bool Slot<T>::isObject() const
{
    return false;
}

template <typename T>
void Slot<T>::promoteConnection()
{
    // Emit signal
    this->connectionChanged();
    if (this->parentStage())
    {
        this->parentStage()->invalidateInputConnections();
    }
}

template <typename T>
void Slot<T>::promoteRequired()
{
    // Check if input slot is connected
    if (!m_source)
    {
        return;
    }

    // Promote required-flag to connected slot
    m_source->setRequired(this->m_required);
}

} // namespace gloperate
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "Font.h"

#include "FloatRect.h"
#include "GlyphBuffer.h"
#include "GraphicsContext.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "SimpleFontData.h"

#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkTemplates.h"
#include "SkTypeface.h"
#include "SkUtils.h"

namespace WebCore {

void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
                      const FloatPoint& point) const {
    SkCanvas* canvas = gc->platformContext()->canvas();
    SkPaint paint;

    font->platformData().setupPaint(&paint);
    paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
    paint.setColor(gc->fillColor().rgb());

    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t));  // compile-time assert

    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
    SkScalar x = SkFloatToScalar(point.x());
    SkScalar y = SkFloatToScalar(point.y());

    // TODO(port): Android WebCore has patches for PLATFORM(SGL) which involves
    // this, however we don't have these patches and it's unclear when Android
    // may upstream them.
#if 0
    if (glyphBuffer.hasAdjustedWidths()) {
        const GlyphBufferAdvance*   adv = glyphBuffer.advances(from);
        SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
        SkPoint*                    pos = storage.get();

        for (int i = 0; i < numGlyphs; i++) {
            pos[i].set(x, y);
            x += SkFloatToScalar(adv[i].width());
            y += SkFloatToScalar(adv[i].height());
        }
        canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);
    } else {
        canvas->drawText(glyphs, numGlyphs << 1, x, y, paint);
    }
#endif

    canvas->drawText(glyphs, numGlyphs << 1, x, y, paint);
}

void Font::drawComplexText(GraphicsContext* context, const TextRun& run,
                           const FloatPoint& point, int from, int to) const
{
    notImplemented();
}

float Font::floatWidthForComplexText(const TextRun& run) const
{
    notImplemented();
    return 0;
}

int Font::offsetForPositionForComplexText(const TextRun& run, int x,
                                          bool includePartialGlyphs) const
{
    notImplemented();
    return 0;
}

FloatRect Font::selectionRectForComplexText(const TextRun& run,
                                            const IntPoint& point, int h,
                                            int from, int to) const
{
    notImplemented();
    return FloatRect();
}

}  // namespace WebCore
<commit_msg>Linux: respect non-standard advance widths for glyphs.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "Font.h"

#include "FloatRect.h"
#include "GlyphBuffer.h"
#include "GraphicsContext.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "SimpleFontData.h"

#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkTemplates.h"
#include "SkTypeface.h"
#include "SkUtils.h"

namespace WebCore {

void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
                      const FloatPoint& point) const {
    SkCanvas* canvas = gc->platformContext()->canvas();
    SkPaint paint;

    font->platformData().setupPaint(&paint);
    paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
    paint.setColor(gc->fillColor().rgb());

    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t));  // compile-time assert

    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
    SkScalar x = SkFloatToScalar(point.x());
    SkScalar y = SkFloatToScalar(point.y());

    // TODO(port): text rendering speed:
    // Android has code in their WebCore fork to special case when the
    // GlyphBuffer has no advances other than the defaults. In that case the
    // text drawing can proceed faster. However, it's unclear when those
    // patches may be upstreamed to WebKit so we always use the slower path
    // here.
    const GlyphBufferAdvance*   adv = glyphBuffer.advances(from);
    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
    SkPoint*                    pos = storage.get();

    for (int i = 0; i < numGlyphs; i++) {
        pos[i].set(x, y);
        x += SkFloatToScalar(adv[i].width());
        y += SkFloatToScalar(adv[i].height());
    }
    canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);
}

void Font::drawComplexText(GraphicsContext* context, const TextRun& run,
                           const FloatPoint& point, int from, int to) const
{
    notImplemented();
}

float Font::floatWidthForComplexText(const TextRun& run) const
{
    notImplemented();
    return 0;
}

int Font::offsetForPositionForComplexText(const TextRun& run, int x,
                                          bool includePartialGlyphs) const
{
    notImplemented();
    return 0;
}

FloatRect Font::selectionRectForComplexText(const TextRun& run,
                                            const IntPoint& point, int h,
                                            int from, int to) const
{
    notImplemented();
    return FloatRect();
}

}  // namespace WebCore
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace EffiData_Test
{
	TEST_CLASS(EffiData_Test)
	{
	protected:
		streambuf * oldStdoutBuf;
		stringstream consoleOutput;
		string consoleDump(){
			std::istreambuf_iterator<char> eos;
			std::string sout(std::istreambuf_iterator<char>(consoleOutput), eos);
			return sout;
		}
	public:
		//Redirect cout.
		TEST_METHOD_INITIALIZE(pre) {
			oldStdoutBuf = std::cout.rdbuf();
			std::cout.rdbuf(consoleOutput.rdbuf());
		}

		//Restore redirect cout
		TEST_METHOD_CLEANUP(post)
		{
			std::cout.rdbuf(oldStdoutBuf);
		}

		TEST_METHOD(BasicPrintCheck)
		{//id = 0
			Event e("test event");
			string expected = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"0\",\n"
			"    \"priority\": \"5\",\n"
			"    \"tags\": \"\",\n" //Should be [], but boost property tree doesn't support it.
			"    \"complete\": \"false\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			Assert::AreEqual(expected, result);
		}

		//WARNING: DO NOT RE-ORDER TESTS. ADD TO THE END.
		TEST_METHOD(TagCheck)
		{//id = 1
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");

			auto tags = e.getTags();
			Assert::AreEqual(2, (int)tags.size());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "nextTag")!=tags.end());
		}

		TEST_METHOD(TagPrintCheck)
		{ //id = 2
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			std::string expected = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"2\",\n"
			"    \"priority\": \"5\",\n"
			"    \"tags\": [\n"
			"        \"tag 1\",\n"
			"        \"nextTag\"\n"
			"    ],\n"
			"    \"complete\": \"false\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			Assert::AreEqual(expected, result);

		}

		TEST_METHOD(IDIncrementCheck)
		{ //id = 3,4
			Event e("test event");
			Event e2("test event");
			Assert::AreEqual(e.getId() +1 ,e2.getId());
		}

		TEST_METHOD(InputTest)
		{ //id=5.
			string contents = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"40\",\n"
			"    \"priority\": \"3\",\n"
			"    \"tags\": \"\",\n"
			"    \"complete\": \"true\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			Event e("");
			stringstream ss;
			ss.str(contents);
			ss>>e;
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			Assert::AreEqual(contents, result);
		}

		TEST_METHOD(TagDeleteCheck)
		{//id = 6
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");
			e.addTag("final tag");
			e.removeTag("nextTag");
			e.removeTag("noexisttag");
			auto tags = e.getTags();
			Assert::AreEqual(2, (int)tags.size());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "final tag")!=tags.end());
		}
	};
}<commit_msg>[DB] Test changes<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace EffiData_Test
{
	TEST_CLASS(EffiData_Test)
	{
	protected:
		streambuf * oldStdoutBuf;
		stringstream consoleOutput;
		string consoleDump(){
			std::istreambuf_iterator<char> eos;
			std::string sout(std::istreambuf_iterator<char>(consoleOutput), eos);
			return sout;
		}
	public:
		//Redirect cout.
		TEST_METHOD_INITIALIZE(pre) {
			oldStdoutBuf = std::cout.rdbuf();
			std::cout.rdbuf(consoleOutput.rdbuf());
		}

		//Restore redirect cout
		TEST_METHOD_CLEANUP(post)
		{
			std::cout.rdbuf(oldStdoutBuf);
		}

		TEST_METHOD(BasicPrintCheck)
		{//id = 1
			Event e("test event");
			string expected = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"1\",\n"
			"    \"priority\": \"5\",\n"
			"    \"tags\": \"\",\n" //Should be [], but boost property tree doesn't support it.
			"    \"complete\": \"false\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			Assert::AreEqual(expected, result);
		}

		//WARNING: DO NOT RE-ORDER TESTS. ADD TO THE END.
		TEST_METHOD(TagCheck)
		{//id = 2
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");

			auto tags = e.getTags();
			Assert::AreEqual(2, (int)tags.size());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "nextTag")!=tags.end());
		}

		TEST_METHOD(TagPrintCheck)
		{ //id = 3
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			std::string expected = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"3\",\n"
			"    \"priority\": \"5\",\n"
			"    \"tags\": [\n"
			"        \"tag 1\",\n"
			"        \"nextTag\"\n"
			"    ],\n"
			"    \"complete\": \"false\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			Assert::AreEqual(expected, result);

		}

		TEST_METHOD(IDIncrementCheck)
		{ //id = 4,5
			Event e("test event");
			Event e2("test event");
			Assert::AreEqual(e.getId() +1 ,e2.getId());
		}

		TEST_METHOD(InputTest)
		{ //id=6.
			string contents = "{\n"
			"    \"name\": \"test event\",\n"
			"    \"id\": \"40\",\n"
			"    \"priority\": \"3\",\n"
			"    \"tags\": \"\",\n"
			"    \"complete\": \"true\",\n"
			"    \"start\": \"0\",\n"
			"    \"end\": \"0\",\n"
			"    \"parent\": \"0\",\n"
			"    \"content\": \"0\"\n"
			"}\n";
			Event e("");
			stringstream ss;
			ss.str(contents);
			ss>>e;
			std::cout<<e;
			string result = consoleDump();
			Logger::WriteMessage(result.c_str());
			Assert::AreEqual(contents, result);
		}

		TEST_METHOD(TagDeleteCheck)
		{//id = 6
			Event e("test event");
			e.addTag("tag 1");
			e.addTag("nextTag");
			e.addTag("final tag");
			e.removeTag("nextTag");
			e.removeTag("noexisttag");
			auto tags = e.getTags();
			Assert::AreEqual(2, (int)tags.size());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end());
			Assert::IsTrue(std::find(tags.begin(), tags.end(), "final tag")!=tags.end());
		}
	};
}<|endoftext|>