<commit_before>#include "LoginScreen.h"

LoginScreen::LoginScreen() :
    _button("Login"),
    _password("Password", (juce::juce_wchar) 0x2022),
    _skipButton("Skip")
{
    _logger = &Poco::Logger::get("subutai");
    auto font = Font("Encode Sans", 17, 1);
    auto fontVersion = juce::Font("Encode Sans", 15, 1);
    addAndMakeVisible(_login);
    _login.setBounds(10, 50, 180, 24);
    _login.setColour(juce::TextEditor::outlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setColour(juce::TextEditor::backgroundColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setColour(juce::TextEditor::focusedOutlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setFont(font);
    _login.setText("");

    addAndMakeVisible(_password);
    _password.setBounds(10, 85, 180, 24);
    _password.setColour(juce::TextEditor::outlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setColour(juce::TextEditor::backgroundColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setColour(juce::TextEditor::focusedOutlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setFont(font);
    _password.setText("");

    addAndMakeVisible(_button);
    _button.addListener(this);
    _button.setBounds(10, 105, 180, 24);

    addAndMakeVisible(_skipButton);
    _skipButton.addListener(this);

    std::string pLogoFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "launcher-logo.png");
    std::string pUserFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "user.png");
    std::string pPassFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "password.png");

    Poco::File pLogo(pLogoFile);
    if (pLogo.exists())
    {
        _logo.setImage(juce::ImageCache::getFromFile(juce::File(pLogoFile)));
    }
    else
    {
        _logger->error("launcher-logo.png doesn't exists");
    }
    addAndMakeVisible(_logo);

    Poco::File pUser(pUserFile);
    if (pUser.exists())
    {
        _userIcon.setImage(juce::ImageCache::getFromFile(juce::File(pUserFile)));
    }
    else
    {
        _logger->error("user.png doesn't exists");
    }
    addAndMakeVisible(_userIcon);

    Poco::File pPass(pPassFile);
    if (pPass.exists())
    {
        _passwordIcon.setImage(juce::ImageCache::getFromFile(juce::File(pPassFile)));
    }
    else
    {
        _logger->error("password.png doesn't exists");
    }
    addAndMakeVisible(_passwordIcon);

    auto linkFont = juce::Font("Encode Sans", 14, 0);
    _resetLink.setURL(URL("https://hub.subut.ai/account-recovery"));
    _resetLink.setFont(linkFont, false);
    _resetLink.setButtonText("Reset Password");
    _resetLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 300, 200, 20);

    _registerLink.setURL(URL("https://hub.subut.ai/register"));
    _registerLink.setFont(linkFont, false);
    _registerLink.setButtonText("Create Account");
    _registerLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 300, 200, 20);

    addAndMakeVisible(_resetLink);
    addAndMakeVisible(_registerLink);

    _title.setText("Subutai Launcher", dontSendNotification);
    _title.setColour(Label::textColourId, juce::Colour(105, 116, 144));
    _title.setBounds(0, 110, 250, 25);
    _title.setFont(font);
    _title.setJustificationType(Justification::centred);
    addAndMakeVisible(_title);

    _version.setText("Version 5.0.0", dontSendNotification);
    _version.setColour(Label::textColourId, juce::Colour(105, 116, 144));
    _version.setBounds(0, 130, 250, 25);
    _version.setFont(fontVersion);
    _version.setJustificationType(Justification::centred);
    addAndMakeVisible(_version);

    _error.setText("Email or password is invalid", dontSendNotification);
    _error.setColour(Label::textColourId, juce::Colours::red);
    _error.setBounds(0, 0, 0, 0);
    _error.setFont(font);
    _error.setJustificationType(Justification::centred);
    addChildComponent(_error);
}

LoginScreen::~LoginScreen()
{

}

void LoginScreen::paint(juce::Graphics& g)
{
    g.fillAll(juce::Colour::fromRGB(247, 249, 252));
    g.setColour(juce::Colour::fromRGB(101, 117, 141));
    g.drawLine(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 252, getWidth() / 2 + (INPUT_FIELD_WIDTH / 2), 252, 2);
    g.drawLine(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 302, getWidth() / 2 + (INPUT_FIELD_WIDTH / 2), 302, 2);
}

void LoginScreen::resized()
{
    int pLogoWidth = 64;
    int pLogoHeight = 64;
    pLogoWidth = _logo.getImage().getWidth();
    pLogoHeight = _logo.getImage().getHeight();
    _error.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 190, INPUT_FIELD_WIDTH, 30);
    _login.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 220, INPUT_FIELD_WIDTH, 30);
    _password.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 270, INPUT_FIELD_WIDTH, 30);
    _logo.setBounds(getWidth() / 2 - pLogoWidth + 30, 40, pLogoWidth, pLogoHeight);
    _userIcon.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2) - 30, 230, 20, 20);
    _passwordIcon.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2) - 30, 280, 20, 20);
    _button.setBounds(getWidth() / 2 - (_button.getWidth() / 2), 320, _button.getWidth(), 24);
    _registerLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 375, 200, 20);
    _resetLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 395, 200, 20);
    _title.setBounds(getWidth() / 2 - 150, 110, 300, 25);
    _version.setBounds(getWidth() / 2 - 150, 130, 300, 25);
    _skipButton.setBounds(getWidth() - _skipButton.getWidth() - 20, getHeight() - 44, _skipButton.getWidth(), 24);
}

void LoginScreen::buttonClicked(juce::Button* button)
{
    if (button == &_button)
    {
        _button.setEnabled(false);
        _error.setVisible(false);
        // Loggin user in
        SubutaiLauncher::Hub* _pHub = SubutaiLauncher::Session::instance()->getHub();
        _pHub->setLogin(_login.getText().toStdString());
        _pHub->setPassword(_password.getText().toStdString());
        bool rc = _pHub->auth();
        if (rc)
        {
            setVisible(false);
        }
        else
        {
            _error.setVisible(true);
            _button.setEnabled(true);
        }
    }
    else if (button == &_skipButton)
    {
        juce::String title = "Skip login?";
        juce::String message = "Although optional, we highly recommend logging into your Hub account to track the installation process due to several advantages:\n\n" \
        "1.    Every system's hardware resources are different. Each fits into a specific resource grade. The resource grades are important for resource comparison and your peer's reputation. Resource grade determination takes place at installation time and is associated with your peer on the Hub.\n" \
        "2.    Every software configuration is different and several problems may result. Logging these from cradle to grave with analytics help to automatically determine better installation options during installation and afterwards for maintenance. Having a cradle to grave view of your peer and client configuration is key.\n" \
        "3.    This information helps us to provide better options and services for you and others that might use your resources. It helps to improve the overall system.\n\n" \
        "Only the resource grade (A-F) of your peer and its resource hosts are made available on the Hub if and only if you choose to make your peer visible to friends or the public. Besides this information, all the installation logs are deemed private information associated with your peer. In no way shape or form will it be shared or sold to any other entity. Please see our privacy bylaws on the Optimal Dynamics website.";

        if (NativeMessageBox::showOkCancelBox(AlertWindow::QuestionIcon, title,
                    message, nullptr, nullptr)) {
            setVisible(false);
        }
    }
}

<commit_msg>Fixed #196. Create account button now leads to a proper domain<commit_after>#include "LoginScreen.h"

