<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.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  This class contains the points for the ALICE event display               //
//                                                                           //
//Begin_Html
/*

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include <TPad.h>
#include <TTree.h>
#include <TView.h>
#include <TMath.h>
#include <TPolyMarker3D.h>
#include <TMarker3DBox.h>

#include <AliRICH.h>
#include "TParticle.h"
#include "AliRICHDisplay.h"
#include "AliRICHPoints.h"
#include "AliRun.h"
#include "AliRICHHit.h"
#include "AliRICHCerenkov.h"
#include "AliRICHSDigit.h"
#include "AliRICHDigit.h"
#include "AliRICHRawCluster.h"

const Int_t kMaxNipx=400, kMaxNipy=800;

ClassImp(AliRICHPoints)

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints()
{
  //
  // Default constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints(Int_t npoints)
  :AliPoints(npoints)
{
  //
  // Standard constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::~AliRICHPoints()
{
  //
  // Default destructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
}

//_____________________________________________________________________________
void AliRICHPoints::DumpHit()
{
  //
  //   Dump hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::DumpDigit()
{
  //
  //   Dump digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectHit()
{
  //
  //   Inspect hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Inspect();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectDigit()
{
  //
  //   Inspect digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Inspect();
}

//_____________________________________________________________________________
Int_t AliRICHPoints::GetTrackIndex()
{
  //
  //   Dump digit corresponding to this point
  //
  printf("GetTrackIndex - fTrackIndex %d \n",fTrackIndex);
  this->Inspect();
  return fTrackIndex;
}
//_____________________________________________________________________________
TParticle *AliRICHPoints::GetParticle() const
{
  //
  //   Returns pointer to particle index in AliRun::fParticles
  //
  if (fIndex < 0 || fIndex >= gAlice->GetNtrack()) return 0;
  return gAlice->Particle(fIndex);
}

//_____________________________________________________________________________
AliRICHHit *AliRICHPoints::GetHit() const
{
  //
  //   Returns pointer to hit index in AliRun::fParticles
  //
  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  pRICH->TreeH()->GetEvent(fTrackIndex);
  TClonesArray *pRICHhits  = pRICH->Hits();
  Int_t nhits = pRICHhits->GetEntriesFast();
  if (fHitIndex < 0 || fHitIndex >= nhits) return 0;
  return (AliRICHHit*)pRICHhits->UncheckedAt(fHitIndex);
}

//_____________________________________________________________________________
AliRICHDigit *AliRICHPoints::GetDigit() const
{
  //
  //   Returns pointer to digit index in AliRun::fParticles
  //

  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  TClonesArray *pRICHdigits  = pRICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = pRICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return 0;
  return (AliRICHDigit*)pRICHdigits->UncheckedAt(fDigitIndex);
}
//----------------------------------------------------------------------------
void AliRICHPoints::ShowRing(Int_t highlight) {

//
// Highlights all pads generated by the same mother particle

  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  AliRICHChamber*       iChamber;
  AliSegmentation*      segmentation;

  AliRICHPoints *points = 0;
  TMarker3DBox  *marker = 0;

  AliRICHHit *mHit = GetHit();

  printf("Hit %d on chamber: %d\n",fHitIndex, mHit->Chamber());

  TClonesArray *digits  = pRICH->DigitsAddress(mHit->Chamber() - 1);
  iChamber = &(pRICH->Chamber(mHit->Chamber() - 1));
  segmentation=iChamber->GetSegmentationModel();

  Float_t dpx  = segmentation->Dpx();
  Float_t dpy  = segmentation->Dpy();

  int ndigits=digits->GetEntriesFast();

  printf("Show Ring called with %d digits\n",ndigits);

  for (int digit=0;digit<ndigits;digit++) {
    AliRICHDigit *mdig = (AliRICHDigit*)digits->UncheckedAt(digit);
    points = new AliRICHPoints(1);

     //printf("Particle %d belongs to ring %d \n", fTrackIndex, mdig->fTracks[1]);

    if (!points) continue;
    if (fTrackIndex == mdig->Track(0)) {

      printf("Digit %d from particle %d belongs to ring %d \n", digit, fTrackIndex, mdig->Track(0));

      Int_t charge=mdig->Signal();
      Int_t index=Int_t(TMath::Log(charge)/(TMath::Log(adc_satm)/22));
      Int_t color=701+index;
      if (color>722) color=722;
      points->SetMarkerColor(color);
      points->SetMarkerStyle(21);
      points->SetMarkerSize(.5);
      Float_t xpad, ypad, zpad;
      segmentation->GetPadC(mdig->PadX(), mdig->PadY(),xpad, ypad, zpad);
      Float_t vectorLoc[3]={xpad,6.276,ypad};
      Float_t  vectorGlob[3];
      points->SetParticle(-1);
      points->SetHitIndex(-1);
      points->SetTrackIndex(-1);
      points->SetDigitIndex(digit);
      iChamber->LocaltoGlobal(vectorLoc,vectorGlob);
      points->SetPoint(0,vectorGlob[0],vectorGlob[1],vectorGlob[2]);

      segmentation->GetPadC(mdig->PadX(), mdig->PadY(), xpad, ypad, zpad);
      Float_t theta = iChamber->GetRotMatrix()->GetTheta();
      Float_t phi   = iChamber->GetRotMatrix()->GetPhi();
      marker=new TMarker3DBox(vectorGlob[0],vectorGlob[1],vectorGlob[2],
			      dpy/2,0,dpx/2,theta,phi);
      marker->SetLineColor(highlight);
      marker->SetFillStyle(1001);
      marker->SetFillColor(color);
      marker->SetRefObject((TObject*)points);
      points->Set3DMarker(0, marker);

      points->Draw("same");
      for (Int_t im=0;im<3;im++) {
	TMarker3DBox *marker=points->GetMarker(im);
	if (marker)
	  marker->Draw();
      }
      TParticle *p = gAlice->Particle(fIndex);
      printf("\nTrack index %d\n",fTrackIndex);
      printf("Particle ID %d\n",p->GetPdgCode());
      printf("Parent %d\n",p->GetFirstMother());
      printf("First child %d\n",p->GetFirstDaughter());
      printf("Px,Py,Pz %f %f %f\n",p->Px(),p->Py(),p->Pz());
    }
  }
}

//_____________________________________________________________________________
const Text_t *AliRICHPoints::GetName() const
{
  //
  // Return name of the Geant3 particle corresponding to this point
  //
  TParticle *particle = GetParticle();
  if (!particle) return "Particle";
  return particle->GetName();
}

//_____________________________________________________________________________
Text_t *AliRICHPoints::GetObjectInfo(Int_t, Int_t)
{
  //
  //   Redefines TObject::GetObjectInfo.
  //   Displays the info (particle,etc
  //   corresponding to cursor position px,py
  //
  static char info[64];
  sprintf(info,"%s %d",GetName(),fIndex);
  return info;
}

<commit_msg>minor problem witn include solved<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.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  This class contains the points for the ALICE event display               //
//                                                                           //
//Begin_Html
/*

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include <TPad.h>
#include <TTree.h>
#include <TView.h>
#include <TMath.h>
#include <TPolyMarker3D.h>
#include <TMarker3DBox.h>

#include "AliRICH.h"
#include <TParticle.h>
#include "AliRICHDisplay.h"
#include "AliRICHPoints.h"
#include "AliRun.h"
#include "AliRICHHit.h"
#include "AliRICHCerenkov.h"
#include "AliRICHSDigit.h"
#include "AliRICHDigit.h"
#include "AliRICHRawCluster.h"

const Int_t kMaxNipx=400, kMaxNipy=800;

ClassImp(AliRICHPoints)

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints()
{
  //
  // Default constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints(Int_t npoints)
  :AliPoints(npoints)
{
  //
  // Standard constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::~AliRICHPoints()
{
  //
  // Default destructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
}

//_____________________________________________________________________________
void AliRICHPoints::DumpHit()
{
  //
  //   Dump hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::DumpDigit()
{
  //
  //   Dump digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectHit()
{
  //
  //   Inspect hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Inspect();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectDigit()
{
  //
  //   Inspect digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Inspect();
}

//_____________________________________________________________________________
Int_t AliRICHPoints::GetTrackIndex()
{
  //
  //   Dump digit corresponding to this point
  //
  printf("GetTrackIndex - fTrackIndex %d \n",fTrackIndex);
  this->Inspect();
  return fTrackIndex;
}
//_____________________________________________________________________________
TParticle *AliRICHPoints::GetParticle() const
{
  //
  //   Returns pointer to particle index in AliRun::fParticles
  //
  if (fIndex < 0 || fIndex >= gAlice->GetNtrack()) return 0;
  return gAlice->Particle(fIndex);
}

//_____________________________________________________________________________
AliRICHHit *AliRICHPoints::GetHit() const
{
  //
  //   Returns pointer to hit index in AliRun::fParticles
  //
  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  pRICH->TreeH()->GetEvent(fTrackIndex);
  TClonesArray *pRICHhits  = pRICH->Hits();
  Int_t nhits = pRICHhits->GetEntriesFast();
  if (fHitIndex < 0 || fHitIndex >= nhits) return 0;
  return (AliRICHHit*)pRICHhits->UncheckedAt(fHitIndex);
}

//_____________________________________________________________________________
AliRICHDigit *AliRICHPoints::GetDigit() const
{
  //
  //   Returns pointer to digit index in AliRun::fParticles
  //

  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  TClonesArray *pRICHdigits  = pRICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = pRICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return 0;
  return (AliRICHDigit*)pRICHdigits->UncheckedAt(fDigitIndex);
}
//----------------------------------------------------------------------------
void AliRICHPoints::ShowRing(Int_t highlight) {

//
// Highlights all pads generated by the same mother particle

  AliRICH *pRICH  = (AliRICH*)gAlice->GetDetector("RICH");
  AliRICHChamber*       iChamber;
  AliSegmentation*      segmentation;

  AliRICHPoints *points = 0;
  TMarker3DBox  *marker = 0;

  AliRICHHit *mHit = GetHit();

  printf("Hit %d on chamber: %d\n",fHitIndex, mHit->Chamber());

  TClonesArray *digits  = pRICH->DigitsAddress(mHit->Chamber() - 1);
  iChamber = &(pRICH->Chamber(mHit->Chamber() - 1));
  segmentation=iChamber->GetSegmentationModel();

  Float_t dpx  = segmentation->Dpx();
  Float_t dpy  = segmentation->Dpy();

  int ndigits=digits->GetEntriesFast();

  printf("Show Ring called with %d digits\n",ndigits);

  for (int digit=0;digit<ndigits;digit++) {
    AliRICHDigit *mdig = (AliRICHDigit*)digits->UncheckedAt(digit);
    points = new AliRICHPoints(1);

     //printf("Particle %d belongs to ring %d \n", fTrackIndex, mdig->fTracks[1]);

    if (!points) continue;
    if (fTrackIndex == mdig->Track(0)) {

      printf("Digit %d from particle %d belongs to ring %d \n", digit, fTrackIndex, mdig->Track(0));

      Int_t charge=mdig->Signal();
      Int_t index=Int_t(TMath::Log(charge)/(TMath::Log(adc_satm)/22));
      Int_t color=701+index;
      if (color>722) color=722;
      points->SetMarkerColor(color);
      points->SetMarkerStyle(21);
      points->SetMarkerSize(.5);
      Float_t xpad, ypad, zpad;
      segmentation->GetPadC(mdig->PadX(), mdig->PadY(),xpad, ypad, zpad);
      Float_t vectorLoc[3]={xpad,6.276,ypad};
      Float_t  vectorGlob[3];
      points->SetParticle(-1);
      points->SetHitIndex(-1);
      points->SetTrackIndex(-1);
      points->SetDigitIndex(digit);
      iChamber->LocaltoGlobal(vectorLoc,vectorGlob);
      points->SetPoint(0,vectorGlob[0],vectorGlob[1],vectorGlob[2]);

      segmentation->GetPadC(mdig->PadX(), mdig->PadY(), xpad, ypad, zpad);
      Float_t theta = iChamber->GetRotMatrix()->GetTheta();
      Float_t phi   = iChamber->GetRotMatrix()->GetPhi();
      marker=new TMarker3DBox(vectorGlob[0],vectorGlob[1],vectorGlob[2],
			      dpy/2,0,dpx/2,theta,phi);
      marker->SetLineColor(highlight);
      marker->SetFillStyle(1001);
      marker->SetFillColor(color);
      marker->SetRefObject((TObject*)points);
      points->Set3DMarker(0, marker);

      points->Draw("same");
      for (Int_t im=0;im<3;im++) {
	TMarker3DBox *marker=points->GetMarker(im);
	if (marker)
	  marker->Draw();
      }
      TParticle *p = gAlice->Particle(fIndex);
      printf("\nTrack index %d\n",fTrackIndex);
      printf("Particle ID %d\n",p->GetPdgCode());
      printf("Parent %d\n",p->GetFirstMother());
      printf("First child %d\n",p->GetFirstDaughter());
      printf("Px,Py,Pz %f %f %f\n",p->Px(),p->Py(),p->Pz());
    }
  }
}

//_____________________________________________________________________________
const Text_t *AliRICHPoints::GetName() const
{
  //
  // Return name of the Geant3 particle corresponding to this point
  //
  TParticle *particle = GetParticle();
  if (!particle) return "Particle";
  return particle->GetName();
}

//_____________________________________________________________________________
Text_t *AliRICHPoints::GetObjectInfo(Int_t, Int_t)
{
  //
  //   Redefines TObject::GetObjectInfo.
  //   Displays the info (particle,etc
  //   corresponding to cursor position px,py
  //
  static char info[64];
  sprintf(info,"%s %d",GetName(),fIndex);
  return info;
}

<|endoftext|>


<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#include <ntstatus.h>
#include <winternl.h>
#include <pathcch.h>
#include <atlbase.h>
#include <atlalloc.h>
#include <atlchecked.h>
#include <array>
#include <memory>
#include <string>
#include <cstdint>
#include "lxsstat.hpp"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "ntdll")

#pragma region
EXTERN_C NTSYSAPI NTSTATUS NTAPI ZwQueryEaFile(
	_In_     HANDLE           FileHandle,
	_Out_    PIO_STATUS_BLOCK IoStatusBlock,
	_Out_    PVOID            Buffer,
	_In_     ULONG            Length,
	_In_     BOOLEAN          ReturnSingleEntry,
	_In_opt_ PVOID            EaList,
	_In_     ULONG            EaListLength,
	_In_opt_ PULONG           EaIndex,
	_In_     BOOLEAN          RestartScan
);
struct FILE_FULL_EA_INFORMATION
{
	ULONG  NextEntryOffset;
	UCHAR  Flags;
	UCHAR  EaNameLength;
	USHORT EaValueLength;
	CHAR   EaName[ANYSIZE_ARRAY];
};
struct FILE_GET_EA_INFORMATION
{
	ULONG NextEntryOffset;
	UCHAR EaNameLength;
	CHAR  EaName[ANYSIZE_ARRAY];
};
constexpr size_t MAXIMUM_LENGTH_OF_EA_NAME = (std::numeric_limits<decltype(FILE_FULL_EA_INFORMATION::EaNameLength)>::max)();
constexpr size_t MAXIMUM_LENGTH_OF_EA_VALUE = (std::numeric_limits<decltype(FILE_FULL_EA_INFORMATION::EaValueLength)>::max)();
#pragma endregion

namespace Lxss
{
	const auto lxss_root = []()->std::wstring
	{
		WCHAR temp[MAX_PATH];
		if (!ExpandEnvironmentStringsW(LR"(%LOCALAPPDATA%\lxss)", temp, ARRAYSIZE(temp)))
		{
			::ATL::AtlThrowLastWin32();
		}
		return temp;
	}();
	std::wstring realpath(std::wstring path)
	{
		_RPT1(_CRT_WARN, "realpath(<%ls)\n", path.c_str());
		if (path[0] == L'/')
		{
			for (size_t pos = path.find(L'#'); pos != std::string::npos; pos = path.find(L'#', pos))
			{
				path.insert(++pos, L"0023");
			}
			for (size_t pos = path.find(L':'); pos != std::string::npos; pos = path.find(L':', pos))
			{
				path[pos] = L'#';
				path.insert(++pos, L"003A");
			}
			bool need_reloc = false;
			const PCWSTR reloc_directory[] = {
				L"/root/",
				L"/home/",
			};
			for (int i = 0; i < _countof(reloc_directory); ++i)
			{
				if (wcsncmp(path.c_str(), reloc_directory[i], wcslen(reloc_directory[i])) == 0 && path.length() > wcslen(reloc_directory[i]))
				{
					need_reloc = true;
					break;
				}
			}
			path.insert(0, !need_reloc ? lxss_root + L"\\rootfs" : lxss_root);
		}
		const WCHAR prefix[] = LR"(\\?\)";
		if (!PathIsRelativeW(path.c_str()) && wcsncmp(path.c_str(), prefix, wcslen(prefix)) != 0 && path[0] != '\\')
		{
			path.insert(0, prefix);
		}
		auto stage1 = std::make_unique<WCHAR[]>(PATHCCH_MAX_CCH);
		if (!GetFullPathNameW(path.c_str(), PATHCCH_MAX_CCH, stage1.get(), nullptr))
		{
			::ATL::AtlThrowLastWin32();
		}
		std::wstring stage2(stage1.get());
		if (wcsncmp(stage2.c_str(), prefix, wcslen(prefix)) != 0 && !PathIsUNCW(stage2.c_str()))
		{
			stage2.insert(0, prefix);
		}
		_RPT1(_CRT_WARN, "realpath(>%ls)\n", stage2.c_str());
		return stage2;
	}
	std::array<char, 11> mode_tostring(uint32_t st_mode)
	{
		if (S_ISLNK(st_mode))
		{
			return{ "lrwxrwxrwx" };
		}

		std::array<char, 11> result;
		std::get<0>(result) = S_ISDIR(st_mode) ? 'd' : S_ISREG(st_mode) ? '-' : '?';
		std::get<1>(result) = st_mode & S_IRUSR ? 'r' : '-';
		std::get<2>(result) = st_mode & S_IWUSR ? 'w' : '-';
		std::get<3>(result) = st_mode & S_ISUID
			? st_mode & S_IXUSR ? 's' : 'S'
			: st_mode & S_IXUSR ? 'x' : '-';
		std::get<4>(result) = st_mode & S_IRGRP ? 'r' : '-';
		std::get<5>(result) = st_mode & S_IWGRP ? 'w' : '-';
		std::get<6>(result) = st_mode & S_ISGID
			? st_mode & S_IXGRP ? 's' : 'S'
			: st_mode & S_IXGRP ? 'x' : '-';
		std::get<7>(result) = st_mode & S_IROTH ? 'r' : '-';
		std::get<8>(result) = st_mode & S_IWOTH ? 'w' : '-';
		std::get<9>(result) = st_mode & S_ISVTX
			? st_mode & S_IXOTH ? 't' : 'T'
			: st_mode & S_IXOTH ? 'x' : '-';
		std::get<10>(result) = '\0';
		return result;
	}
	_Success_(return == 0) int stat(_In_z_ const wchar_t *__restrict path, _Out_ struct Lxss::stat *__restrict buf)
	{
		auto windows_path = realpath(path);

		::ATL::CHandle h(CreateFileW(windows_path.c_str(), FILE_READ_EA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, nullptr));
		if (h == INVALID_HANDLE_VALUE)
		{
			return -1;
		}

		constexpr size_t EaLength = offsetof(FILE_FULL_EA_INFORMATION, EaName) + MAXIMUM_LENGTH_OF_EA_NAME + MAXIMUM_LENGTH_OF_EA_VALUE;
		::ATL::CTempBuffer<FILE_FULL_EA_INFORMATION> Ea(EaLength);

		constexpr size_t EaQueryLength = offsetof(FILE_GET_EA_INFORMATION, EaName) + MAXIMUM_LENGTH_OF_EA_NAME;
		::ATL::CTempBuffer<FILE_GET_EA_INFORMATION> EaQuery(EaQueryLength);
		EaQuery->NextEntryOffset = 0;
		EaQuery->EaNameLength = (UCHAR)strlen(LxssEaName);
		::ATL::Checked::strcpy_s(EaQuery->EaName, MAXIMUM_LENGTH_OF_EA_NAME, LxssEaName);

		IO_STATUS_BLOCK ea_iob;
		NTSTATUS ea_status = ZwQueryEaFile(h, &ea_iob, Ea, EaLength, FALSE, EaQuery, EaQueryLength, nullptr, TRUE);
		if (NT_ERROR(ea_status))
		{
			SetLastError(ea_status);
			return -1;
		}
		// If EaList != null ZwQueryEaFile() always return STATUS_SUCCESS even EA not found.
		if (Ea->EaValueLength != sizeof(LXATTRB))
		{
			SetLastError((ULONG)STATUS_NO_EAS_ON_FILE);
			return -1;
		}
		_ASSERTE(strcmp(Ea->EaName, LxssEaName) == 0);
		const LXATTRB* const lxattr = (LXATTRB*)&Ea->EaName[Ea->EaNameLength + 1];

		auto file_std_info = std::make_unique<FILE_STANDARD_INFO>();
		if (!GetFileInformationByHandleEx(h, FileStandardInfo, file_std_info.get(), sizeof(FILE_STANDARD_INFO)))
		{
			return -1;
		}
		auto file_storage_info = std::make_unique<FILE_STORAGE_INFO>();
		if (!GetFileInformationByHandleEx(h, FileStorageInfo, file_storage_info.get(), sizeof(FILE_STORAGE_INFO)))
		{
			return -1;
		}
		auto file_id_info = std::make_unique<FILE_ID_INFO>();
		if (!GetFileInformationByHandleEx(h, FileIdInfo, file_id_info.get(), sizeof(FILE_ID_INFO)))
		{
			return -1;
		}

		// Always 0 ?
		buf->st_dev = 0;
		buf->FileId = file_id_info->FileId;
		buf->st_nlink = file_std_info->NumberOfLinks;
		buf->st_atim.tv_sec = lxattr->atime;
		buf->st_atim.tv_nsec = lxattr->atime_extra;
		buf->st_mtim.tv_sec = lxattr->mtime;
		buf->st_mtim.tv_nsec = lxattr->mtime_extra;
		buf->st_ctim.tv_sec = lxattr->ctime;
		buf->st_ctim.tv_nsec = lxattr->ctime_extra;
		// FILE_BASIC_INFO::CreationTime unused ?
		buf->st_birthtim.tv_sec = 0;
		buf->st_birthtim.tv_nsec = 0;
		buf->st_size = !lxattr->permission.is_directory ? file_std_info->EndOfFile.QuadPart : 0;
		buf->st_blksize = file_storage_info->PhysicalBytesPerSectorForPerformance;
		buf->st_blocks = file_std_info->AllocationSize.QuadPart / 512;
		buf->st_uid = lxattr->st_uid;
		buf->st_gid = lxattr->st_gid;
		buf->st_mode = lxattr->st_mode;

		return 0;
	}
}<commit_msg>Bugfix Relocate /root and /home itself<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#include <ntstatus.h>
#include <winternl.h>
#include <pathcch.h>
#include <atlbase.h>
#include <atlalloc.h>
#include <atlchecked.h>
#include <array>
#include <memory>
#include <string>
#include <cstdint>
#include "lxsstat.hpp"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "ntdll")

#pragma region
EXTERN_C NTSYSAPI NTSTATUS NTAPI ZwQueryEaFile(
	_In_     HANDLE           FileHandle,
	_Out_    PIO_STATUS_BLOCK IoStatusBlock,
	_Out_    PVOID            Buffer,
	_In_     ULONG            Length,
	_In_     BOOLEAN          ReturnSingleEntry,
	_In_opt_ PVOID            EaList,
	_In_     ULONG            EaListLength,
	_In_opt_ PULONG           EaIndex,
	_In_     BOOLEAN          RestartScan
);
struct FILE_FULL_EA_INFORMATION
{
	ULONG  NextEntryOffset;
	UCHAR  Flags;
	UCHAR  EaNameLength;
	USHORT EaValueLength;
	CHAR   EaName[ANYSIZE_ARRAY];
};
struct FILE_GET_EA_INFORMATION
{
	ULONG NextEntryOffset;
	UCHAR EaNameLength;
	CHAR  EaName[ANYSIZE_ARRAY];
};
constexpr size_t MAXIMUM_LENGTH_OF_EA_NAME = (std::numeric_limits<decltype(FILE_FULL_EA_INFORMATION::EaNameLength)>::max)();
constexpr size_t MAXIMUM_LENGTH_OF_EA_VALUE = (std::numeric_limits<decltype(FILE_FULL_EA_INFORMATION::EaValueLength)>::max)();
#pragma endregion

namespace Lxss
{
	const auto lxss_root = []()->std::wstring
	{
		WCHAR temp[MAX_PATH];
		if (!ExpandEnvironmentStringsW(LR"(%LOCALAPPDATA%\lxss)", temp, ARRAYSIZE(temp)))
		{
			::ATL::AtlThrowLastWin32();
		}
		return temp;
	}();
	std::wstring realpath(std::wstring path)
	{
		_RPT1(_CRT_WARN, "realpath(<%ls)\n", path.c_str());
		if (path[0] == L'/')
		{
			for (size_t pos = path.find(L'#'); pos != std::string::npos; pos = path.find(L'#', pos))
			{
				path.insert(++pos, L"0023");
			}
			for (size_t pos = path.find(L':'); pos != std::string::npos; pos = path.find(L':', pos))
			{
				path[pos] = L'#';
				path.insert(++pos, L"003A");
			}
			bool need_reloc = false;
			const PCWSTR reloc_directory[] = {
				L"/root",
				L"/home",
			};
			for (int i = 0; i < _countof(reloc_directory); ++i)
			{
				const size_t reloc_length = wcslen(reloc_directory[i]);
				if (
					wcsncmp(path.c_str(), reloc_directory[i], reloc_length) == 0
					&& (path[reloc_length] == L'\0' || path[reloc_length] == L'/'))
				{
					need_reloc = true;
					break;
				}
			}
			path.insert(0, !need_reloc ? lxss_root + L"\\rootfs" : lxss_root);
		}
		const WCHAR prefix[] = LR"(\\?\)";
		if (!PathIsRelativeW(path.c_str()) && wcsncmp(path.c_str(), prefix, wcslen(prefix)) != 0 && path[0] != '\\')
		{
			path.insert(0, prefix);
		}
		auto stage1 = std::make_unique<WCHAR[]>(PATHCCH_MAX_CCH);
		if (!GetFullPathNameW(path.c_str(), PATHCCH_MAX_CCH, stage1.get(), nullptr))
		{
			::ATL::AtlThrowLastWin32();
		}
		std::wstring stage2(stage1.get());
		if (wcsncmp(stage2.c_str(), prefix, wcslen(prefix)) != 0 && !PathIsUNCW(stage2.c_str()))
		{
			stage2.insert(0, prefix);
		}
		_RPT1(_CRT_WARN, "realpath(>%ls)\n", stage2.c_str());
		return stage2;
	}
	std::array<char, 11> mode_tostring(uint32_t st_mode)
	{
		if (S_ISLNK(st_mode))
		{
			return{ "lrwxrwxrwx" };
		}

		std::array<char, 11> result;
		std::get<0>(result) = S_ISDIR(st_mode) ? 'd' : S_ISREG(st_mode) ? '-' : '?';
		std::get<1>(result) = st_mode & S_IRUSR ? 'r' : '-';
		std::get<2>(result) = st_mode & S_IWUSR ? 'w' : '-';
		std::get<3>(result) = st_mode & S_ISUID
			? st_mode & S_IXUSR ? 's' : 'S'
			: st_mode & S_IXUSR ? 'x' : '-';
		std::get<4>(result) = st_mode & S_IRGRP ? 'r' : '-';
		std::get<5>(result) = st_mode & S_IWGRP ? 'w' : '-';
		std::get<6>(result) = st_mode & S_ISGID
			? st_mode & S_IXGRP ? 's' : 'S'
			: st_mode & S_IXGRP ? 'x' : '-';
		std::get<7>(result) = st_mode & S_IROTH ? 'r' : '-';
		std::get<8>(result) = st_mode & S_IWOTH ? 'w' : '-';
		std::get<9>(result) = st_mode & S_ISVTX
			? st_mode & S_IXOTH ? 't' : 'T'
			: st_mode & S_IXOTH ? 'x' : '-';
		std::get<10>(result) = '\0';
		return result;
	}
	_Success_(return == 0) int stat(_In_z_ const wchar_t *__restrict path, _Out_ struct Lxss::stat *__restrict buf)
	{
		auto windows_path = realpath(path);

		::ATL::CHandle h(CreateFileW(windows_path.c_str(), FILE_READ_EA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, nullptr));
		if (h == INVALID_HANDLE_VALUE)
		{
			return -1;
		}

		constexpr size_t EaLength = offsetof(FILE_FULL_EA_INFORMATION, EaName) + MAXIMUM_LENGTH_OF_EA_NAME + MAXIMUM_LENGTH_OF_EA_VALUE;
		::ATL::CTempBuffer<FILE_FULL_EA_INFORMATION> Ea(EaLength);

		constexpr size_t EaQueryLength = offsetof(FILE_GET_EA_INFORMATION, EaName) + MAXIMUM_LENGTH_OF_EA_NAME;
		::ATL::CTempBuffer<FILE_GET_EA_INFORMATION> EaQuery(EaQueryLength);
		EaQuery->NextEntryOffset = 0;
		EaQuery->EaNameLength = (UCHAR)strlen(LxssEaName);
		::ATL::Checked::strcpy_s(EaQuery->EaName, MAXIMUM_LENGTH_OF_EA_NAME, LxssEaName);

		IO_STATUS_BLOCK ea_iob;
		NTSTATUS ea_status = ZwQueryEaFile(h, &ea_iob, Ea, EaLength, FALSE, EaQuery, EaQueryLength, nullptr, TRUE);
		if (NT_ERROR(ea_status))
		{
			SetLastError(ea_status);
			return -1;
		}
		// If EaList != null ZwQueryEaFile() always return STATUS_SUCCESS even EA not found.
		if (Ea->EaValueLength != sizeof(LXATTRB))
		{
			SetLastError((ULONG)STATUS_NO_EAS_ON_FILE);
			return -1;
		}
		_ASSERTE(strcmp(Ea->EaName, LxssEaName) == 0);
		const LXATTRB* const lxattr = (LXATTRB*)&Ea->EaName[Ea->EaNameLength + 1];

		auto file_std_info = std::make_unique<FILE_STANDARD_INFO>();
		if (!GetFileInformationByHandleEx(h, FileStandardInfo, file_std_info.get(), sizeof(FILE_STANDARD_INFO)))
		{
			return -1;
		}
		auto file_storage_info = std::make_unique<FILE_STORAGE_INFO>();
		if (!GetFileInformationByHandleEx(h, FileStorageInfo, file_storage_info.get(), sizeof(FILE_STORAGE_INFO)))
		{
			return -1;
		}
		auto file_id_info = std::make_unique<FILE_ID_INFO>();
		if (!GetFileInformationByHandleEx(h, FileIdInfo, file_id_info.get(), sizeof(FILE_ID_INFO)))
		{
			return -1;
		}

		// Always 0 ?
		buf->st_dev = 0;
		buf->FileId = file_id_info->FileId;
		buf->st_nlink = file_std_info->NumberOfLinks;
		buf->st_atim.tv_sec = lxattr->atime;
		buf->st_atim.tv_nsec = lxattr->atime_extra;
		buf->st_mtim.tv_sec = lxattr->mtime;
		buf->st_mtim.tv_nsec = lxattr->mtime_extra;
		buf->st_ctim.tv_sec = lxattr->ctime;
		buf->st_ctim.tv_nsec = lxattr->ctime_extra;
		// FILE_BASIC_INFO::CreationTime unused ?
		buf->st_birthtim.tv_sec = 0;
		buf->st_birthtim.tv_nsec = 0;
		buf->st_size = !lxattr->permission.is_directory ? file_std_info->EndOfFile.QuadPart : 0;
		buf->st_blksize = file_storage_info->PhysicalBytesPerSectorForPerformance;
		buf->st_blocks = file_std_info->AllocationSize.QuadPart / 512;
		buf->st_uid = lxattr->st_uid;
		buf->st_gid = lxattr->st_gid;
		buf->st_mode = lxattr->st_mode;

		return 0;
	}
}<|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.                  *
 **************************************************************************/