LoginScreen::LoginScreen() :
    _button("Login"),
    _password("Password", (juce::juce_wchar) 0x2022),
    _skipButton("Skip")
{
    _logger = &Poco::Logger::get("subutai");
    auto font = Font("Encode Sans", 17, 1);
    auto fontVersion = juce::Font("Encode Sans", 15, 1);
    addAndMakeVisible(_login);
    _login.setBounds(10, 50, 180, 24);
    _login.setColour(juce::TextEditor::outlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setColour(juce::TextEditor::backgroundColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setColour(juce::TextEditor::focusedOutlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _login.setFont(font);
    _login.setText("");

    addAndMakeVisible(_password);
    _password.setBounds(10, 85, 180, 24);
    _password.setColour(juce::TextEditor::outlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setColour(juce::TextEditor::backgroundColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setColour(juce::TextEditor::focusedOutlineColourId, juce::Colour::fromRGB(247, 249, 252));
    _password.setFont(font);
    _password.setText("");

    addAndMakeVisible(_button);
    _button.addListener(this);
    _button.setBounds(10, 105, 180, 24);

    addAndMakeVisible(_skipButton);
    _skipButton.addListener(this);

    std::string pLogoFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "launcher-logo.png");
    std::string pUserFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "user.png");
    std::string pPassFile(SubutaiLauncher::Session::instance()->getSettings()->getTmpPath() + "password.png");

    Poco::File pLogo(pLogoFile);
    if (pLogo.exists())
    {
        _logo.setImage(juce::ImageCache::getFromFile(juce::File(pLogoFile)));
    }
    else
    {
        _logger->error("launcher-logo.png doesn't exists");
    }
    addAndMakeVisible(_logo);

    Poco::File pUser(pUserFile);
    if (pUser.exists())
    {
        _userIcon.setImage(juce::ImageCache::getFromFile(juce::File(pUserFile)));
    }
    else
    {
        _logger->error("user.png doesn't exists");
    }
    addAndMakeVisible(_userIcon);

    Poco::File pPass(pPassFile);
    if (pPass.exists())
    {
        _passwordIcon.setImage(juce::ImageCache::getFromFile(juce::File(pPassFile)));
    }
    else
    {
        _logger->error("password.png doesn't exists");
    }
    addAndMakeVisible(_passwordIcon);

    auto linkFont = juce::Font("Encode Sans", 14, 0);
    _resetLink.setURL(URL("https://hub.subut.ai/account-recovery"));
    _resetLink.setFont(linkFont, false);
    _resetLink.setButtonText("Reset Password");
    _resetLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 300, 200, 20);

    _registerLink.setURL(URL("https://"+SubutaiLauncher::Hub::URL+"/register"));
    _registerLink.setFont(linkFont, false);
    _registerLink.setButtonText("Create Account");
    _registerLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 300, 200, 20);

    addAndMakeVisible(_resetLink);
    addAndMakeVisible(_registerLink);

    _title.setText("Subutai Launcher", dontSendNotification);
    _title.setColour(Label::textColourId, juce::Colour(105, 116, 144));
    _title.setBounds(0, 110, 250, 25);
    _title.setFont(font);
    _title.setJustificationType(Justification::centred);
    addAndMakeVisible(_title);

    _version.setText("Version 5.0.0", dontSendNotification);
    _version.setColour(Label::textColourId, juce::Colour(105, 116, 144));
    _version.setBounds(0, 130, 250, 25);
    _version.setFont(fontVersion);
    _version.setJustificationType(Justification::centred);
    addAndMakeVisible(_version);

    _error.setText("Email or password is invalid", dontSendNotification);
    _error.setColour(Label::textColourId, juce::Colours::red);
    _error.setBounds(0, 0, 0, 0);
    _error.setFont(font);
    _error.setJustificationType(Justification::centred);
    addChildComponent(_error);
}

LoginScreen::~LoginScreen()
{

}

void LoginScreen::paint(juce::Graphics& g)
{
    g.fillAll(juce::Colour::fromRGB(247, 249, 252));
    g.setColour(juce::Colour::fromRGB(101, 117, 141));
    g.drawLine(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 252, getWidth() / 2 + (INPUT_FIELD_WIDTH / 2), 252, 2);
    g.drawLine(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 302, getWidth() / 2 + (INPUT_FIELD_WIDTH / 2), 302, 2);
}

void LoginScreen::resized()
{
    int pLogoWidth = 64;
    int pLogoHeight = 64;
    pLogoWidth = _logo.getImage().getWidth();
    pLogoHeight = _logo.getImage().getHeight();
    _error.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 190, INPUT_FIELD_WIDTH, 30);
    _login.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 220, INPUT_FIELD_WIDTH, 30);
    _password.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 270, INPUT_FIELD_WIDTH, 30);
    _logo.setBounds(getWidth() / 2 - pLogoWidth + 30, 40, pLogoWidth, pLogoHeight);
    _userIcon.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2) - 30, 230, 20, 20);
    _passwordIcon.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2) - 30, 280, 20, 20);
    _button.setBounds(getWidth() / 2 - (_button.getWidth() / 2), 320, _button.getWidth(), 24);
    _registerLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 375, 200, 20);
    _resetLink.setBounds(getWidth() / 2 - (INPUT_FIELD_WIDTH / 2), 395, 200, 20);
    _title.setBounds(getWidth() / 2 - 150, 110, 300, 25);
    _version.setBounds(getWidth() / 2 - 150, 130, 300, 25);
    _skipButton.setBounds(getWidth() - _skipButton.getWidth() - 20, getHeight() - 44, _skipButton.getWidth(), 24);
}

void LoginScreen::buttonClicked(juce::Button* button)
{
    if (button == &_button)
    {
        _button.setEnabled(false);
        _error.setVisible(false);
        // Loggin user in
        SubutaiLauncher::Hub* _pHub = SubutaiLauncher::Session::instance()->getHub();
        _pHub->setLogin(_login.getText().toStdString());
        _pHub->setPassword(_password.getText().toStdString());
        bool rc = _pHub->auth();
        if (rc)
        {
            setVisible(false);
        }
        else
        {
            _error.setVisible(true);
            _button.setEnabled(true);
        }
    }
    else if (button == &_skipButton)
    {
        juce::String title = "Skip login?";
        juce::String message = "Although optional, we highly recommend logging into your Hub account to track the installation process due to several advantages:\n\n" \
        "1.    Every system's hardware resources are different. Each fits into a specific resource grade. The resource grades are important for resource comparison and your peer's reputation. Resource grade determination takes place at installation time and is associated with your peer on the Hub.\n" \
        "2.    Every software configuration is different and several problems may result. Logging these from cradle to grave with analytics help to automatically determine better installation options during installation and afterwards for maintenance. Having a cradle to grave view of your peer and client configuration is key.\n" \
        "3.    This information helps us to provide better options and services for you and others that might use your resources. It helps to improve the overall system.\n\n" \
        "Only the resource grade (A-F) of your peer and its resource hosts are made available on the Hub if and only if you choose to make your peer visible to friends or the public. Besides this information, all the installation logs are deemed private information associated with your peer. In no way shape or form will it be shared or sold to any other entity. Please see our privacy bylaws on the Optimal Dynamics website.";

        if (NativeMessageBox::showOkCancelBox(AlertWindow::QuestionIcon, title,
                    message, nullptr, nullptr)) {
            setVisible(false);
        }
    }
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include "AliVZERODataDCS.h"

#include "AliDCSValue.h"
#include "AliLog.h"

#include "TGraph.h"
#include "TAxis.h"
#include "TCanvas.h"
#include "TTimeStamp.h"
#include "TMap.h"

class TH2;
class AliCDBMetaData;
class TDatime;

// AliVZERODataDCS class
// main aim to introduce the aliases for the VZERO DCS
// data points to be then
// stored in the OCDB, and to process them.
// ProcessData() method called by VZEROPreprocessor

ClassImp(AliVZERODataDCS)

//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS():
	TObject(),
	fRun(0),
	fStartTime(0),
	fEndTime(0),
        fGraphs("TGraph",kNGraphs),
	fIsProcessed(kFALSE)
{
  // Default constructor
}

//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS(Int_t nRun, UInt_t startTime, UInt_t endTime):
	TObject(),
	fRun(nRun),
	fStartTime(startTime),
	fEndTime(endTime),
        fGraphs("TGraph",kNGraphs),
	fIsProcessed(kFALSE)
{

  // constructor with arguments

	AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", nRun,
	TTimeStamp(startTime).AsString(),
	TTimeStamp(endTime).AsString()));

	Init();

}

//_____________________________________________________________________________
AliVZERODataDCS::~AliVZERODataDCS() {

  // destructor
  fGraphs.Clear("C");

}

//_____________________________________________________________________________
void AliVZERODataDCS::ProcessData(TMap& aliasMap){

  // method to process the data

  if(!(fAliasNames[0])) Init();

  TObjArray *aliasArr;
  AliDCSValue* aValue;

  // starting loop on aliases
  for(int iAlias=0; iAlias<kNAliases; iAlias++){

    aliasArr = (TObjArray*) aliasMap.GetValue(fAliasNames[iAlias].Data());
    if(!aliasArr){
      AliError(Form("Alias %s not found!", fAliasNames[iAlias].Data()));
      return;
    }

    Introduce(iAlias, aliasArr);

    if(aliasArr->GetEntries()<2){
      AliError(Form("Alias %s has just %d entries!",
		    fAliasNames[iAlias].Data(),aliasArr->GetEntries()));
      continue;
    }

    TIter iterarray(aliasArr);

    Int_t nentries = aliasArr->GetEntries();

    Double_t *Times = new Double_t[nentries];
    Double_t *Values = new Double_t[nentries];

    UInt_t iValue=0;
    while((aValue = (AliDCSValue*) iterarray.Next())) {
   		Values[iValue] = aValue->GetFloat();
   		Times[iValue] = (Double_t) (aValue->GetTimeStamp());
		fHv[iAlias]->Fill(Values[iValue]);
   		iValue++;
    }
    CreateGraph(iAlias, aliasArr->GetEntries(), Times, Values); // fill graphs

    delete[] Values;
    delete[] Times;
  }

  	// calculate mean and rms of the first two histos
	for(int i=0;i<kNAliases;i++){
		fMeanHV[i] = fHv[i]->GetMean();
		fWidthHV[i] = fHv[i]->GetRMS();
	}

  fIsProcessed=kTRUE;
}