/*
  $Log$
*/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  This class contains the points for the ALICE event display               //
//                                                                           //
//Begin_Html
/*

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include "AliRICHDisplay.h"
#include "AliRICHPoints.h"
#include "AliRun.h"
#include "TPad.h"
#include "TView.h"
#include "TMath.h"

const Int_t MAX_Nipx=400, MAX_Nipy=800;

ClassImp(AliRICHPoints)

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints()
{
  //
  // Default constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints(Int_t npoints)
  :AliPoints(npoints)
{
  //
  // Standard constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::~AliRICHPoints()
{
  //
  // Default destructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
}

//_____________________________________________________________________________
void AliRICHPoints::DumpHit()
{
  //
  //   Dump hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::DumpDigit()
{
  //
  //   Dump digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectHit()
{
  //
  //   Inspect hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Inspect();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectDigit()
{
  //
  //   Inspect digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Inspect();
}

//_____________________________________________________________________________
Int_t AliRICHPoints::GetTrackIndex()
{
  //
  //   Dump digit corresponding to this point
  //
  printf("GetTrackIndex - fTrackIndex %d \n",fTrackIndex);
  this->Inspect();
  return fTrackIndex;
}

//_____________________________________________________________________________
AliRICHHit *AliRICHPoints::GetHit() const
{
  //
  //   Returns pointer to hit index in AliRun::fParticles
  //
  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  gAlice->TreeH()->GetEvent(fTrackIndex);
  TClonesArray *RICHhits  = RICH->Hits();
  Int_t nhits = RICHhits->GetEntriesFast();
  if (fHitIndex < 0 || fHitIndex >= nhits) return 0;
  return (AliRICHHit*)RICHhits->UncheckedAt(fHitIndex);
}

//_____________________________________________________________________________
AliRICHDigit *AliRICHPoints::GetDigit() const
{
  //
  //   Returns pointer to digit index in AliRun::fParticles
  //

  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  TClonesArray *RICHdigits  = RICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = RICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return 0;
  return (AliRICHDigit*)RICHdigits->UncheckedAt(fDigitIndex);
}
//_____________________________________________________________________________
struct Bin {
   const AliRICHDigit *dig;
   int idx;
   Bin() {dig=0; idx=-1;}
};

struct PreCluster : public AliRICHRawCluster {
   const AliRICHDigit* summit;
   int idx;
   int cut;
   int npeaks;
   PreCluster() : AliRICHRawCluster() {cut=npeaks=0;}
};
//_____________________________________________________________________________

static void FindCluster(AliRICHChamber *iChamber, AliRICHSegmentation *segmentation, int i, int j, Bin bins[MAX_Nipx][MAX_Nipy], PreCluster &c)

{

  //
  // Find clusters
  //

  printf("I'm in FindCluster \n");

  Bin& b=bins[i][j];
  Int_t q=b.dig->fSignal;

  printf("FindCluster - i j q %d %d %d\n",i,j,q);

  if (q<0) {
    q=-q;
    c.cut=1;
  }
  if (b.idx >= 0 && b.idx != c.idx) {
    c.idx=b.idx;
    c.npeaks++;
  }

  if (q > TMath::Abs(c.summit->fSignal)) c.summit=b.dig;

  Int_t npx  = segmentation->Npx();
  Int_t npy  = segmentation->Npy();
  Float_t x,y;
  segmentation->GetPadCxy(i-npx, j-npy, x,y);
  printf("FindCluster - x  y %f %f \n",x,y);

  c.fX += q*x;
  c.fY += q*y;
  c.fQ += q;

  b.dig = 0;  b.idx = c.idx;

  if (bins[i-1][j].dig) FindCluster(iChamber,segmentation,i-1,j,bins,c);
  if (bins[i][j-1].dig) FindCluster(iChamber,segmentation,i,j-1,bins,c);
  if (bins[i+1][j].dig) FindCluster(iChamber,segmentation,i+1,j,bins,c);
  if (bins[i][j+1].dig) FindCluster(iChamber,segmentation,i,j+1,bins,c);

}

//_____________________________________________________________________________

void AliRICHPoints::GetCenterOfGravity()
{
  //
  // simple RICH cluster finder from digits -- finds neighbours and
  // calculates center of gravity for the cluster
  //
  const Int_t MAX_nipx=400, MAX_nipy=800;
  printf("\n Hallo world");
  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  AliRICHChamber *iChamber;
  AliRICHSegmentation *segmentation;
  iChamber =&(RICH->Chamber(chamber-1));
  segmentation=iChamber->GetSegmentationModel(cathode);
  Int_t npx  = segmentation->Npx();
  Int_t npy  = segmentation->Npy();
  Float_t zpos=iChamber->ZPosition();

  TClonesArray *RICHdigits  = RICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = RICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return;

  AliRICHDigit  *dig;
  dig=(AliRICHDigit*)RICHdigits->UncheckedAt(fDigitIndex);
  Int_t ipx=dig->fPadX;
  Int_t ipy=dig->fPadY;
  Bin bins[MAX_nipx][MAX_nipy];
  bins[ipx+npx][ipy+npy].dig=dig;

  int ndig;
  int ncls=0;
  for (ndig=0; ndig<ndigits; ndig++) {
      dig = (AliRICHDigit*)RICHdigits->UncheckedAt(ndig);
      int i=dig->fPadX, j=dig->fPadY;
      bins[i+npx][j+npy].dig=dig;
  }

  PreCluster c; c.summit=bins[ipx+npx][ipy+npy].dig; c.idx=ncls;
  FindCluster(iChamber,segmentation,ipx+npx, ipy+npy, bins, c);
  if (c.npeaks>1) {
      printf("GetCenterOfGravity -- more than one peak");
  }
  c.fX /= c.fQ;
  c.fY /= c.fQ;
  printf("GetCenterOfGravity - c.fX c.fY c.fQ %f %f %d \n",c.fX,c.fY,c.fQ);

  c.fTracks[0]=c.summit->fTracks[0];
  c.fTracks[1]=c.summit->fTracks[1];
  c.fTracks[2]=c.summit->fTracks[2];
  ncls++;
  AliRICHPoints *points = 0;
  points = new AliRICHPoints(1);
  points->SetMarkerColor(kYellow);
  points->SetMarkerStyle(5);
  points->SetMarkerSize(1.);
  points->SetPoint(0,c.fX,c.fY,zpos);
  points->Draw();

  printf("GetCenterOfGravity -- ncls %d \n",ncls);

}

//_____________________________________________________________________________
const Text_t *AliRICHPoints::GetName() const
{
  //
  // Return name of the Geant3 particle corresponding to this point
  //
  TParticle *particle = GetParticle();
  if (!particle) return "Particle";
  return particle->GetName();
}

//_____________________________________________________________________________
Text_t *AliRICHPoints::GetObjectInfo(Int_t, Int_t)
{
  //
  //   Redefines TObject::GetObjectInfo.
  //   Displays the info (particle,etc
  //   corresponding to cursor position px,py
  //
  static char info[64];
  sprintf(info,"%s %d",GetName(),fIndex);
  return info;
}

<commit_msg>Added the ShowRing function.<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.                  *
 **************************************************************************/

/*
  $Log$
  Revision 1.1  2000/04/19 13:16:47  morsch
  Minor changes on class names.

*/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  This class contains the points for the ALICE event display               //
//                                                                           //
//Begin_Html
/*

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include "AliRICHDisplay.h"
#include "AliRICHPoints.h"
#include "AliRun.h"
#include "TPad.h"
#include "TView.h"
#include "TMath.h"

const Int_t MAX_Nipx=400, MAX_Nipy=800;

ClassImp(AliRICHPoints)

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints()
{
  //
  // Default constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::AliRICHPoints(Int_t npoints)
  :AliPoints(npoints)
{
  //
  // Standard constructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
  fMarker[0] = fMarker[1] = fMarker[2]=0;
}

//_____________________________________________________________________________
AliRICHPoints::~AliRICHPoints()
{
  //
  // Default destructor
  //
  fHitIndex = 0;
  fTrackIndex = 0;
  fDigitIndex = 0;
}

//_____________________________________________________________________________
void AliRICHPoints::DumpHit()
{
  //
  //   Dump hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::DumpDigit()
{
  //
  //   Dump digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Dump();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectHit()
{
  //
  //   Inspect hit corresponding to this point
  //
  AliRICHHit *hit = GetHit();
  if (hit) hit->Inspect();
}

//_____________________________________________________________________________
void AliRICHPoints::InspectDigit()
{
  //
  //   Inspect digit corresponding to this point
  //
  AliRICHDigit *digit = GetDigit();
  if (digit) digit->Inspect();
}

//_____________________________________________________________________________
Int_t AliRICHPoints::GetTrackIndex()
{
  //
  //   Dump digit corresponding to this point
  //
  printf("GetTrackIndex - fTrackIndex %d \n",fTrackIndex);
  this->Inspect();
  return fTrackIndex;
}
//_____________________________________________________________________________
TParticle *AliRICHPoints::GetParticle() const
{
  //
  //   Returns pointer to particle index in AliRun::fParticles
  //
  TClonesArray *particles = gAlice->Particles();
  Int_t nparticles = particles->GetEntriesFast();
  if (fIndex < 0 || fIndex >= nparticles) return 0;
  return (TParticle*)particles->UncheckedAt(fIndex);
}

//_____________________________________________________________________________
AliRICHHit *AliRICHPoints::GetHit() const
{
  //
  //   Returns pointer to hit index in AliRun::fParticles
  //
  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  gAlice->TreeH()->GetEvent(fTrackIndex);
  TClonesArray *RICHhits  = RICH->Hits();
  Int_t nhits = RICHhits->GetEntriesFast();
  if (fHitIndex < 0 || fHitIndex >= nhits) return 0;
  return (AliRICHHit*)RICHhits->UncheckedAt(fHitIndex);
}

//_____________________________________________________________________________
AliRICHDigit *AliRICHPoints::GetDigit() const
{
  //
  //   Returns pointer to digit index in AliRun::fParticles
  //

  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  TClonesArray *RICHdigits  = RICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = RICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return 0;
  return (AliRICHDigit*)RICHdigits->UncheckedAt(fDigitIndex);
}
//----------------------------------------------------------------------------
void AliRICHPoints::ShowRing(Int_t highlight) {

  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  AliRICHChamber*       iChamber;
  AliRICHSegmentation*  segmentation;

  AliRICHPoints *points = 0;
  TMarker3DBox  *marker = 0;

  AliRICHHit *mHit = GetHit();

  printf("Hit %d on chamber: %d\n",fHitIndex, mHit->fChamber);

  TClonesArray *digits  = RICH->DigitsAddress(mHit->fChamber - 1);
  iChamber = &(RICH->Chamber(mHit->fChamber - 1));
  segmentation=iChamber->GetSegmentationModel();

  Float_t dpx  = segmentation->Dpx();
  Float_t dpy  = segmentation->Dpy();

  int ndigits=digits->GetEntriesFast();

  printf("Show Ring called with %d digits\n",ndigits);

  for (int digit=0;digit<ndigits;digit++) {
    AliRICHDigit *mdig = (AliRICHDigit*)digits->UncheckedAt(digit);
    points = new AliRICHPoints(1);

     //printf("Particle %d belongs to ring %d \n", fTrackIndex, mdig->fTracks[1]);

    if (!points) continue;
    if (fTrackIndex == mdig->fTracks[0]) {

      printf("Digit %d from particle %d belongs to ring %d \n", digit, fTrackIndex, mdig->fTracks[0]);

      Int_t charge=mdig->fSignal;
      Int_t index=Int_t(TMath::Log(charge)/(TMath::Log(adc_satm)/22));
      Int_t color=701+index;
      if (color>722) color=722;
      points->SetMarkerColor(color);
      points->SetMarkerStyle(21);
      points->SetMarkerSize(.5);
      Float_t xpad, ypad;
      segmentation->GetPadCxy(mdig->fPadX, mdig->fPadY,xpad, ypad);
      Float_t VecLoc[3]={xpad,6.276,ypad};
      Float_t  VecGlob[3];
      points->SetParticle(-1);
      points->SetHitIndex(-1);
      points->SetTrackIndex(-1);
      points->SetDigitIndex(digit);
      iChamber->LocaltoGlobal(VecLoc,VecGlob);
      points->SetPoint(0,VecGlob[0],VecGlob[1],VecGlob[2]);

      segmentation->GetPadCxy(mdig->fPadX, mdig->fPadY, xpad, ypad);
      Float_t theta = iChamber->GetRotMatrix()->GetTheta();
      Float_t phi   = iChamber->GetRotMatrix()->GetPhi();
      marker=new TMarker3DBox(VecGlob[0],VecGlob[1],VecGlob[2],
			      dpy/2,0,dpx/2,theta,phi);
      marker->SetLineColor(highlight);
      marker->SetFillStyle(1001);
      marker->SetFillColor(color);
      marker->SetRefObject((TObject*)points);
      points->Set3DMarker(0, marker);

      points->Draw("same");
      for (Int_t im=0;im<3;im++) {
	TMarker3DBox *marker=points->GetMarker(im);
	if (marker)
	  marker->Draw();
      }
      TClonesArray *particles=gAlice->Particles();
      TParticle *p = (TParticle*)particles->UncheckedAt(fIndex);
      printf("\nTrack index %d\n",fTrackIndex);
      printf("Particle ID %d\n",p->GetPdgCode());
      printf("Parent %d\n",p->GetFirstMother());
      printf("First child %d\n",p->GetFirstDaughter());
      printf("Px,Py,Pz %f %f %f\n",p->Px(),p->Py(),p->Pz());
    }
  }
}
//_____________________________________________________________________________
struct Bin {
   const AliRICHDigit *dig;
   int idx;
   Bin() {dig=0; idx=-1;}
};

struct PreCluster : public AliRICHRawCluster {
   const AliRICHDigit* summit;
   int idx;
   int cut;
   int npeaks;
   PreCluster() : AliRICHRawCluster() {cut=npeaks=0;}
};
//_____________________________________________________________________________

static void FindCluster(AliRICHChamber *iChamber, AliRICHSegmentation *segmentation, int i, int j, Bin bins[MAX_Nipx][MAX_Nipy], PreCluster &c)

{

  //
  // Find clusters
  //

  printf("I'm in FindCluster \n");

  Bin& b=bins[i][j];
  Int_t q=b.dig->fSignal;

  printf("FindCluster - i j q %d %d %d\n",i,j,q);

  if (q<0) {
    q=-q;
    c.cut=1;
  }
  if (b.idx >= 0 && b.idx != c.idx) {
    c.idx=b.idx;
    c.npeaks++;
  }

  if (q > TMath::Abs(c.summit->fSignal)) c.summit=b.dig;

  Int_t npx  = segmentation->Npx();
  Int_t npy  = segmentation->Npy();
  Float_t x,y;
  segmentation->GetPadCxy(i-npx, j-npy, x,y);
  printf("FindCluster - x  y %f %f \n",x,y);

  c.fX += q*x;
  c.fY += q*y;
  c.fQ += q;

  b.dig = 0;  b.idx = c.idx;

  if (bins[i-1][j].dig) FindCluster(iChamber,segmentation,i-1,j,bins,c);
  if (bins[i][j-1].dig) FindCluster(iChamber,segmentation,i,j-1,bins,c);
  if (bins[i+1][j].dig) FindCluster(iChamber,segmentation,i+1,j,bins,c);
  if (bins[i][j+1].dig) FindCluster(iChamber,segmentation,i,j+1,bins,c);

}

//_____________________________________________________________________________

void AliRICHPoints::GetCenterOfGravity()
{
  //
  // simple RICH cluster finder from digits -- finds neighbours and
  // calculates center of gravity for the cluster
  //
  const Int_t MAX_nipx=400, MAX_nipy=800;
  printf("\n Hallo world");
  AliRICHDisplay *display=(AliRICHDisplay*)gAlice->Display();
  Int_t chamber=display->GetChamber();
  Int_t cathode=display->GetCathode();

  AliRICH *RICH  = (AliRICH*)gAlice->GetDetector("RICH");
  AliRICHChamber *iChamber;
  AliRICHSegmentation *segmentation;
  iChamber =&(RICH->Chamber(chamber-1));
  segmentation=iChamber->GetSegmentationModel(cathode);
  Int_t npx  = segmentation->Npx();
  Int_t npy  = segmentation->Npy();
  Float_t zpos=iChamber->ZPosition();

  TClonesArray *RICHdigits  = RICH->DigitsAddress(chamber-1);
  gAlice->TreeD()->GetEvent(cathode);
  Int_t ndigits = RICHdigits->GetEntriesFast();
  if (fDigitIndex < 0 || fDigitIndex >= ndigits) return;

  AliRICHDigit  *dig;
  dig=(AliRICHDigit*)RICHdigits->UncheckedAt(fDigitIndex);
  Int_t ipx=dig->fPadX;
  Int_t ipy=dig->fPadY;
  Bin bins[MAX_nipx][MAX_nipy];
  bins[ipx+npx][ipy+npy].dig=dig;

  int ndig;
  int ncls=0;
  for (ndig=0; ndig<ndigits; ndig++) {
      dig = (AliRICHDigit*)RICHdigits->UncheckedAt(ndig);
      int i=dig->fPadX, j=dig->fPadY;
      bins[i+npx][j+npy].dig=dig;
  }

  PreCluster c; c.summit=bins[ipx+npx][ipy+npy].dig; c.idx=ncls;
  FindCluster(iChamber,segmentation,ipx+npx, ipy+npy, bins, c);
  if (c.npeaks>1) {
      printf("GetCenterOfGravity -- more than one peak");
  }
  c.fX /= c.fQ;
  c.fY /= c.fQ;
  printf("GetCenterOfGravity - c.fX c.fY c.fQ %f %f %d \n",c.fX,c.fY,c.fQ);

  c.fTracks[0]=c.summit->fTracks[0];
  c.fTracks[1]=c.summit->fTracks[1];
  c.fTracks[2]=c.summit->fTracks[2];
  ncls++;
  AliRICHPoints *points = 0;
  points = new AliRICHPoints(1);
  points->SetMarkerColor(kYellow);
  points->SetMarkerStyle(5);
  points->SetMarkerSize(1.);
  points->SetPoint(0,c.fX,c.fY,zpos);
  points->Draw();

  printf("GetCenterOfGravity -- ncls %d \n",ncls);

}

//_____________________________________________________________________________
const Text_t *AliRICHPoints::GetName() const
{
  //
  // Return name of the Geant3 particle corresponding to this point
  //
  TParticle *particle = GetParticle();
  if (!particle) return "Particle";
  return particle->GetName();
}

//_____________________________________________________________________________
Text_t *AliRICHPoints::GetObjectInfo(Int_t, Int_t)
{
  //
  //   Redefines TObject::GetObjectInfo.
  //   Displays the info (particle,etc
  //   corresponding to cursor position px,py
  //
  static char info[64];
  sprintf(info,"%s %d",GetName(),fIndex);
  return info;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2008, John Wiegley.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * - Neither the name of New Artisans LLC nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 THE COPYRIGHT
 * OWNER 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 "session.h"
#include "report.h"
#include "handler.h"
#include "iterators.h"
#include "filters.h"

namespace ledger {

session_t * session_t::current = NULL;

#if 0
boost::mutex session_t::session_mutex;
#endif

void set_session_context(session_t * session)
{
#if 0
  session_t::session_mutex.lock();
#endif

  if (session && ! session_t::current) {
    session_t::initialize();
  }
  else if (! session && session_t::current) {
    session_t::shutdown();
#if 0
    session_t::session_mutex.unlock();
#endif
  }

  session_t::current = session;
}

void release_session_context()
{
#if 0
  session_t::session_mutex.unlock();
#endif
}

session_t::session_t()
  : register_format
    ("%-.9D %-.20P %-.23A %!12(print_balance(fmt_t, 12, 67)) "
     "%!12(print_balance(fmt_T, 12, 80, true))\n%/"
     "%32|%-.22A %!12(print_balance(fmt_t, 12, 67)) "
     "%!12(print_balance(fmt_T, 12, 80, true))\n"),
    wide_register_format
    ("%-.9D  %-.35P %-.39A %22.108t %!22.132T\n%/"
     "%48|%-.38A %22.108t %!22.132T\n"),
    print_format
    ("\n%d %Y%C%P\n    %-34W  %12o%n\n%/    %-34W  %12o%n\n"),
    balance_format
    ("%20T  %_%-a\n"),
    equity_format
    ("\n%D %Y%C%P\n%/    %-34W  %12t\n"),
    plot_amount_format
    ("%D %(S(t))\n"),
    plot_total_format
    ("%D %(S(T))\n"),
    write_hdr_format
    ("%d %Y%C%P\n"),
    write_xact_format
    ("    %-34W  %12o%n\n"),
    prices_format
    ("%[%Y/%m/%d %H:%M:%S %Z]   %-10A %12t %12T\n"),
    pricesdb_format
    ("P %[%Y/%m/%d %H:%M:%S] %A %t\n"),

    pricing_leeway(24 * 3600),

    download_quotes(false),
    use_cache(true),
    cache_dirty(false),

    now(now),

#if 0
    elision_style(ABBREVIATE),
#endif
    abbrev_length(2),

    ansi_codes(false),
    ansi_invert(false),

    master(new account_t(this, NULL, ""))
{
  TRACE_CTOR(session_t, "");
}

session_t::~session_t()
{
  TRACE_DTOR(session_t);
}

std::size_t session_t::read_journal(journal_t&	  journal,
				    std::istream& in,
				    const path&	  pathname,
				    account_t *   master)
{
  if (! master)
    master = journal.master;

  foreach (journal_t::parser_t& parser, parsers)
    if (parser.test(in))
      return parser.parse(in, *this, journal, master, &pathname);

  return 0;
}

std::size_t session_t::read_journal(journal_t&	journal,
				    const path& pathname,
				    account_t * master)
{
  journal.sources.push_back(pathname);

  if (! exists(pathname))
    throw_(std::logic_error, "Cannot read file" << pathname);

  ifstream stream(pathname);
  return read_journal(journal, stream, pathname, master);
}

void session_t::read_init()
{
  if (! init_file)
    return;

  if (! exists(*init_file))
    throw_(std::logic_error, "Cannot read init file" << *init_file);

  ifstream init(*init_file);

  journal_t temp(this);
  if (read_journal(temp, *init_file) > 0 ||
      temp.auto_entries.size() > 0 ||
      temp.period_entries.size() > 0)
    throw_(parse_error, "Entries found in initialization file '" <<
	   init_file << "'");
}

std::size_t session_t::read_data(journal_t&    journal,
				 const string& master_account)
{
  if (data_file.empty())
    throw_(parse_error, "No journal file was specified (please use -f)");

  TRACE_START(parser, 1, "Parsing journal file");

  std::size_t entry_count = 0;

  read_init();

  DEBUG("ledger.cache", "3. use_cache = " << use_cache);

  if (use_cache && cache_file) {
    DEBUG("ledger.cache", "using_cache " << cache_file->string());
    cache_dirty = true;
    if (exists(*cache_file)) {
      push_variable<optional<path> >
	save_price_db(journal.price_db, price_db);

      entry_count += read_journal(journal, *cache_file);
      if (entry_count > 0)
	cache_dirty = false;
    }
  }

  if (entry_count == 0) {
    account_t * acct = NULL;
    if (! master_account.empty())
      acct = journal.find_account(master_account);

    journal.price_db = price_db;
    if (journal.price_db && exists(*journal.price_db)) {
      if (read_journal(journal, *journal.price_db)) {
	throw_(parse_error, "Entries not allowed in price history file");
      } else {
	DEBUG("ledger.cache",
	      "read price database " << journal.price_db->string());
	journal.sources.pop_back();
      }
    }

    DEBUG("ledger.cache", "rejected cache, parsing " << data_file.string());
    if (data_file == "-") {
      use_cache = false;
      journal.sources.push_back("/dev/stdin");
      entry_count += read_journal(journal, std::cin, "/dev/stdin", acct);
    }
    else if (exists(data_file)) {
      entry_count += read_journal(journal, data_file, acct);
      if (journal.price_db)
	journal.sources.push_back(*journal.price_db);
      clean_accounts();
    }
  }

  VERIFY(journal.valid());

  TRACE_STOP(parser, 1);

  return entry_count;
}

namespace {
  account_t * find_account_re_(account_t * account, const mask_t& regexp)
  {
    if (regexp.match(account->fullname()))
      return account;

    foreach (accounts_map::value_type& pair, account->accounts)
      if (account_t * a = find_account_re_(pair.second, regexp))
	return a;

    return NULL;
  }
}

account_t * session_t::find_account_re(const string& regexp)
{
  return find_account_re_(master.get(), mask_t(regexp));
}

void session_t::clean_xacts()
{
  session_xacts_iterator walker(*this);
  pass_down_xacts
    (xact_handler_ptr(new clear_xact_xdata), walker);
}

void session_t::clean_xacts(entry_t& entry)
{
  entry_xacts_iterator walker(entry);
  pass_down_xacts(xact_handler_ptr(new clear_xact_xdata), walker);
}

void session_t::clean_accounts()
{
  basic_accounts_iterator acct_walker(*master);
  pass_down_accounts(acct_handler_ptr(new clear_account_xdata),
		     acct_walker);
}

#if 0
value_t session_t::resolve(const string& name, expr_t::scope_t& locals)
{
  const char * p = name.c_str();
  switch (*p) {
  case 'd':
#if 0
    if (name == "date_format") {
      // jww (2007-04-18): What to do here?
      return string_value(moment_t::output_format);
    }
#endif
    break;

  case 'n':
    switch (*++p) {
    case 'o':
      if (name == "now")
	return value_t(now);
      break;
    }
    break;

  case 'r':
    if (name == "register_format")
      return string_value(register_format);
    break;
  }
  return expr_t::scope_t::resolve(name, locals);
}
#endif

expr_t::ptr_op_t session_t::lookup(const string& name)
{
  const char * p = name.c_str();
  switch (*p) {
  case 'b':
    if (std::strcmp(p, "balance_format") == 0)
      return expr_t::op_t::wrap_value(string_value(balance_format));
    break;

  case 'e':
    if (std::strcmp(p, "equity_format") == 0)
      return expr_t::op_t::wrap_value(string_value(equity_format));
    break;

  case 'p':
    if (std::strcmp(p, "plot_amount_format") == 0)
      return expr_t::op_t::wrap_value(string_value(plot_amount_format));
    else if (std::strcmp(p, "plot_total_format") == 0)
      return expr_t::op_t::wrap_value(string_value(plot_total_format));
    else if (std::strcmp(p, "prices_format") == 0)
      return expr_t::op_t::wrap_value(string_value(prices_format));
    else if (std::strcmp(p, "pricesdb_format") == 0)
      return expr_t::op_t::wrap_value(string_value(pricesdb_format));
    else if (std::strcmp(p, "print_format") == 0)
      return expr_t::op_t::wrap_value(string_value(print_format));
    break;

  case 'r':
    if (std::strcmp(p, "register_format") == 0)
      return expr_t::op_t::wrap_value(string_value(register_format));
    break;

  case 'w':
    if (std::strcmp(p, "wide_register_format") == 0)
      return expr_t::op_t::wrap_value(string_value(wide_register_format));
    else if (std::strcmp(p, "write_hdr_format") == 0)
      return expr_t::op_t::wrap_value(string_value(write_hdr_format));
    else if (std::strcmp(p, "write_xact_format") == 0)
      return expr_t::op_t::wrap_value(string_value(write_xact_format));
    break;

  case 'o':
    if (std::strncmp(p, "opt_", 4) == 0) {
      p = p + 4;
      switch (*p) {
      case 'd':
	if (std::strcmp(p, "debug_") == 0)
	  return MAKE_FUNCTOR(session_t::option_debug_);
	break;

      case 'f':
	if ((*(p + 1) == '_' && ! *(p + 2)) ||
	    std::strcmp(p, "file_") == 0)
	  return MAKE_FUNCTOR(session_t::option_file_);
	break;

      case 't':
	if (std::strcmp(p, "trace_") == 0)
	  return MAKE_FUNCTOR(session_t::option_trace_);
	break;

      case 'v':
	if (! *(p + 1) || std::strcmp(p, "verbose") == 0)
	  return MAKE_FUNCTOR(session_t::option_verbose);
	else if (std::strcmp(p, "version") == 0)
	  return MAKE_FUNCTOR(session_t::option_version);
	else if (std::strcmp(p, "verify") == 0)
	  return MAKE_FUNCTOR(session_t::option_verify);
	break;
      }
    }
    break;
  }

  return expr_t::ptr_op_t();
}

// jww (2007-04-26): All of Ledger should be accessed through a
// session_t object
void session_t::initialize()
{
  amount_t::initialize();
  value_t::initialize();
  expr_t::initialize();
}

void session_t::shutdown()
{
  expr_t::shutdown();
  value_t::shutdown();
  amount_t::shutdown();
}

} // namespace ledger
<commit_msg>Corrected the formatting of second-lines in the register report.<commit_after>/*
 * Copyright (c) 2003-2008, John Wiegley.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * - Neither the name of New Artisans LLC nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 THE COPYRIGHT
 * OWNER 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 "session.h"
#include "report.h"
#include "handler.h"
#include "iterators.h"
#include "filters.h"

namespace ledger {

session_t * session_t::current = NULL;

#if 0
boost::mutex session_t::session_mutex;
#endif

void set_session_context(session_t * session)
{
#if 0
  session_t::session_mutex.lock();
#endif

  if (session && ! session_t::current) {
    session_t::initialize();
  }
  else if (! session && session_t::current) {
    session_t::shutdown();
#if 0
    session_t::session_mutex.unlock();
#endif
  }

  session_t::current = session;
}

void release_session_context()
{
#if 0
  session_t::session_mutex.unlock();
#endif
}

session_t::session_t()
  : register_format
    ("%-.9D %-.20P %-.23A %!12(print_balance(fmt_t, 12, 67)) "
     "%!12(print_balance(fmt_T, 12, 80, true))\n%/"
     "%31|%-.23A %!12(print_balance(fmt_t, 12, 67)) "
     "%!12(print_balance(fmt_T, 12, 80, true))\n"),
    wide_register_format
    ("%-.9D  %-.35P %-.39A %22.108t %!22.132T\n%/"
     "%48|%-.38A %22.108t %!22.132T\n"),
    print_format
    ("\n%d %Y%C%P\n    %-34W  %12o%n\n%/    %-34W  %12o%n\n"),
    balance_format
    ("%20T  %_%-a\n"),
    equity_format
    ("\n%D %Y%C%P\n%/    %-34W  %12t\n"),
    plot_amount_format
    ("%D %(S(t))\n"),
    plot_total_format
    ("%D %(S(T))\n"),
    write_hdr_format
    ("%d %Y%C%P\n"),
    write_xact_format
    ("    %-34W  %12o%n\n"),
    prices_format
    ("%[%Y/%m/%d %H:%M:%S %Z]   %-10A %12t %12T\n"),
    pricesdb_format
    ("P %[%Y/%m/%d %H:%M:%S] %A %t\n"),

    pricing_leeway(24 * 3600),

    download_quotes(false),
    use_cache(true),
    cache_dirty(false),

    now(now),

#if 0
    elision_style(ABBREVIATE),
#endif
    abbrev_length(2),

    ansi_codes(false),
    ansi_invert(false),

    master(new account_t(this, NULL, ""))
{
  TRACE_CTOR(session_t, "");
}

session_t::~session_t()
{
  TRACE_DTOR(session_t);
}

std::size_t session_t::read_journal(journal_t&	  journal,
				    std::istream& in,
				    const path&	  pathname,
				    account_t *   master)
{
  if (! master)
    master = journal.master;

  foreach (journal_t::parser_t& parser, parsers)
    if (parser.test(in))
      return parser.parse(in, *this, journal, master, &pathname);

  return 0;
}

std::size_t session_t::read_journal(journal_t&	journal,
				    const path& pathname,
				    account_t * master)
{
  journal.sources.push_back(pathname);

  if (! exists(pathname))
    throw_(std::logic_error, "Cannot read file" << pathname);

  ifstream stream(pathname);
  return read_journal(journal, stream, pathname, master);
}

void session_t::read_init()
{
  if (! init_file)
    return;

  if (! exists(*init_file))
    throw_(std::logic_error, "Cannot read init file" << *init_file);

  ifstream init(*init_file);

  journal_t temp(this);
  if (read_journal(temp, *init_file) > 0 ||
      temp.auto_entries.size() > 0 ||
      temp.period_entries.size() > 0)
    throw_(parse_error, "Entries found in initialization file '" <<
	   init_file << "'");
}

std::size_t session_t::read_data(journal_t&    journal,
				 const string& master_account)
{
  if (data_file.empty())
    throw_(parse_error, "No journal file was specified (please use -f)");

  TRACE_START(parser, 1, "Parsing journal file");

  std::size_t entry_count = 0;

  read_init();

  DEBUG("ledger.cache", "3. use_cache = " << use_cache);

  if (use_cache && cache_file) {
    DEBUG("ledger.cache", "using_cache " << cache_file->string());
    cache_dirty = true;
    if (exists(*cache_file)) {
      push_variable<optional<path> >
	save_price_db(journal.price_db, price_db);

      entry_count += read_journal(journal, *cache_file);
      if (entry_count > 0)
	cache_dirty = false;
    }
  }

  if (entry_count == 0) {
    account_t * acct = NULL;
    if (! master_account.empty())
      acct = journal.find_account(master_account);

    journal.price_db = price_db;
    if (journal.price_db && exists(*journal.price_db)) {
      if (read_journal(journal, *journal.price_db)) {
	throw_(parse_error, "Entries not allowed in price history file");
      } else {
	DEBUG("ledger.cache",
	      "read price database " << journal.price_db->string());
	journal.sources.pop_back();
      }
    }

    DEBUG("ledger.cache", "rejected cache, parsing " << data_file.string());
    if (data_file == "-") {
      use_cache = false;
      journal.sources.push_back("/dev/stdin");
      entry_count += read_journal(journal, std::cin, "/dev/stdin", acct);
    }
    else if (exists(data_file)) {
      entry_count += read_journal(journal, data_file, acct);
      if (journal.price_db)
	journal.sources.push_back(*journal.price_db);
      clean_accounts();
    }
  }

  VERIFY(journal.valid());

  TRACE_STOP(parser, 1);

  return entry_count;
}

namespace {
  account_t * find_account_re_(account_t * account, const mask_t& regexp)
  {
    if (regexp.match(account->fullname()))
      return account;

    foreach (accounts_map::value_type& pair, account->accounts)
      if (account_t * a = find_account_re_(pair.second, regexp))
	return a;

    return NULL;
  }
}

account_t * session_t::find_account_re(const string& regexp)
{
  return find_account_re_(master.get(), mask_t(regexp));
}

void session_t::clean_xacts()
{
  session_xacts_iterator walker(*this);
  pass_down_xacts
    (xact_handler_ptr(new clear_xact_xdata), walker);
}

void session_t::clean_xacts(entry_t& entry)
{
  entry_xacts_iterator walker(entry);
  pass_down_xacts(xact_handler_ptr(new clear_xact_xdata), walker);
}

void session_t::clean_accounts()
{
  basic_accounts_iterator acct_walker(*master);
  pass_down_accounts(acct_handler_ptr(new clear_account_xdata),
		     acct_walker);
}

#if 0
value_t session_t::resolve(const string& name, expr_t::scope_t& locals)
{
  const char * p = name.c_str();
  switch (*p) {
  case 'd':
#if 0
    if (name == "date_format") {
      // jww (2007-04-18): What to do here?
      return string_value(moment_t::output_format);
    }
#endif
    break;

  case 'n':
    switch (*++p) {
    case 'o':
      if (name == "now")
	return value_t(now);
      break;
    }
    break;

  case 'r':
    if (name == "register_format")
      return string_value(register_format);
    break;
  }
  return expr_t::scope_t::resolve(name, locals);
}
#endif

expr_t::ptr_op_t session_t::lookup(const string& name)
{
  const char * p = name.c_str();
  switch (*p) {
  case 'b':
    if (std::strcmp(p, "balance_format") == 0)
      return expr_t::op_t::wrap_value(string_value(balance_format));
    break;

  case 'e':
    if (std::strcmp(p, "equity_format") == 0)
      return expr_t::op_t::wrap_value(string_value(equity_format));
    break;

  case 'p':
    if (std::strcmp(p, "plot_amount_format") == 0)
      return expr_t::op_t::wrap_value(string_value(plot_amount_format));
    else if (std::strcmp(p, "plot_total_format") == 0)
      return expr_t::op_t::wrap_value(string_value(plot_total_format));
    else if (std::strcmp(p, "prices_format") == 0)
      return expr_t::op_t::wrap_value(string_value(prices_format));
    else if (std::strcmp(p, "pricesdb_format") == 0)
      return expr_t::op_t::wrap_value(string_value(pricesdb_format));
    else if (std::strcmp(p, "print_format") == 0)
      return expr_t::op_t::wrap_value(string_value(print_format));
    break;

  case 'r':
    if (std::strcmp(p, "register_format") == 0)
      return expr_t::op_t::wrap_value(string_value(register_format));
    break;

  case 'w':
    if (std::strcmp(p, "wide_register_format") == 0)
      return expr_t::op_t::wrap_value(string_value(wide_register_format));
    else if (std::strcmp(p, "write_hdr_format") == 0)
      return expr_t::op_t::wrap_value(string_value(write_hdr_format));
    else if (std::strcmp(p, "write_xact_format") == 0)
      return expr_t::op_t::wrap_value(string_value(write_xact_format));
    break;

  case 'o':
    if (std::strncmp(p, "opt_", 4) == 0) {
      p = p + 4;
      switch (*p) {
      case 'd':
	if (std::strcmp(p, "debug_") == 0)
	  return MAKE_FUNCTOR(session_t::option_debug_);
	break;

      case 'f':
	if ((*(p + 1) == '_' && ! *(p + 2)) ||
	    std::strcmp(p, "file_") == 0)
	  return MAKE_FUNCTOR(session_t::option_file_);
	break;

      case 't':
	if (std::strcmp(p, "trace_") == 0)
	  return MAKE_FUNCTOR(session_t::option_trace_);
	break;

      case 'v':
	if (! *(p + 1) || std::strcmp(p, "verbose") == 0)
	  return MAKE_FUNCTOR(session_t::option_verbose);
	else if (std::strcmp(p, "version") == 0)
	  return MAKE_FUNCTOR(session_t::option_version);
	else if (std::strcmp(p, "verify") == 0)
	  return MAKE_FUNCTOR(session_t::option_verify);
	break;
      }
    }
    break;
  }

  return expr_t::ptr_op_t();
}

// jww (2007-04-26): All of Ledger should be accessed through a
// session_t object
void session_t::initialize()
{
  amount_t::initialize();
  value_t::initialize();
  expr_t::initialize();
}

void session_t::shutdown()
{
  expr_t::shutdown();
  value_t::shutdown();
  amount_t::shutdown();
}

} // namespace ledger
<|endoftext|>


<commit_before>#include "routing/routing_helpers.hpp"
#include "routing/road_point.hpp"

#include "traffic/traffic_info.hpp"

namespace routing
{
using namespace traffic;

void ReconstructRoute(IDirectionsEngine * engine, IRoadGraph const & graph,
                      shared_ptr<TrafficInfo::Coloring> const & trafficColoring,
                      my::Cancellable const & cancellable, vector<Junction> & path, Route & route)
{
  if (path.empty())
  {
    LOG(LERROR, ("Can't reconstruct route from an empty list of positions."));
    return;
  }

  // By some reason there're two adjacent positions on a road with
  // the same end-points. This could happen, for example, when
  // direction on a road was changed.  But it doesn't matter since
  // this code reconstructs only geometry of a route.
  path.erase(unique(path.begin(), path.end()), path.end());

  Route::TTimes times;
  Route::TTurns turnsDir;
  vector<Junction> junctions;
  // @TODO(bykoianko) streetNames is not filled in Generate(). It should be done.
  Route::TStreets streetNames;
  vector<TrafficInfo::RoadSegmentId> trafficSegs;
  if (engine)
    engine->Generate(graph, path, times, turnsDir, junctions, trafficSegs, cancellable);

  // @TODO(bykoianko) If the start and the finish of a route lies on the same road segment
  // engine->Generate() fills with empty vectors |times|, |turnsDir|, |junctions| and |trafficSegs|.
  // It's not correct and should be fixed. It's necessary to work corrrectly with such routes.

  vector<m2::PointD> routeGeometry;
  JunctionsToPoints(junctions, routeGeometry);
  feature::TAltitudes altitudes;
  JunctionsToAltitudes(junctions, altitudes);

  route.SetGeometry(routeGeometry.begin(), routeGeometry.end());
  route.SetSectionTimes(move(times));
  route.SetTurnInstructions(move(turnsDir));
  route.SetStreetNames(move(streetNames));
  route.SetAltitudes(move(altitudes));

  vector<traffic::SpeedGroup> traffic;
  if (trafficColoring && !trafficSegs.empty())
  {
    traffic.reserve(2 * trafficSegs.size());
    for (TrafficInfo::RoadSegmentId const & seg : trafficSegs)
    {
      auto const it = trafficColoring->find(seg);
      SpeedGroup const segTraffic = (it == trafficColoring->cend()) ? SpeedGroup::Unknown
                                                               : it->second;
      // @TODO It's written to compensate an error. The problem is in case of any routing except for osrm
      // all route points except for begining and ending are duplicated.
      // See a TODO in BicycleDirectionsEngine::Generate() for details.
      // At this moment the route looks like:
      // 0----1    4----5
      //      2----3    6---7
      // This route consists of 4 edges and there're 4 items in trafficSegs.
      // But it has 8 items in routeGeometry.
      // So for segments 0-1 and 1-2 let's set trafficSegs[0]
      // for segments 2-3 and 3-4 let's set trafficSegs[1]
      // for segments 4-5 and 5-6 let's set trafficSegs[2]
      // and for segment 6-7 let's set trafficSegs[3]
      traffic.insert(traffic.end(), {segTraffic, segTraffic});
    }
    CHECK(!traffic.empty(), ());
    traffic.pop_back();
  }

  route.SetTraffic(move(traffic));
}
}  // namespace rouing
<commit_msg>[routing] Crashfix. Processing errors while turn generation.<commit_after>#include "routing/routing_helpers.hpp"
#include "routing/road_point.hpp"

#include "traffic/traffic_info.hpp"

namespace routing
{
using namespace traffic;

void ReconstructRoute(IDirectionsEngine * engine, IRoadGraph const & graph,
                      shared_ptr<TrafficInfo::Coloring> const & trafficColoring,
                      my::Cancellable const & cancellable, vector<Junction> & path, Route & route)
{
  if (path.empty())
  {
    LOG(LERROR, ("Can't reconstruct route from an empty list of positions."));
    return;
  }

  // By some reason there're two adjacent positions on a road with
  // the same end-points. This could happen, for example, when
  // direction on a road was changed.  But it doesn't matter since
  // this code reconstructs only geometry of a route.
  path.erase(unique(path.begin(), path.end()), path.end());

  Route::TTimes times;
  Route::TTurns turnsDir;
  vector<Junction> junctions;
  // @TODO(bykoianko) streetNames is not filled in Generate(). It should be done.
  Route::TStreets streetNames;
  vector<TrafficInfo::RoadSegmentId> trafficSegs;
  if (engine)
    engine->Generate(graph, path, times, turnsDir, junctions, trafficSegs, cancellable);

  if (cancellable.IsCancelled())
    return;

  // In case of any errors in IDirectionsEngine::Generate() |junctions| is empty.
  if (junctions.empty())
  {
    LOG(LERROR, ("Internal error happened while turn generation."));
    return;
  }

  // @TODO(bykoianko) If the start and the finish of a route lies on the same road segment
  // engine->Generate() fills with empty vectors |times|, |turnsDir|, |junctions| and |trafficSegs|.
  // It's not correct and should be fixed. It's necessary to work corrrectly with such routes.

  vector<m2::PointD> routeGeometry;
  JunctionsToPoints(junctions, routeGeometry);
  feature::TAltitudes altitudes;
  JunctionsToAltitudes(junctions, altitudes);

  route.SetGeometry(routeGeometry.begin(), routeGeometry.end());
  route.SetSectionTimes(move(times));
  route.SetTurnInstructions(move(turnsDir));
  route.SetStreetNames(move(streetNames));
  route.SetAltitudes(move(altitudes));

  vector<traffic::SpeedGroup> traffic;
  if (trafficColoring && !trafficSegs.empty())
  {
    traffic.reserve(2 * trafficSegs.size());
    for (TrafficInfo::RoadSegmentId const & seg : trafficSegs)
    {
      auto const it = trafficColoring->find(seg);
      SpeedGroup const segTraffic = (it == trafficColoring->cend()) ? SpeedGroup::Unknown
                                                               : it->second;
      // @TODO It's written to compensate an error. The problem is in case of any routing except for osrm
      // all route points except for begining and ending are duplicated.
      // See a TODO in BicycleDirectionsEngine::Generate() for details.
      // At this moment the route looks like:
      // 0----1    4----5
      //      2----3    6---7
      // This route consists of 4 edges and there're 4 items in trafficSegs.
      // But it has 8 items in routeGeometry.
      // So for segments 0-1 and 1-2 let's set trafficSegs[0]
      // for segments 2-3 and 3-4 let's set trafficSegs[1]
      // for segments 4-5 and 5-6 let's set trafficSegs[2]
      // and for segment 6-7 let's set trafficSegs[3]
      traffic.insert(traffic.end(), {segTraffic, segTraffic});
    }
    CHECK(!traffic.empty(), ());
    traffic.pop_back();
  }

  route.SetTraffic(move(traffic));
}
}  // namespace rouing
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "TiffEntry.h"
#include <math.h>
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffEntry::TiffEntry() {
  own_data = NULL;
}

TiffEntry::TiffEntry(FileMap* f, uint32 offset) {
  own_data = NULL;
  unsigned short* p = (unsigned short*)f->getData(offset);
  tag = (TiffTag)p[0];
  type = (TiffDataType)p[1];
  count = *(int*)f->getData(offset + 4);
  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);
  uint32 bytesize = count << datashifts[type];
  if (bytesize <= 4) {
    data = f->getDataWrt(offset + 8);
  } else { // offset
    data_offset = *(uint32*)f->getData(offset + 8);
    CHECKSIZE(data_offset + bytesize);
    data = f->getDataWrt(data_offset);
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntry::TiffEntry(TiffTag _tag, TiffDataType _type, uint32 _count, const uchar8* _data )
{
  tag = _tag;
  type = _type;
  count = _count;
  if (NULL == _data) {
    uint32 bytesize = _count << datashifts[_type];
    own_data = new uchar8[bytesize];
    memset(own_data,0,bytesize);
    data = own_data;
  } else {
    data = _data;
    own_data = NULL;
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntry::~TiffEntry(void) {
  if (own_data)
    delete[] own_data;
}

bool TiffEntry::isInt() {
  return (type == TIFF_LONG || type == TIFF_SHORT || type ==  TIFF_BYTE);
}

unsigned int TiffEntry::getInt() {
  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_BYTE))
    ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Long, Short or Byte", type);
  if (type == TIFF_BYTE)
    return getByte();
  if (type == TIFF_SHORT)
    return getShort();
  return (uint32)data[3] << 24 | (uint32)data[2] << 16 | (uint32)data[1] << 8 | (uint32)data[0];
}

unsigned short TiffEntry::getShort() {
  if (type != TIFF_SHORT)
    ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type);
  return ((ushort16)data[1] << 8) | (ushort16)data[0];
}

const uint32* TiffEntry::getIntArray() {
  if (type != TIFF_LONG && type != TIFF_RATIONAL && type != TIFF_SRATIONAL && type != TIFF_UNDEFINED )
    ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Long", type);
  return (uint32*)&data[0];
}

const ushort16* TiffEntry::getShortArray() {
  if (type != TIFF_SHORT)
    ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type);
  return (ushort16*)&data[0];
}

uchar8 TiffEntry::getByte() {
  if (type != TIFF_BYTE)
    ThrowTPE("TIFF, getByte: Wrong type 0x%x encountered. Expected Byte", type);
  return data[0];
}

bool TiffEntry::isFloat() {
  return (type == TIFF_FLOAT || type == TIFF_DOUBLE || type == TIFF_RATIONAL || type == TIFF_SRATIONAL || type == TIFF_LONG || type == TIFF_SHORT);
}

float TiffEntry::getFloat() {
  if (!(type == TIFF_FLOAT || type == TIFF_DOUBLE || type == TIFF_RATIONAL || type == TIFF_SRATIONAL || type == TIFF_LONG || type == TIFF_SHORT))
    ThrowTPE("TIFF, getFloat: Wrong type 0x%x encountered. Expected Float", type);
  if (type == TIFF_DOUBLE) {
    return (float)*(double*)&data[0];
  } else if (type == TIFF_FLOAT) {
    return *(float*)&data[0];
  } else if (type == TIFF_LONG || type == TIFF_SHORT) {
    return (float)getInt();
  } else if (type == TIFF_RATIONAL) {
    const unsigned int* t = getIntArray();
    if (t[1])
      return (float)t[0]/t[1];
  } else if (type == TIFF_SRATIONAL) {
    const int* t = (const int*)getIntArray();
    if (t[1])
      return (float)t[0]/t[1];
  }
  return 0.0f;
}

string TiffEntry::getString() {
  if (type != TIFF_ASCII)
    ThrowTPE("TIFF, getString: Wrong type 0x%x encountered. Expected Ascii", type);
  if (!own_data) {
    own_data = new uchar8[count];
    memcpy(own_data, data, count);
    own_data[count-1] = 0;  // Ensure string is not larger than count defines
  }
  return string((const char*)&data[0]);
}

bool TiffEntry::isString() {
  return (type == TIFF_ASCII);
}

int TiffEntry::getElementSize() {
  return datasizes[type];
}

int TiffEntry::getElementShift() {
  return datashifts[type];
}

void TiffEntry::setData( const void *in_data, uint32 byte_count )
{
  uint32 bytesize = count << datashifts[type];
  if (byte_count > bytesize)
    ThrowTPE("TIFF, data set larger than entry size given");

  if (!own_data) {
    own_data = new uchar8[bytesize];
    memcpy(own_data, data, bytesize);
  }
  memcpy(own_data, in_data, byte_count);
}

uchar8* TiffEntry::getDataWrt()
{
  if (!own_data) {
    uint32 bytesize = count << datashifts[type];
    own_data = new uchar8[bytesize];
    memcpy(own_data, data, bytesize);
  }
  return own_data;
}

#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif

std::string TiffEntry::getValueAsString()
{
  if (type == TIFF_ASCII)
    return string((const char*)&data[0]);
  char *temp_string = new char[4096];
  if (count == 1) {
    switch (type) {
      case TIFF_LONG:
        sprintf(temp_string, "Long: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_SHORT:
        sprintf(temp_string, "Short: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_BYTE:
        sprintf(temp_string, "Byte: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_FLOAT:
        sprintf(temp_string, "Float: %f", getFloat());
        break;
      case TIFF_RATIONAL:
      case TIFF_SRATIONAL:
        sprintf(temp_string, "Rational Number: %f", getFloat());
        break;
      default:
        sprintf(temp_string, "Type: %x: ", type);
        for (uint32 i = 0; i < datasizes[type]; i++) {
          sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
        }
    }
  }
  string ret(temp_string);
  delete temp_string;
  return ret;
}

} // namespace RawSpeed
<commit_msg>Actually return our copied safe data.<commit_after>#include "StdAfx.h"
#include "TiffEntry.h"
#include <math.h>
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffEntry::TiffEntry() {
  own_data = NULL;
}

TiffEntry::TiffEntry(FileMap* f, uint32 offset) {
  own_data = NULL;
  unsigned short* p = (unsigned short*)f->getData(offset);
  tag = (TiffTag)p[0];
  type = (TiffDataType)p[1];
  count = *(int*)f->getData(offset + 4);
  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);
  uint32 bytesize = count << datashifts[type];
  if (bytesize <= 4) {
    data = f->getDataWrt(offset + 8);
  } else { // offset
    data_offset = *(uint32*)f->getData(offset + 8);
    CHECKSIZE(data_offset + bytesize);
    data = f->getDataWrt(data_offset);
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntry::TiffEntry(TiffTag _tag, TiffDataType _type, uint32 _count, const uchar8* _data )
{
  tag = _tag;
  type = _type;
  count = _count;
  if (NULL == _data) {
    uint32 bytesize = _count << datashifts[_type];
    own_data = new uchar8[bytesize];
    memset(own_data,0,bytesize);
    data = own_data;
  } else {
    data = _data;
    own_data = NULL;
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntry::~TiffEntry(void) {
  if (own_data)
    delete[] own_data;
}

bool TiffEntry::isInt() {
  return (type == TIFF_LONG || type == TIFF_SHORT || type ==  TIFF_BYTE);
}

unsigned int TiffEntry::getInt() {
  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_BYTE))
    ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Long, Short or Byte", type);
  if (type == TIFF_BYTE)
    return getByte();
  if (type == TIFF_SHORT)
    return getShort();
  return (uint32)data[3] << 24 | (uint32)data[2] << 16 | (uint32)data[1] << 8 | (uint32)data[0];
}

unsigned short TiffEntry::getShort() {
  if (type != TIFF_SHORT)
    ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type);
  return ((ushort16)data[1] << 8) | (ushort16)data[0];
}

const uint32* TiffEntry::getIntArray() {
  if (type != TIFF_LONG && type != TIFF_RATIONAL && type != TIFF_SRATIONAL && type != TIFF_UNDEFINED )
    ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Long", type);
  return (uint32*)&data[0];
}

const ushort16* TiffEntry::getShortArray() {
  if (type != TIFF_SHORT)
    ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type);
  return (ushort16*)&data[0];
}

uchar8 TiffEntry::getByte() {
  if (type != TIFF_BYTE)
    ThrowTPE("TIFF, getByte: Wrong type 0x%x encountered. Expected Byte", type);
  return data[0];
}

bool TiffEntry::isFloat() {
  return (type == TIFF_FLOAT || type == TIFF_DOUBLE || type == TIFF_RATIONAL || type == TIFF_SRATIONAL || type == TIFF_LONG || type == TIFF_SHORT);
}

float TiffEntry::getFloat() {
  if (!(type == TIFF_FLOAT || type == TIFF_DOUBLE || type == TIFF_RATIONAL || type == TIFF_SRATIONAL || type == TIFF_LONG || type == TIFF_SHORT))
    ThrowTPE("TIFF, getFloat: Wrong type 0x%x encountered. Expected Float", type);
  if (type == TIFF_DOUBLE) {
    return (float)*(double*)&data[0];
  } else if (type == TIFF_FLOAT) {
    return *(float*)&data[0];
  } else if (type == TIFF_LONG || type == TIFF_SHORT) {
    return (float)getInt();
  } else if (type == TIFF_RATIONAL) {
    const unsigned int* t = getIntArray();
    if (t[1])
      return (float)t[0]/t[1];
  } else if (type == TIFF_SRATIONAL) {
    const int* t = (const int*)getIntArray();
    if (t[1])
      return (float)t[0]/t[1];
  }
  return 0.0f;
}

string TiffEntry::getString() {
  if (type != TIFF_ASCII)
    ThrowTPE("TIFF, getString: Wrong type 0x%x encountered. Expected Ascii", type);
  if (!own_data) {
    own_data = new uchar8[count];
    memcpy(own_data, data, count);
    own_data[count-1] = 0;  // Ensure string is not larger than count defines
  }
  return string((const char*)&own_data[0]);
}

bool TiffEntry::isString() {
  return (type == TIFF_ASCII);
}

int TiffEntry::getElementSize() {
  return datasizes[type];
}

int TiffEntry::getElementShift() {
  return datashifts[type];
}

void TiffEntry::setData( const void *in_data, uint32 byte_count )
{
  uint32 bytesize = count << datashifts[type];
  if (byte_count > bytesize)
    ThrowTPE("TIFF, data set larger than entry size given");

  if (!own_data) {
    own_data = new uchar8[bytesize];
    memcpy(own_data, data, bytesize);
  }
  memcpy(own_data, in_data, byte_count);
}

uchar8* TiffEntry::getDataWrt()
{
  if (!own_data) {
    uint32 bytesize = count << datashifts[type];
    own_data = new uchar8[bytesize];
    memcpy(own_data, data, bytesize);
  }
  return own_data;
}

#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif

std::string TiffEntry::getValueAsString()
{
  if (type == TIFF_ASCII)
    return string((const char*)&data[0]);
  char *temp_string = new char[4096];
  if (count == 1) {
    switch (type) {
      case TIFF_LONG:
        sprintf(temp_string, "Long: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_SHORT:
        sprintf(temp_string, "Short: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_BYTE:
        sprintf(temp_string, "Byte: %u (0x%x)", getInt(), getInt());
        break;
      case TIFF_FLOAT:
        sprintf(temp_string, "Float: %f", getFloat());
        break;
      case TIFF_RATIONAL:
      case TIFF_SRATIONAL:
        sprintf(temp_string, "Rational Number: %f", getFloat());
        break;
      default:
        sprintf(temp_string, "Type: %x: ", type);
        for (uint32 i = 0; i < datasizes[type]; i++) {
          sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
        }
    }
  }
  string ret(temp_string);
  delete temp_string;
  return ret;
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>#include <luaconf.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <luajit.h>

int main(int argc, char** argv)
{
	return 0;
}<commit_msg>Branched for Lua Example<commit_after>int main(int argc, char** argv)
{
	return 0;
}<|endoftext|>