//_____________________________________________________________________________
void AliVZERODataDCS::Init(){

  // initialization of aliases and DCS data

  TString sindex;
  int iAlias = 0;

  for(int iSide = 0; iSide<2 ; iSide++){
  	for(int iRing = 0; iRing<4 ; iRing++){
  		for(int iSector = 0; iSector<8 ; iSector++){
  			if(iSide == 0) fAliasNames[iAlias] = "V00/HV/V0A/SECTOR";
  			else fAliasNames[iAlias] = "V00/HV/V0C/SECTOR";
			sindex.Form("%d/RING%d",iSector,iRing);
			fAliasNames[iAlias] += sindex;

			fHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);
			fHv[iAlias]->GetXaxis()->SetTitle("Hv");
			iAlias++;
  		}
  	}
  }
  if(iAlias!=kNAliases)
  	      AliError(Form("Number of DCS Aliases defined not correct"));

}

//_____________________________________________________________________________
void AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const
{

  // method to introduce new aliases

  int entries=aliasArr->GetEntries();
  AliInfo(Form("************ Alias: %s **********",fAliasNames[numAlias].Data()));
  AliInfo(Form("    	%d DP values collected",entries));

}

//_____________________________________________________________________________
void AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)
{

   // Create graphics

   TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);

   gr->GetXaxis()->SetTimeDisplay(1);
   gr->SetTitle(fAliasNames[i].Data());

   AliInfo(Form("Array entries: %d",fGraphs.GetEntriesFast()));

}

//_____________________________________________________________________________
void AliVZERODataDCS::Draw(const Option_t* /*option*/)
{
// Draw all histos and graphs

  if(!fIsProcessed) return;

  if(fGraphs.GetEntries()==0)  return;

  TString CanvasName;
  TCanvas *cHV[8];

  for(int iSide = 0 ;iSide<2;iSide++){
  	for(int iRing=0;iRing<4;iRing++){
  		if(iSide == 0)  CanvasName = "V0A_Ring";
  		else  CanvasName = "V0C_Ring";
  		CanvasName += iRing;
  		int iCanvas = iSide*4 + iRing;
  		cHV[iCanvas] = new TCanvas(CanvasName,CanvasName);
  		cHV[iCanvas]->Divide(3,3);
  		for(int iSector=0;iSector<8;iSector++){
  			cHV[iCanvas]->cd(iSector+1);
  			int iChannel = iSide*32 + iRing*8 + iSector;
  			((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);
  			((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw("ALP");

  		}

  	}
  }

}

<commit_msg>Conversion of DCS mapping to aliroot mapping<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include "AliVZERODataDCS.h"

#include "AliDCSValue.h"
#include "AliLog.h"

#include "TGraph.h"
#include "TAxis.h"
#include "TCanvas.h"
#include "TTimeStamp.h"
#include "TMap.h"

class TH2;
class AliCDBMetaData;
class TDatime;

// AliVZERODataDCS class
// main aim to introduce the aliases for the VZERO DCS
// data points to be then
// stored in the OCDB, and to process them.
// ProcessData() method called by VZEROPreprocessor

ClassImp(AliVZERODataDCS)

//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS():
	TObject(),
	fRun(0),
	fStartTime(0),
	fEndTime(0),
        fGraphs("TGraph",kNGraphs),
	fIsProcessed(kFALSE)
{
  // Default constructor
}

//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS(Int_t nRun, UInt_t startTime, UInt_t endTime):
	TObject(),
	fRun(nRun),
	fStartTime(startTime),
	fEndTime(endTime),
        fGraphs("TGraph",kNGraphs),
	fIsProcessed(kFALSE)
{

  // constructor with arguments

	AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", nRun,
	TTimeStamp(startTime).AsString(),
	TTimeStamp(endTime).AsString()));

	Init();

}

//_____________________________________________________________________________
AliVZERODataDCS::~AliVZERODataDCS() {

  // destructor
  fGraphs.Clear("C");

}

//_____________________________________________________________________________
void AliVZERODataDCS::ProcessData(TMap& aliasMap){

  // method to process the data

  if(!(fAliasNames[0])) Init();

  TObjArray *aliasArr;
  AliDCSValue* aValue;

  // starting loop on aliases
  for(int iAlias=0; iAlias<kNAliases; iAlias++){

    aliasArr = (TObjArray*) aliasMap.GetValue(fAliasNames[iAlias].Data());
    if(!aliasArr){
      AliError(Form("Alias %s not found!", fAliasNames[iAlias].Data()));
      return;
    }

    Introduce(iAlias, aliasArr);

    if(aliasArr->GetEntries()<2){
      AliError(Form("Alias %s has just %d entries!",
		    fAliasNames[iAlias].Data(),aliasArr->GetEntries()));
      continue;
    }

    TIter iterarray(aliasArr);

    Int_t nentries = aliasArr->GetEntries();

    Double_t *Times = new Double_t[nentries];
    Double_t *Values = new Double_t[nentries];

    UInt_t iValue=0;
    while((aValue = (AliDCSValue*) iterarray.Next())) {
   		Values[iValue] = aValue->GetFloat();
   		Times[iValue] = (Double_t) (aValue->GetTimeStamp());
		fHv[iAlias]->Fill(Values[iValue]);
   		iValue++;
    }
    CreateGraph(iAlias, aliasArr->GetEntries(), Times, Values); // fill graphs

    delete[] Values;
    delete[] Times;
  }

  	// calculate mean and rms of the first two histos
	// and convert index to aliroot channel
	for(int i=0;i<kNAliases;i++){
	        Int_t iChannel     = GetOfflineChannel(i);
		fMeanHV[iChannel]  = fHv[i]->GetMean();
		fWidthHV[iChannel] = fHv[i]->GetRMS();
	}

  fIsProcessed=kTRUE;
}

//_____________________________________________________________________________
void AliVZERODataDCS::Init(){

  // initialization of aliases and DCS data

  TString sindex;
  int iAlias = 0;

  for(int iSide = 0; iSide<2 ; iSide++){
  	for(int iRing = 0; iRing<4 ; iRing++){
  		for(int iSector = 0; iSector<8 ; iSector++){
  			if(iSide == 0) fAliasNames[iAlias] = "V00/HV/V0A/SECTOR";
  			else fAliasNames[iAlias] = "V00/HV/V0C/SECTOR";
			sindex.Form("%d/RING%d",iSector,iRing);
			fAliasNames[iAlias] += sindex;

			fHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);
			fHv[iAlias]->GetXaxis()->SetTitle("Hv");
			iAlias++;
  		}
  	}
  }
  if(iAlias!=kNAliases)
  	      AliError(Form("Number of DCS Aliases defined not correct"));

}

//_____________________________________________________________________________
void AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const
{

  // method to introduce new aliases

  int entries=aliasArr->GetEntries();
  AliInfo(Form("************ Alias: %s **********",fAliasNames[numAlias].Data()));
  AliInfo(Form("    	%d DP values collected",entries));

}

//_____________________________________________________________________________
void AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)
{

   // Create graphics

   TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);

   gr->GetXaxis()->SetTimeDisplay(1);
   gr->SetTitle(fAliasNames[i].Data());

   AliInfo(Form("Array entries: %d",fGraphs.GetEntriesFast()));

}

//_____________________________________________________________________________
void AliVZERODataDCS::Draw(const Option_t* /*option*/)
{
// Draw all histos and graphs

  if(!fIsProcessed) return;

  if(fGraphs.GetEntries()==0)  return;

  TString CanvasName;
  TCanvas *cHV[8];

  for(int iSide = 0 ;iSide<2;iSide++){
  	for(int iRing=0;iRing<4;iRing++){
  		if(iSide == 0)  CanvasName = "V0A_Ring";
  		else  CanvasName = "V0C_Ring";
  		CanvasName += iRing;
  		int iCanvas = iSide*4 + iRing;
  		cHV[iCanvas] = new TCanvas(CanvasName,CanvasName);
  		cHV[iCanvas]->Divide(3,3);
  		for(int iSector=0;iSector<8;iSector++){
  			cHV[iCanvas]->cd(iSector+1);
  			int iChannel = iSide*32 + iRing*8 + iSector;
  			((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);
  			((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw("ALP");

  		}

  	}
  }

}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WebCorePrefix.h"
<commit_msg>Touch precompiled header wrapper to try and fix build.<commit_after>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WebCorePrefix.h"

<|endoftext|>


<commit_before>#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
  return true;
}
<commit_msg>Add status echo to PPG node for debug<commit_after>#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ROS_INFO("Ready. getPostureKey");
  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  ROS_INFO("Get map of patterns parent");
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
    ROS_INFO(std::string("Found posture of ").append(it->second).c_str());
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
  return true;
}
<|endoftext|>


<commit_before> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EApi.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:28:19 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#include <rtl/ustring.hxx>
#include <osl/module.h>
#include <stdio.h>
#define  DECLARE_FN_POINTERS 1
#ifndef _CONNECTIVITY_EVOAB_EVOLUTION_API_HXX_
#include "EApi.h"
#endif
static char *eBookLibNames[] = {
    "libebook-1.2.so.9", // evolution-2.8
    "libebook-1.2.so.5", // evolution-2.4 and 2.6+
    "libebook-1.2.so.3", // evolution-2.2
    "libebook.so.8"      // evolution-2.0
};

typedef void (*SymbolFunc) (void);

#define SYM_MAP(a) { #a, (SymbolFunc *)&a }
    static struct {
    const char *sym_name;
    SymbolFunc *ref_value;
    } aApiMap[] = {
    SYM_MAP( e_contact_field_name ),
    SYM_MAP( e_contact_get ),
    SYM_MAP( e_contact_get_type ),
    SYM_MAP( e_contact_field_id ),
    SYM_MAP( e_source_peek_name ),
    SYM_MAP( e_source_get_property ),
    SYM_MAP( e_source_list_peek_groups ),
    SYM_MAP( e_source_group_peek_sources ),
    SYM_MAP( e_book_new ),
    SYM_MAP( e_book_open ),
    SYM_MAP( e_book_get_uri ),
    SYM_MAP( e_book_get_source ),
    SYM_MAP( e_book_get_addressbooks ),
    SYM_MAP( e_book_get_contacts ),
    SYM_MAP( e_book_authenticate_user ),
    SYM_MAP( e_book_query_field_test ),
    SYM_MAP( e_book_query_and ),
    SYM_MAP( e_book_query_or ),
    SYM_MAP( e_book_query_not ),
    SYM_MAP( e_book_query_unref ),
    SYM_MAP( e_book_query_from_string ),
    SYM_MAP( e_book_query_to_string ),
    SYM_MAP( e_book_query_field_exists ),
    SYM_MAP( e_source_group_peek_base_uri)
    };
#undef SYM_MAP

static bool
tryLink( oslModule &aModule, const char *pName )
{
    for( guint i = 0; i < G_N_ELEMENTS( aApiMap ); i++ )
    {
    SymbolFunc aMethod;
    aMethod = (SymbolFunc) osl_getSymbol
        ( aModule, rtl::OUString::createFromAscii ( aApiMap[ i ].sym_name ).pData );
    if( !aMethod )
    {
        fprintf( stderr, "Warning: missing symbol '%s' in '%s'",
             aApiMap[ i ].sym_name, pName );
        return false;
    }
    * aApiMap[ i ].ref_value = aMethod;
    }
    return true;
}

bool EApiInit()
{
    oslModule aModule;

    for( guint j = 0; j < G_N_ELEMENTS( eBookLibNames ); j++ )
    {
        aModule = osl_loadModule( rtl::OUString::createFromAscii
                                  ( eBookLibNames[ j ] ).pData,
                                  SAL_LOADMODULE_DEFAULT );
        if( aModule)
        {
            if ( tryLink( aModule, eBookLibNames[ j ] ) )
                return true;
            osl_unloadModule( aModule );
        }
    }
    fprintf( stderr, "Can find no compliant libebook client libraries\n" );
    return false;
}

#if 0

/*
 * Test code - enable &
 *
 * Compile with ( after source LinuxIntelEnv.Set.sh )
   gcc $SOLARDEF -I $SOLARVER/$UPD/$INPATH/inc \
     -I. `pkg-config --cflags --libs gobject-2.0` \
     -L $SOLARVER/$UPD/$INPATH/lib -luno_sal -lstdc++ EApi.cxx
 */

int main( int argc, char **argv)
{
    return EApiInit();
}

#endif

<commit_msg>INTEGRATION: CWS ause069 (1.6.16); FILE MERGED 2006/12/19 14:43:11 hjs 1.6.16.1: #i58881# just a comment...<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EApi.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-25 13:46:54 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#include <rtl/ustring.hxx>
#include <osl/module.h>
#include <stdio.h>
#define  DECLARE_FN_POINTERS 1
#ifndef _CONNECTIVITY_EVOAB_EVOLUTION_API_HXX_
#include "EApi.h"
#endif
static char *eBookLibNames[] = {
    "libebook-1.2.so.9", // evolution-2.8
    "libebook-1.2.so.5", // evolution-2.4 and 2.6+
    "libebook-1.2.so.3", // evolution-2.2
    "libebook.so.8"      // evolution-2.0
};

typedef void (*SymbolFunc) (void);

#define SYM_MAP(a) { #a, (SymbolFunc *)&a }
    static struct {
    const char *sym_name;
    SymbolFunc *ref_value;
    } aApiMap[] = {
    SYM_MAP( e_contact_field_name ),
    SYM_MAP( e_contact_get ),
    SYM_MAP( e_contact_get_type ),
    SYM_MAP( e_contact_field_id ),
    SYM_MAP( e_source_peek_name ),
    SYM_MAP( e_source_get_property ),
    SYM_MAP( e_source_list_peek_groups ),
    SYM_MAP( e_source_group_peek_sources ),
    SYM_MAP( e_book_new ),
    SYM_MAP( e_book_open ),
    SYM_MAP( e_book_get_uri ),
    SYM_MAP( e_book_get_source ),
    SYM_MAP( e_book_get_addressbooks ),
    SYM_MAP( e_book_get_contacts ),
    SYM_MAP( e_book_authenticate_user ),
    SYM_MAP( e_book_query_field_test ),
    SYM_MAP( e_book_query_and ),
    SYM_MAP( e_book_query_or ),
    SYM_MAP( e_book_query_not ),
    SYM_MAP( e_book_query_unref ),
    SYM_MAP( e_book_query_from_string ),
    SYM_MAP( e_book_query_to_string ),
    SYM_MAP( e_book_query_field_exists ),
    SYM_MAP( e_source_group_peek_base_uri)
    };
#undef SYM_MAP

static bool
tryLink( oslModule &aModule, const char *pName )
{
    for( guint i = 0; i < G_N_ELEMENTS( aApiMap ); i++ )
    {
    SymbolFunc aMethod;
    aMethod = (SymbolFunc) osl_getSymbol
        ( aModule, rtl::OUString::createFromAscii ( aApiMap[ i ].sym_name ).pData );
    if( !aMethod )
    {
        fprintf( stderr, "Warning: missing symbol '%s' in '%s'",
             aApiMap[ i ].sym_name, pName );
        return false;
    }
    * aApiMap[ i ].ref_value = aMethod;
    }
    return true;
}

bool EApiInit()
{
    oslModule aModule;

    for( guint j = 0; j < G_N_ELEMENTS( eBookLibNames ); j++ )
    {
        aModule = osl_loadModule( rtl::OUString::createFromAscii
                                  ( eBookLibNames[ j ] ).pData,
                                  SAL_LOADMODULE_DEFAULT );
        if( aModule)
        {
            if ( tryLink( aModule, eBookLibNames[ j ] ) )
                return true;
            osl_unloadModule( aModule );
        }
    }
    fprintf( stderr, "Can find no compliant libebook client libraries\n" );
    return false;
}

#if 0
// hjs: SOLARDEF does no longer exist please lookup the required
// defines in a regular compile line
/*
 * Test code - enable &
 *
 * Compile with ( after source LinuxIntelEnv.Set.sh )
   gcc $SOLARDEF -I $SOLARVER/$UPD/$INPATH/inc \
     -I. `pkg-config --cflags --libs gobject-2.0` \
     -L $SOLARVER/$UPD/$INPATH/lib -luno_sal -lstdc++ EApi.cxx
 */

int main( int argc, char **argv)
{
    return EApiInit();
}

#endif

<|endoftext|>


<commit_before>// BoostPythonTests.cpp : Defines the entry point for the console application.
//

#define BOOST_PYTHON_STATIC_LIB
#define BOOST_LIB_NAME "boost_numpy"
#include <boost/config/auto_link.hpp>
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>

namespace pycpp
{
	using namespace std;

	namespace py = boost::python;
	namespace np = boost::python::numpy;

	class PythonCpp
	{
	public:
		py::object main_module_;
		py::object main_namespace_;
		py::object builtins_;
		py::object sys_;
		py::object print_;

		PythonCpp(wchar_t* home_path = L"C:/Anaconda3/envs/py35tf1")
		{
			Py_SetPythonHome(home_path);

			Py_Initialize();
			np::initialize();

			main_module_ = py::import("__main__");
			main_namespace_ = main_module_.attr("__dict__");
			builtins_ = main_module_.attr("__builtins__");
			sys_ = py::import("sys");
			print_ = builtins_.attr("print");

		}

		string version() const
		{
			return py::extract<std::string>(sys_.attr("version"));
		}

		// let's simply use print_(...) because this makes compile overhead unnecessarily.
		// However, it's happy to see working.
		template<typename ... Args>
		void print(Args ... args) const
		{
			this->print_(args ...);
		}
	};

	class NumpyCpp
	{
	public:
		template<typename ... Args>
		static np::ndarray make_array(Args ... args)
		{
			return np::array(py::make_tuple(args ...));
		}
	};

	class TensorflowCpp
	{
	public:
		const py::object tf_ = py::import("tensorflow");

		template<typename ... Args>
		py::object constant(Args ... args)
		{
			return tf_.attr("constant")(args ...);
		}

		template<typename ... Args>
		py::object multiply(Args ... args)
		{
			return tf_.attr("multiply")(args ...);
		}

		template<typename ... Args>
		py::object Session(Args ... args)
		{
			return tf_.attr("Session")(args ...);
		}
	};
}

int main()
{
	using namespace pycpp;

	PythonCpp pyw;

	cout << pyw.version() << endl;

	pyw.print_("Hello, Python");
	pyw.print("Hello, Python", 1234, 1234 * 2);

	// examples from https://www.datacamp.com/community/tutorials/tensorflow-tutorial#gs.7CN1YdQ

	const np::ndarray d1 = pycpp::NumpyCpp::make_array(1.0f, 2.0f, 3.0f, 4.0f);
	const np::ndarray d2 = pycpp::NumpyCpp::make_array(5.0f, 6.0f, 7.0f, 8.0f);

	pyw.print(d1);
	pyw.print(d2);

	TensorflowCpp tfc;
	const auto x1 = tfc.constant(d1);
	const auto x2 = tfc.constant(d2);

	const auto mult = tfc.multiply(x1, x2);
	const auto sess = tfc.Session();
	const auto result = sess.attr("run")(mult); //TODO: run session to nodes, receive results as list.

	pyw.print(result);

    return 0;
}

<commit_msg>backp - testing node list to run.<commit_after>// BoostPythonTests.cpp : Defines the entry point for the console application.
//

#define BOOST_PYTHON_STATIC_LIB
#define BOOST_LIB_NAME "boost_numpy"
#include <boost/config/auto_link.hpp>
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>

namespace pycpp
{
	using namespace std;

	namespace py = boost::python;
	namespace np = boost::python::numpy;

	class PythonCpp
	{
	public:
		py::object main_module_;
		py::object main_namespace_;
		py::object builtins_;
		py::object sys_;
		py::object print_;

		PythonCpp(wchar_t* home_path = L"C:/Anaconda3/envs/py35tf1")
		{
			Py_SetPythonHome(home_path);

			Py_Initialize();
			np::initialize();

			main_module_ = py::import("__main__");
			main_namespace_ = main_module_.attr("__dict__");
			builtins_ = main_module_.attr("__builtins__");
			sys_ = py::import("sys");
			print_ = builtins_.attr("print");

		}

		string version() const
		{
			return py::extract<std::string>(sys_.attr("version"));
		}

		// let's simply use print_(...) because this makes compile overhead unnecessarily.
		// However, it's happy to see working.
		template<typename ... Args>
		void print(Args ... args) const
		{
			this->print_(args ...);
		}
	};

	class NumpyCpp
	{
	public:
		template<typename ... Args>
		static np::ndarray make_array(Args ... args)
		{
			return np::array(py::make_tuple(args ...));
		}
	};

	class TensorflowCpp
	{
	public:
		const py::object tf_ = py::import("tensorflow");
		const py::object sess_ = tf_.attr("Session")();

		template<typename ... Args>
		py::object run(Args ... args)
		{
			return sess_.attr("run")(args ...);
		}

		template<typename ... Args>
		py::object add(Args ... args)
		{
			return tf_.attr("add")(args ...);
		}

		template<typename ... Args>
		py::object constant(Args ... args)
		{
			return tf_.attr("constant")(args ...);
		}

		template<typename ... Args>
		py::object multiply(Args ... args)
		{
			return tf_.attr("multiply")(args ...);
		}

		template<typename ... Args>
		py::object Session(Args ... args)
		{
			return tf_.attr("Session")(args ...);
		}
	};
}

int main()
{
	using namespace pycpp;

	PythonCpp pyw;

	cout << pyw.version() << endl;

	pyw.print_("Hello, Python");
	pyw.print("Hello, Python", 1234, 1234 * 2);

	// examples from https://www.datacamp.com/community/tutorials/tensorflow-tutorial#gs.7CN1YdQ

	const np::ndarray d1 = pycpp::NumpyCpp::make_array(1.0f, 2.0f, 3.0f, 4.0f);
	const np::ndarray d2 = pycpp::NumpyCpp::make_array(5.0f, 6.0f, 7.0f, 8.0f);

	pyw.print(d1);
	pyw.print(d2);

	TensorflowCpp tfc;
	const auto x1 = tfc.constant(d1);
	const auto x2 = tfc.constant(d2);

	const auto mult = tfc.multiply(x1, x2);
	pyw.print(mult);

	const auto add = tfc.add(x1, x2);
	pyw.print(add);

	auto result = tfc.run(mult);
	pyw.print("Mult result ", result);

	result = tfc.run(add);
	pyw.print("Add result ", result);

	py::list nodes;
	nodes.append(mult);
	nodes.append(add);

	//result = tfc.run(nodes);

	auto result_list = py::extract<py::list>(tfc.run(nodes));

	pyw.print(result_list);

    return 0;
}

<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "generator/affiliation.hpp"

#include "transit/world_feed/world_feed.hpp"

#include "platform/platform.hpp"

#include "base/assert.hpp"
#include "base/file_name_utils.hpp"
#include "base/string_utils.hpp"

#include <algorithm>
#include <string>
#include <utility>

namespace
{
// You can clone data from repo https://github.com/mapsme/world_feed_integration_tests_data
std::string const kFeedsSubdir = "world_feed_integration_tests_data";
}  // namespace

namespace transit
{
class WorldFeedIntegrationTests
{
public:
  WorldFeedIntegrationTests()
    : m_mwmMatcher(GetTestingOptions().m_resourcePath, false /* haveBordersForWholeWorld */)
    , m_globalFeed(m_generator, m_generatorEdges, m_colorPicker, m_mwmMatcher)
  {
    auto const & options = GetTestingOptions();

    GetPlatform().SetResourceDir(options.m_resourcePath);
    m_testPath = base::JoinPath(GetPlatform().WritableDir(), kFeedsSubdir);
    CHECK(GetPlatform().IsFileExistsByFullPath(m_testPath), ());

    m_generator = IdGenerator(base::JoinPath(m_testPath, "mapping.txt"));
    m_generatorEdges = IdGenerator(base::JoinPath(m_testPath, "mapping_edges.txt"));
  }

  void ReadMinimalisticFeed()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "minimalistic_feed"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 2, ());
    // We check that lines with no entries in stop_times.txt are not added.
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 7, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 2, ());
    // There are 2 lines with 3 and 4 stops correspondingly. So we have 5 edges.
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 5, ());
  }

  void ReadRealLifeFeed()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "real_life_feed"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 21, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 87, ());
    // All trips have unique service_id so each line corresponds to some trip.
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 392, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 1008, ());
    // 64 shapes contained in other shapes should be skipped.
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 329, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 3999, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 0, ());
  }

  void ReadFeedWithMultipleShapeProjections()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_multiple_shape_projections"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 27, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 2, ());
  }

  void ReadFeedWithWrongStopsOrder()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_wrong_stops_order"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    // Feed has wrong stops order (impossible for trip shape) and should be rejected.
    TEST(!m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());
  }

  void ReadFeedWithBackwardOrder()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_backward_order"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 2, ());
  }

  // Test for train itinerary that passes through 4 regions in Europe and consists of 4 stops
  // (each in separate mwm) and 1 route with 1 line. This line passes through 4 stops:
  // [1] Switzerland_Ticino -> [2] Switzerland_Eastern ->
  // [3] Italy_Lombardy_Como -> [4] Italy_Lombardy_Monza and Brianza
  void SplitFeedIntoMultipleRegions()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_long_itinerary"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 4, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 3, ());

    m_globalFeed.SplitFeedIntoRegions();

    size_t const mwmCount = 4;
    // We check that count of keys in each regions-to-ids mapping corresponds to the mwms count.
    TEST_EQUAL(m_globalFeed.m_splitting.m_networks.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_routes.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_lines.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_stops.size(), mwmCount, ());

    auto & stopsInRegions = m_globalFeed.m_splitting.m_stops;
    auto & edgesInRegions = m_globalFeed.m_splitting.m_edges;

    // First and last stops are connected through 1 edge with 1 nearest stop.
    // Stops in the middle are connected through 2 edges with 2 nearest stops.
    TEST_EQUAL(stopsInRegions["Switzerland_Ticino"].size(), 3, ());
    TEST_EQUAL(edgesInRegions["Switzerland_Ticino"].size(), 1, ());

    TEST_EQUAL(stopsInRegions["Switzerland_Eastern"].size(), 4, ());
    TEST_EQUAL(edgesInRegions["Switzerland_Eastern"].size(), 2, ());

    TEST_EQUAL(stopsInRegions["Italy_Lombardy_Como"].size(), 4, ());
    TEST_EQUAL(edgesInRegions["Italy_Lombardy_Como"].size(), 2, ());

    TEST_EQUAL(stopsInRegions["Italy_Lombardy_Monza and Brianza"].size(), 3, ());
    TEST_EQUAL(edgesInRegions["Italy_Lombardy_Monza and Brianza"].size(), 1, ());
  }

private:
  std::string m_testPath;
  IdGenerator m_generator;
  IdGenerator m_generatorEdges;
  transit::ColorPicker m_colorPicker;
  feature::CountriesFilesAffiliation m_mwmMatcher;
  WorldFeed m_globalFeed;
};

UNIT_CLASS_TEST(WorldFeedIntegrationTests, MinimalisticFeed)
{
  ReadMinimalisticFeed();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, RealLifeFeed)
{
  ReadRealLifeFeed();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithLongItinerary)
{
  SplitFeedIntoMultipleRegions();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithMultipleShapeProjections)
{
  ReadFeedWithMultipleShapeProjections();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithWrongStopsOrder)
{
  ReadFeedWithWrongStopsOrder();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithBackwardOrder)
{
  ReadFeedWithBackwardOrder();
}
}  // namespace transit
<commit_msg>[transit] Add integration test.<commit_after>#include "testing/testing.hpp"

#include "generator/affiliation.hpp"

#include "transit/world_feed/world_feed.hpp"

#include "platform/platform.hpp"

#include "base/assert.hpp"
#include "base/file_name_utils.hpp"
#include "base/string_utils.hpp"

#include <algorithm>
#include <string>
#include <utility>

namespace
{
// You can clone data from repo https://github.com/mapsme/world_feed_integration_tests_data
std::string const kFeedsSubdir = "world_feed_integration_tests_data";
}  // namespace

namespace transit
{
class WorldFeedIntegrationTests
{
public:
  WorldFeedIntegrationTests()
    : m_mwmMatcher(GetTestingOptions().m_resourcePath, false /* haveBordersForWholeWorld */)
    , m_globalFeed(m_generator, m_generatorEdges, m_colorPicker, m_mwmMatcher)
  {
    auto const & options = GetTestingOptions();

    GetPlatform().SetResourceDir(options.m_resourcePath);
    m_testPath = base::JoinPath(GetPlatform().WritableDir(), kFeedsSubdir);
    CHECK(GetPlatform().IsFileExistsByFullPath(m_testPath), ());

    m_generator = IdGenerator(base::JoinPath(m_testPath, "mapping.txt"));
    m_generatorEdges = IdGenerator(base::JoinPath(m_testPath, "mapping_edges.txt"));
  }

  void ReadMinimalisticFeed()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "minimalistic_feed"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 2, ());
    // We check that lines with no entries in stop_times.txt are not added.
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 7, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 2, ());
    // There are 2 lines with 3 and 4 stops correspondingly. So we have 5 edges.
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 5, ());
  }

  void ReadRealLifeFeed()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "real_life_feed"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 21, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 87, ());
    // All trips have unique service_id so each line corresponds to some trip.
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 392, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 1008, ());
    // 64 shapes contained in other shapes should be skipped.
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 329, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 3999, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 0, ());
  }

  void ReadRealLifeFeedWithoutShapes()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "real_life_feed_without_shapes"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), true /* generateTrivialShapes */), ());
    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 21, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 87, ());
    // All trips have unique service_id so each line corresponds to some trip.
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 390, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 1008, ());
    // 64 shapes contained in other shapes should be skipped.
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 286, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 3977, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 0, ());
  }

  void ReadFeedWithMultipleShapeProjections()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_multiple_shape_projections"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 27, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 2, ());
  }

  void ReadFeedWithWrongStopsOrder()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_wrong_stops_order"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    // Feed has wrong stops order (impossible for trip shape) and should be rejected.
    TEST(!m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());
  }

  void ReadFeedWithBackwardOrder()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_with_backward_order"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_networks.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_routes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_shapes.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_gates.m_data.size(), 0, ());
    TEST_EQUAL(m_globalFeed.m_transfers.m_data.size(), 2, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 16, ());
    TEST_EQUAL(m_globalFeed.m_edgesTransfers.m_data.size(), 2, ());
  }

  // Test for train itinerary that passes through 4 regions in Europe and consists of 4 stops
  // (each in separate mwm) and 1 route with 1 line. This line passes through 4 stops:
  // [1] Switzerland_Ticino -> [2] Switzerland_Eastern ->
  // [3] Italy_Lombardy_Como -> [4] Italy_Lombardy_Monza and Brianza
  void SplitFeedIntoMultipleRegions()
  {
    gtfs::Feed feed(base::JoinPath(m_testPath, "feed_long_itinerary"));
    TEST_EQUAL(feed.read_feed().code, gtfs::ResultCode::OK, ());
    TEST(m_globalFeed.SetFeed(std::move(feed), false /* generateTrivialShapes */), ());

    TEST_EQUAL(m_globalFeed.m_lines.m_data.size(), 1, ());
    TEST_EQUAL(m_globalFeed.m_stops.m_data.size(), 4, ());
    TEST_EQUAL(m_globalFeed.m_edges.m_data.size(), 3, ());

    m_globalFeed.SplitFeedIntoRegions();

    size_t const mwmCount = 4;
    // We check that count of keys in each regions-to-ids mapping corresponds to the mwms count.
    TEST_EQUAL(m_globalFeed.m_splitting.m_networks.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_routes.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_lines.size(), mwmCount, ());
    TEST_EQUAL(m_globalFeed.m_splitting.m_stops.size(), mwmCount, ());

    auto & stopsInRegions = m_globalFeed.m_splitting.m_stops;
    auto & edgesInRegions = m_globalFeed.m_splitting.m_edges;

    // First and last stops are connected through 1 edge with 1 nearest stop.
    // Stops in the middle are connected through 2 edges with 2 nearest stops.
    TEST_EQUAL(stopsInRegions["Switzerland_Ticino"].size(), 3, ());
    TEST_EQUAL(edgesInRegions["Switzerland_Ticino"].size(), 1, ());

    TEST_EQUAL(stopsInRegions["Switzerland_Eastern"].size(), 4, ());
    TEST_EQUAL(edgesInRegions["Switzerland_Eastern"].size(), 2, ());

    TEST_EQUAL(stopsInRegions["Italy_Lombardy_Como"].size(), 4, ());
    TEST_EQUAL(edgesInRegions["Italy_Lombardy_Como"].size(), 2, ());

    TEST_EQUAL(stopsInRegions["Italy_Lombardy_Monza and Brianza"].size(), 3, ());
    TEST_EQUAL(edgesInRegions["Italy_Lombardy_Monza and Brianza"].size(), 1, ());
  }

private:
  std::string m_testPath;
  IdGenerator m_generator;
  IdGenerator m_generatorEdges;
  transit::ColorPicker m_colorPicker;
  feature::CountriesFilesAffiliation m_mwmMatcher;
  WorldFeed m_globalFeed;
};

UNIT_CLASS_TEST(WorldFeedIntegrationTests, MinimalisticFeed)
{
  ReadMinimalisticFeed();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, RealLifeFeed)
{
  ReadRealLifeFeed();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, RealLifeFeedWithoutShapes)
{
  ReadRealLifeFeedWithoutShapes();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithLongItinerary)
{
  SplitFeedIntoMultipleRegions();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithMultipleShapeProjections)
{
  ReadFeedWithMultipleShapeProjections();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithWrongStopsOrder)
{
  ReadFeedWithWrongStopsOrder();
}

UNIT_CLASS_TEST(WorldFeedIntegrationTests, FeedWithBackwardOrder)
{
  ReadFeedWithBackwardOrder();
}
}  // namespace transit
<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdApplicationsBrowser.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ApplicationsBrowser

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
ApplicationsBrowser
::ApplicationsBrowser( QObject* parent ) :
  QObject( parent ),
  m_AutoLoadPath("")
{
}

/*******************************************************************************/
ApplicationsBrowser
::~ApplicationsBrowser()
{
}

/*******************************************************************************/
void
ApplicationsBrowser
::SetAutoLoadPath(const std::string & itk_auto_load_path)
{
  m_AutoLoadPath = itk_auto_load_path;

  //
  // add the path
  otb::Wrapper::ApplicationRegistry::AddApplicationPath(m_AutoLoadPath);
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetAvailableApplications()
{
  //
  // check if search path is not empty
  // TODO : throw exception to be catched by the catalog manager later
  if (m_AutoLoadPath.empty())
    {
    std::cerr << "ERROR: Search path is empty "<< std::endl;
    }

  //
  // get available application in search path
  StringVector appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications();

  //
  // some verbosity
  // TODO : remove this verbosity later
  if ( appList.size() == 0 )
    {
    std::cerr << "ERROR: Available modules : none." << std::endl;
    }
  else
    {
    std::cout << "--- Available modules :" << std::endl;
    for (StringVector::const_iterator it = appList.begin(); it != appList.end(); ++it)
      {
      std::cout << "\t" << *it << std::endl;
      }
    }

  return appList;
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetApplicationTags( const std::string& appName )
{
  //
  // output vector
  StringVector  vtags;

  //
  // instantiate the application using the factory
  otb::Wrapper::Application::Pointer application
    = otb::Wrapper::ApplicationRegistry::CreateApplication(appName);

  //
  // get tags
  if ( !application.IsNull() )
    {
    vtags = application->GetDocTags();
    }

  return vtags;
}

/*******************************************************************************/
void
ApplicationsBrowser
::SearchAvailableApplicationsTags()
{
  //
  // get all the applications in the search path
  StringVector vapp = GetAvailableApplications();

  //
  // loop on the applications to get tags
  ApplicationsTagContainer      outputContainer;
  StringVector::const_iterator  it = vapp.begin();

  while ( it != vapp.end() )
    {
    // get tags of current app
    StringVector ctags = GetApplicationTags( *it );

    // key will be the tag (easier for tree origanisation in )
    StringVector::const_iterator  itTag = ctags.begin();
    while ( itTag != ctags.end() )
      {

      // search for this tag in the output container
      ApplicationsTagContainer::iterator  pos = outputContainer.find( *itTag );
      if ( pos != outputContainer.end() )  // key found
        {
        //
        // add the application name (*it) as value for the current app tag
        (*pos).second.push_back(*it);
        }
      else
        {
        //
        // if tag not found in the container, add it
        std::pair< std::string, StringVector > currentAppTags;
        currentAppTags.first  = *itTag;
        currentAppTags.second.push_back( *it );
        outputContainer.insert( currentAppTags );
        }

      ++itTag;
      }

    ++it;
    }

  //
  // emit a signal with the ApplicationsTagContainer as
  // parameter
  emit AvailableApplicationsTagsChanged(outputContainer);
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>ENH: comment<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdApplicationsBrowser.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ApplicationsBrowser

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
ApplicationsBrowser
::ApplicationsBrowser( QObject* parent ) :
  QObject( parent ),
  m_AutoLoadPath("")
{
}

/*******************************************************************************/
ApplicationsBrowser
::~ApplicationsBrowser()
{
}

/*******************************************************************************/
void
ApplicationsBrowser
::SetAutoLoadPath(const std::string & itk_auto_load_path)
{
  m_AutoLoadPath = itk_auto_load_path;

  //
  // add the path
  otb::Wrapper::ApplicationRegistry::AddApplicationPath(m_AutoLoadPath);
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetAvailableApplications()
{
  //
  // check if search path is not empty
  // TODO : throw exception to be catched by the catalog manager later
  if (m_AutoLoadPath.empty())
    {
    std::cerr << "ERROR: Search path is empty "<< std::endl;
    }

  //
  // get available application in search path
  StringVector appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications();

  //
  // some verbosity
  // TODO : remove this verbosity later
  if ( appList.size() == 0 )
    {
    std::cerr << "ERROR: Available modules : none." << std::endl;
    }
  else
    {
    std::cout << "--- Available modules :" << std::endl;
    for (StringVector::const_iterator it = appList.begin(); it != appList.end(); ++it)
      {
      std::cout << "\t" << *it << std::endl;
      }
    }

  return appList;
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetApplicationTags( const std::string& appName )
{
  //
  // output vector
  StringVector  vtags;

  //
  // instantiate the application using the factory
  otb::Wrapper::Application::Pointer application
    = otb::Wrapper::ApplicationRegistry::CreateApplication(appName);

  //
  // get tags
  if ( !application.IsNull() )
    {
    vtags = application->GetDocTags();
    }

  return vtags;
}

/*******************************************************************************/
void
ApplicationsBrowser
::SearchAvailableApplicationsTags()
{
  //
  // get all the applications in the search path
  StringVector vapp = GetAvailableApplications();

  //
  // Fill the  map as following
  // - key   -> tag
  // - value -> list of applications having this tag
  ApplicationsTagContainer      outputContainer;
  StringVector::const_iterator  it = vapp.begin();

  while ( it != vapp.end() )
    {
    // get tags of current app
    StringVector ctags = GetApplicationTags( *it );

    // key will be the tag (easier for tree origanisation in )
    StringVector::const_iterator  itTag = ctags.begin();
    while ( itTag != ctags.end() )
      {

      // search for this tag in the output container
      ApplicationsTagContainer::iterator  pos = outputContainer.find( *itTag );
      if ( pos != outputContainer.end() )  // key found
        {
        //
        // append the application name (*it)
        (*pos).second.push_back(*it);
        }
      else
        {
        //
        // if tag not found in the container, add it
        std::pair< std::string, StringVector > currentAppTags;
        currentAppTags.first  = *itTag;
        currentAppTags.second.push_back( *it );
        outputContainer.insert( currentAppTags );
        }

      ++itTag;
      }

    ++it;
    }

  //
  // emit a signal with the ApplicationsTagContainer as
  // parameter
  emit AvailableApplicationsTagsChanged(outputContainer);
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


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

#include "modules/canbus/vehicle/lincoln/protocol/surround_73.h"

#include "modules/drivers/canbus/common/byte.h"

namespace apollo {
namespace canbus {
namespace lincoln {

using ::apollo::drivers::canbus::Byte;

const int32_t Surround73::ID = 0x73;

void Surround73::Parse(const std::uint8_t *bytes, int32_t length,
                       ChassisDetail *chassis_detail) const {
  // sonar left
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left(
      is_cross_traffic_alert_left(bytes, length));
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left_enabled(
      is_cross_traffic_alert_left_enabled(bytes, length));

  // blind spot left
  chassis_detail->mutable_surround()->set_blind_spot_left_alert(
      is_blind_spot_left_alert(bytes, length));
  chassis_detail->mutable_surround()->set_blind_spot_left_alert_enabled(
      is_blind_spot_left_alert_enabled(bytes, length));

  // sonar right
  chassis_detail->mutable_surround()->set_cross_traffic_alert_right(
      is_cross_traffic_alert_right(bytes, length));
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left_enabled(
      is_cross_traffic_alert_left_enabled(bytes, length));

  // blind spot right
  chassis_detail->mutable_surround()->set_blind_spot_right_alert(
      is_blind_spot_right_alert(bytes, length));
  chassis_detail->mutable_surround()->set_blind_spot_right_alert_enabled(
      is_blind_spot_right_alert_enabled(bytes, length));

  // sonar00 ~ sonar11, output in meters
  chassis_detail->mutable_surround()->set_sonar00(sonar00(bytes, length));
  chassis_detail->mutable_surround()->set_sonar01(sonar01(bytes, length));
  chassis_detail->mutable_surround()->set_sonar02(sonar02(bytes, length));
  chassis_detail->mutable_surround()->set_sonar03(sonar03(bytes, length));
  chassis_detail->mutable_surround()->set_sonar04(sonar04(bytes, length));
  chassis_detail->mutable_surround()->set_sonar05(sonar05(bytes, length));
  chassis_detail->mutable_surround()->set_sonar06(sonar06(bytes, length));
  chassis_detail->mutable_surround()->set_sonar07(sonar07(bytes, length));
  chassis_detail->mutable_surround()->set_sonar08(sonar08(bytes, length));
  chassis_detail->mutable_surround()->set_sonar09(sonar09(bytes, length));
  chassis_detail->mutable_surround()->set_sonar10(sonar10(bytes, length));
  chassis_detail->mutable_surround()->set_sonar11(sonar11(bytes, length));

  // alternative representations.
  const int8_t kSonarNumbers = 12;
  for (std::int8_t i = 0; i < kSonarNumbers; ++i) {
    chassis_detail->mutable_surround()->add_sonar_range(
        sonars(bytes, i, length / 2));
  }
}

bool Surround73::is_cross_traffic_alert_left(const std::uint8_t *bytes,
                                             int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(0);
}

bool Surround73::is_cross_traffic_alert_left_enabled(const std::uint8_t *bytes,
                                                     int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(1);
}

bool Surround73::is_blind_spot_left_alert(const std::uint8_t *bytes,
                                          int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(2);
}

bool Surround73::is_blind_spot_left_alert_enabled(const std::uint8_t *bytes,
                                                  int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(3);
}

bool Surround73::is_cross_traffic_alert_right(const std::uint8_t *bytes,
                                              int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(4);
}

bool Surround73::is_cross_traffic_alert_right_enabled(const std::uint8_t *bytes,
                                                      int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(5);
}

bool Surround73::is_blind_spot_right_alert(const std::uint8_t *bytes,
                                           int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(6);
}

bool Surround73::is_blind_spot_right_alert_enabled(const std::uint8_t *bytes,
                                                   int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(7);
}

double Surround73::sonar00(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 1);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar01(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 1);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar02(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 2);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar03(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 2);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar04(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 3);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar05(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 3);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar06(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 4);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar07(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 4);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar08(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 5);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar09(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 5);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar10(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 6);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar11(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 6);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

bool Surround73::sonar_enabled(const std::uint8_t *bytes,
                               int32_t length) const {
  Byte frame(bytes + 7);
  return frame.is_bit_1(6);
}

bool Surround73::sonar_fault(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 7);
  return frame.is_bit_1(7);
}

double Surround73::sonar_range(const std::int32_t x) const {
  if (x == 0x0) {
    return 100.0;  // If nothing detected, set test range to 100.0m.
  }
  return 0.145 * (x - 0x1) + 0.3;
}

double Surround73::sonars(const std::uint8_t *bytes, std::uint8_t sonar_number,
                          int32_t length) const {
  Byte frame(bytes + sonar_number / 2 + 1);
  int32_t start = (sonar_number % 2) * length;
  int32_t x = frame.get_byte(start, start + length);
  return sonar_range(x);
}

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

#include "modules/canbus/vehicle/lincoln/protocol/surround_73.h"

#include "modules/drivers/canbus/common/byte.h"

namespace apollo {
namespace canbus {
namespace lincoln {

using ::apollo::drivers::canbus::Byte;

const int32_t Surround73::ID = 0x73;

void Surround73::Parse(const std::uint8_t *bytes, int32_t length,
                       ChassisDetail *chassis_detail) const {
  // sonar left
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left(
      is_cross_traffic_alert_left(bytes, length));
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left_enabled(
      is_cross_traffic_alert_left_enabled(bytes, length));

  // blind spot left
  chassis_detail->mutable_surround()->set_blind_spot_left_alert(
      is_blind_spot_left_alert(bytes, length));
  chassis_detail->mutable_surround()->set_blind_spot_left_alert_enabled(
      is_blind_spot_left_alert_enabled(bytes, length));

  // sonar right
  chassis_detail->mutable_surround()->set_cross_traffic_alert_right(
      is_cross_traffic_alert_right(bytes, length));
  chassis_detail->mutable_surround()->set_cross_traffic_alert_left_enabled(
      is_cross_traffic_alert_left_enabled(bytes, length));

  // blind spot right
  chassis_detail->mutable_surround()->set_blind_spot_right_alert(
      is_blind_spot_right_alert(bytes, length));
  chassis_detail->mutable_surround()->set_blind_spot_right_alert_enabled(
      is_blind_spot_right_alert_enabled(bytes, length));

  // sonar00 ~ sonar11, output in meters
  chassis_detail->mutable_surround()->set_sonar00(sonar00(bytes, length));
  chassis_detail->mutable_surround()->set_sonar01(sonar01(bytes, length));
  chassis_detail->mutable_surround()->set_sonar02(sonar02(bytes, length));
  chassis_detail->mutable_surround()->set_sonar03(sonar03(bytes, length));
  chassis_detail->mutable_surround()->set_sonar04(sonar04(bytes, length));
  chassis_detail->mutable_surround()->set_sonar05(sonar05(bytes, length));
  chassis_detail->mutable_surround()->set_sonar06(sonar06(bytes, length));
  chassis_detail->mutable_surround()->set_sonar07(sonar07(bytes, length));
  chassis_detail->mutable_surround()->set_sonar08(sonar08(bytes, length));
  chassis_detail->mutable_surround()->set_sonar09(sonar09(bytes, length));
  chassis_detail->mutable_surround()->set_sonar10(sonar10(bytes, length));
  chassis_detail->mutable_surround()->set_sonar11(sonar11(bytes, length));

  // alternative representations.
  const int8_t kSonarNumbers = 12;
  chassis_detail->mutable_surround()->clear_sonar_range();
  for (std::int8_t i = 0; i < kSonarNumbers; ++i) {
    chassis_detail->mutable_surround()->add_sonar_range(
        sonars(bytes, i, length / 2));
  }
}

bool Surround73::is_cross_traffic_alert_left(const std::uint8_t *bytes,
                                             int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(0);
}

bool Surround73::is_cross_traffic_alert_left_enabled(const std::uint8_t *bytes,
                                                     int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(1);
}

bool Surround73::is_blind_spot_left_alert(const std::uint8_t *bytes,
                                          int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(2);
}

bool Surround73::is_blind_spot_left_alert_enabled(const std::uint8_t *bytes,
                                                  int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(3);
}

bool Surround73::is_cross_traffic_alert_right(const std::uint8_t *bytes,
                                              int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(4);
}

bool Surround73::is_cross_traffic_alert_right_enabled(const std::uint8_t *bytes,
                                                      int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(5);
}

bool Surround73::is_blind_spot_right_alert(const std::uint8_t *bytes,
                                           int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(6);
}

bool Surround73::is_blind_spot_right_alert_enabled(const std::uint8_t *bytes,
                                                   int32_t length) const {
  Byte frame(bytes + 0);
  return frame.is_bit_1(7);
}

double Surround73::sonar00(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 1);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar01(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 1);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar02(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 2);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar03(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 2);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar04(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 3);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar05(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 3);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar06(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 4);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar07(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 4);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar08(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 5);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar09(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 5);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

double Surround73::sonar10(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 6);
  int32_t x = frame.get_byte(0, 3);
  return sonar_range(x);
}

double Surround73::sonar11(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 6);
  int32_t x = frame.get_byte(4, 7);
  return sonar_range(x);
}

bool Surround73::sonar_enabled(const std::uint8_t *bytes,
                               int32_t length) const {
  Byte frame(bytes + 7);
  return frame.is_bit_1(6);
}

bool Surround73::sonar_fault(const std::uint8_t *bytes, int32_t length) const {
  Byte frame(bytes + 7);
  return frame.is_bit_1(7);
}

double Surround73::sonar_range(const std::int32_t x) const {
  if (x == 0x0) {
    return 100.0;  // If nothing detected, set test range to 100.0m.
  }
  return 0.145 * (x - 0x1) + 0.3;
}

double Surround73::sonars(const std::uint8_t *bytes, std::uint8_t sonar_number,
                          int32_t length) const {
  Byte frame(bytes + sonar_number / 2 + 1);
  int32_t start = (sonar_number % 2) * length;
  int32_t x = frame.get_byte(start, start + length);
  return sonar_range(x);
}

}  // namespace lincoln
}  // namespace canbus
}  // namespace apollo
<|endoftext|>