<commit_before> // RcpMaker
#include "Spectra/PidDataMaker.h"
#include "Correction/SpectraCorrecter.h"

// ROOT
#include "TLine.h"

// STL
#define _USE_MATH_DEFINES
#include <cmath> // for M_1_PI etc.

void PidDataMaker::initialize() {

	InclusiveSpectra::initialize();

	/**
	 * Initialize the Phase Space Recentering Object
	 */
	tofSigmaIdeal 	= config.getDouble( nodePath+".ZRecentering.sigma:tof", 0.011);
	dedxSigmaIdeal 	= config.getDouble( nodePath+".ZRecentering.sigma:dedx", 0.033);
	zr 				= new ZRecentering( dedxSigmaIdeal,
									 	tofSigmaIdeal,
									 	config.getString( nodePath+".Bichsel.table", "dedxBichsel.root"),
									 	config.getInt( nodePath+".Bichsel.method", 0) );

		// method for phase space recentering
	zrMethod 		= config.getString( nodePath + ".ZRecentering.method", "traditional" );
		// alias the centered species for ease of use
	centerSpecies 	= config.getString( nodePath + ".ZRecentering.centerSpecies", "K" );

	//Make the momentum transverse binning
	binsPt = unique_ptr<HistoBins>(new HistoBins( config, "binning.pt" ));

	// Get the list of charges we are looking at
	charges = config.getIntVector( "binning.charges" );

	// apply corrections now at a tack-by-track level?
	trackBytrackCorrs = config.getBool( nodePath + ":trackBytrackCorrs", true );
	INFO( classname(), "Applying Track by Track params : " << bts( trackBytrackCorrs ));

	if ( trackBytrackCorrs ){
		// Efficiency corrector
		sc = unique_ptr<SpectraCorrecter>( new SpectraCorrecter( config, nodePath ) );

		tpcSysNSigma = config.getDouble( nodePath + ".TpcEff:systematics", 0 );
		INFO( classname(), "Systematic uncertainty on TpcEff = " << tpcSysNSigma << " sigma" );
	}

	// make the energy loss params
	vector<int> charges = { -1, 1 };
	if ( config.exists( nodePath + ".EnergyLossParams:path" ) ){
		string path = config.getString( nodePath + ".EnergyLossParams:path" );

		for ( int c : charges ){

			string cfgName = path + centerSpecies + "_" + Common::chargeString( c ) + ".xml";
			XmlConfig cfgEL( cfgName );

			for ( int cb : config.getIntVector( nodePath + ".CentralityBins" ) ){

				// Name like 'Pi_p_0' ... 'Pi_n_6' to be used for quick lookup
				string name = centerSpecies + "_" + Common::chargeString( c ) +"_" + ts( cb );
				elParams[ name ] = unique_ptr<EnergyLossParams>( new EnergyLossParams(&cfgEL, "EnergyLossParams[" + ts(cb) + "]") );
			}

		}
	}

}

PidDataMaker::~PidDataMaker(){

}

void PidDataMaker::preEventLoop() {
	INFO( classname(), "");

	InclusiveSpectra::preEventLoop();

	book->cd();

	// make the energy loss histograms
	book->cd( "energyLoss" );
	for ( int c : charges ){
		for ( int cb : centralityBins ) {
			book->clone( "/", "corrPt", "energyLoss", "corrPt_" + Common::chargeString(c) + "_" + ts(cb) );
		}
	}

	for ( int c : charges ) {
		for ( string plc : Common::species ){
			for ( int cb : centralityBins ) {
				for ( int iPt = 0; iPt < binsPt->nBins(); iPt++ ){

					// create a PidPoint
					string nname = Common::speciesName( centerSpecies, c, cb, iPt );
					pidPoints[ nname ] = unique_ptr<TNtuple>( new TNtuple( nname.c_str(), "PidData", "zb:zd:w" ) );
				}
			}
		}
	}
}

void PidDataMaker::postEventLoop() {
	INFO( classname(), "");
	book->cd();

	// write the PidData trees to the file
	book->cd( "PidPoints" );
	for ( auto &k : pidPoints ){
		k.second->Write( k.first.c_str() );
	}

}

void PidDataMaker::analyzeTofTrack( int iTrack ){
	InclusiveSpectra::analyzeTofTrack( iTrack );

	book->cd();

	// Alias Track Traits
	int charge 		= pico->trackCharge( iTrack );
	double pt 		= pico->trackPt( iTrack );
	double p 		= pico->trackP( iTrack );
	double eta 		= pico->trackEta( iTrack );
	trackPt 		= pt; // saved for whole track calculations

	/************ Energy Loss Corrections **********/
	// Apply Energy Loss Corrections if given
	string elName = centerSpecies + "_" + Common::chargeString( charge ) +"_" + ts( cBin );
	if ( elParams.count( elName ) ){

		double corrPt = pt - elParams[ elName ]->eval( pt );
		// QA
		book->cd( "energyLoss" );
		book->fill( "corrPt_" + Common::chargeString( charge ) + "_" + ts(cBin), pt, pt - corrPt );
		book->cd(  );

		// recalc the p from corrPt and eta
		p = Common::p( corrPt, eta );
		pt = corrPt;
	} else {
		ERROR( classname(), "No Energy Loss Params Given - These must be applied here" )
	}
	/************ Energy Loss Corrections **********/

	// Must be done after corrections
	int ptBin 	= binsPt->findBin( pt );
	corrTrackPt = pt;
	double avgP = binAverageP( ptBin );

	// Require valid p bin
	if ( ptBin < 0 ){	// only caused by pT outside of range we are interested in
		DEBUG( classname(), "invalid ptBin = " << ptBin << " pT = " << pt << ", track pT = " << trackPt );
		return;
	}

	double ptBinWidth = binsPt->binWidth( ptBin );

	book->cd();

	// Traditionally Recentered values
	double tof 		= zr->rTof(centerSpecies, pico->trackBeta(iTrack), p );
	double dedx 	= zr->rDedx(centerSpecies, pico->trackDedx(iTrack), p );

	// Non-Linearly Recentered values
	double tofNL 	= zr->nlTof(centerSpecies, pico->trackBeta(iTrack), p, avgP );
	double dedxNL 	= zr->nlDedx(centerSpecies, pico->trackDedx(iTrack), p, avgP );

	// Choose recentered values
	if ( "nonlinear" == zrMethod ){
		tof = tofNL;
		dedx = dedxNL;
	}

	// event weight from RefMult correction
	double trackWeight = eventWeight;

	if ( trackBytrackCorrs ){
		trackWeight = trackWeight * M_1_PI * 0.5; 			// 1.0 / ( 2 pi )
		trackWeight = trackWeight * ( 1.0 / corrTrackPt ); 	// 1.0 / pT
		trackWeight = trackWeight * ( 1.0 / ptBinWidth ); 	// 1.0 / ( bin width )
		trackWeight = trackWeight * ( 1.0 / ( cut_rapidity->max - cut_rapidity->min ) ); 	// 1.0 / dy

		// correct for TPC matching efficiency
		trackWeight = trackWeight * sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma );
	}

	// fill the tree
	string name = Common::speciesName( centerSpecies, charge, cBin, ptBin );
	pidPoints[ name ]->Fill( tof, dedx, trackWeight );

	book->cd();
}
<commit_msg>debug messages for PidDataMaker<commit_after> // RcpMaker
#include "Spectra/PidDataMaker.h"
#include "Correction/SpectraCorrecter.h"

// ROOT
#include "TLine.h"

// STL
#define _USE_MATH_DEFINES
#include <cmath> // for M_1_PI etc.

void PidDataMaker::initialize() {

	InclusiveSpectra::initialize();

	/**
	 * Initialize the Phase Space Recentering Object
	 */
	tofSigmaIdeal 	= config.getDouble( nodePath+".ZRecentering.sigma:tof", 0.011);
	dedxSigmaIdeal 	= config.getDouble( nodePath+".ZRecentering.sigma:dedx", 0.033);
	zr 				= new ZRecentering( dedxSigmaIdeal,
									 	tofSigmaIdeal,
									 	config.getString( nodePath+".Bichsel.table", "dedxBichsel.root"),
									 	config.getInt( nodePath+".Bichsel.method", 0) );

		// method for phase space recentering
	zrMethod 		= config.getString( nodePath + ".ZRecentering.method", "traditional" );
		// alias the centered species for ease of use
	centerSpecies 	= config.getString( nodePath + ".ZRecentering.centerSpecies", "K" );

	//Make the momentum transverse binning
	binsPt = unique_ptr<HistoBins>(new HistoBins( config, "binning.pt" ));

	// Get the list of charges we are looking at
	charges = config.getIntVector( "binning.charges" );

	// apply corrections now at a tack-by-track level?
	trackBytrackCorrs = config.getBool( nodePath + ":trackBytrackCorrs", true );
	INFO( classname(), "Applying Track by Track params : " << bts( trackBytrackCorrs ));

	if ( trackBytrackCorrs ){
		// Efficiency corrector
		sc = unique_ptr<SpectraCorrecter>( new SpectraCorrecter( config, nodePath ) );

		tpcSysNSigma = config.getDouble( nodePath + ".TpcEff:systematics", 0 );
		INFO( classname(), "Systematic uncertainty on TpcEff = " << tpcSysNSigma << " sigma" );
	}

	// make the energy loss params
	vector<int> charges = { -1, 1 };
	if ( config.exists( nodePath + ".EnergyLossParams:path" ) ){
		string path = config.getString( nodePath + ".EnergyLossParams:path" );

		for ( int c : charges ){

			string cfgName = path + centerSpecies + "_" + Common::chargeString( c ) + ".xml";
			XmlConfig cfgEL( cfgName );

			for ( int cb : config.getIntVector( nodePath + ".CentralityBins" ) ){

				// Name like 'Pi_p_0' ... 'Pi_n_6' to be used for quick lookup
				string name = centerSpecies + "_" + Common::chargeString( c ) +"_" + ts( cb );
				elParams[ name ] = unique_ptr<EnergyLossParams>( new EnergyLossParams(&cfgEL, "EnergyLossParams[" + ts(cb) + "]") );
			}

		}
	}

}

PidDataMaker::~PidDataMaker(){

}

void PidDataMaker::preEventLoop() {
	INFO( classname(), "");

	InclusiveSpectra::preEventLoop();

	book->cd();

	// make the energy loss histograms
	book->cd( "energyLoss" );
	for ( int c : charges ){
		for ( int cb : centralityBins ) {
			book->clone( "/", "corrPt", "energyLoss", "corrPt_" + Common::chargeString(c) + "_" + ts(cb) );
		}
	}

	for ( int c : charges ) {
		for ( string plc : Common::species ){
			for ( int cb : centralityBins ) {
				for ( int iPt = 0; iPt < binsPt->nBins(); iPt++ ){

					// create a PidPoint
					string nname = Common::speciesName( centerSpecies, c, cb, iPt );
					pidPoints[ nname ] = unique_ptr<TNtuple>( new TNtuple( nname.c_str(), "PidData", "zb:zd:w" ) );
				}
			}
		}
	}
}

void PidDataMaker::postEventLoop() {
	INFO( classname(), "");
	book->cd();

	// write the PidData trees to the file
	book->cd( "PidPoints" );
	for ( auto &k : pidPoints ){
		k.second->Write( k.first.c_str() );
	}

}

void PidDataMaker::analyzeTofTrack( int iTrack ){
	InclusiveSpectra::analyzeTofTrack( iTrack );

	book->cd();

	// Alias Track Traits
	int charge 		= pico->trackCharge( iTrack );
	double pt 		= pico->trackPt( iTrack );
	double p 		= pico->trackP( iTrack );
	double eta 		= pico->trackEta( iTrack );
	trackPt 		= pt; // saved for whole track calculations

	/************ Energy Loss Corrections **********/
	// Apply Energy Loss Corrections if given
	string elName = centerSpecies + "_" + Common::chargeString( charge ) +"_" + ts( cBin );
	if ( elParams.count( elName ) ){

		double corrPt = pt - elParams[ elName ]->eval( pt );
		// QA
		book->cd( "energyLoss" );
		book->fill( "corrPt_" + Common::chargeString( charge ) + "_" + ts(cBin), pt, pt - corrPt );
		book->cd(  );

		// recalc the p from corrPt and eta
		p = Common::p( corrPt, eta );
		pt = corrPt;
	} else {
		ERROR( classname(), "No Energy Loss Params Given - These must be applied here" )
	}
	/************ Energy Loss Corrections **********/

	// Must be done after corrections
	int ptBin 	= binsPt->findBin( pt );
	corrTrackPt = pt;
	double avgP = binAverageP( ptBin );

	// Require valid p bin
	if ( ptBin < 0 ){	// only caused by pT outside of range we are interested in
		DEBUG( classname(), "invalid ptBin = " << ptBin << " pT = " << pt << ", track pT = " << trackPt );
		return;
	}

	double ptBinWidth = binsPt->binWidth( ptBin );

	book->cd();

	// Traditionally Recentered values
	double tof 		= zr->rTof(centerSpecies, pico->trackBeta(iTrack), p );
	double dedx 	= zr->rDedx(centerSpecies, pico->trackDedx(iTrack), p );

	// Non-Linearly Recentered values
	double tofNL 	= zr->nlTof(centerSpecies, pico->trackBeta(iTrack), p, avgP );
	double dedxNL 	= zr->nlDedx(centerSpecies, pico->trackDedx(iTrack), p, avgP );

	// Choose recentered values
	if ( "nonlinear" == zrMethod ){
		tof = tofNL;
		dedx = dedxNL;
	}

	// event weight from RefMult correction
	double trackWeight = eventWeight;

	if ( trackBytrackCorrs ){
		trackWeight = trackWeight * M_1_PI * 0.5; 			// 1.0 / ( 2 pi )
		trackWeight = trackWeight * ( 1.0 / corrTrackPt ); 	// 1.0 / pT
		trackWeight = trackWeight * ( 1.0 / ptBinWidth ); 	// 1.0 / ( bin width )
		trackWeight = trackWeight * ( 1.0 / ( cut_rapidity->max - cut_rapidity->min ) ); 	// 1.0 / dy

		// correct for TPC matching efficiency
		trackWeight = trackWeight * sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma );

		if ( ptBin == 12 ){
			INFO( classname(), "pT = " << corrTrackPt );
			INFO( classname(), "pTBinWidth = " << ptBinWidth );
			INFO( classname(), "dy = " << ( cut_rapidity->max - cut_rapidity->min ) );
			INFO( classname(), "tpcEff = " << (1.0 / sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma )) );

			INFO( classname(), "w = " << trackWeight );

		}
	}

	// fill the tree
	string name = Common::speciesName( centerSpecies, charge, cBin, ptBin );
	pidPoints[ name ]->Fill( tof, dedx, trackWeight );

	book->cd();
}
<|endoftext|>


<commit_before>#ifndef MOBS_HPP
#define MOBS_HPP

#include <iostream>
{
public:
  mob(std::string, std::string std::string, int, int, int, int);

  void setName(std::string);
  void setArea(std::string);
  void setSkill(std::string);

  void setLevel(int);
  void setEXP(int);
  void setHP(int);
  void setMaxHealth(int);

  void setDamage();
  void setEXP();

  std::string getName;
  std::string getArea;

  int getLevel();
  int getEXP();
  int getHP();
  int getMaxHealth();
  int getDamage();
  int getEXP();

private:
  std::string mobName;
  std::string mobArea;
  int mobLevel;
  int mobHealth;
  int mobMaxHealth;
  int mobDamage;
  int mobEXP;
};

#endif

<commit_msg>Update mobs.hpp<commit_after>#ifndef MOBS_HPP
#define MOBS_HPP

#include <iostream>

class Mob
{
public:
  mob(std::string, std::string std::string, int, int, int, int);

  void setName(std::string);
  void setArea(std::string);
  void setSkill(std::string);

  void setLevel(int);
  void setEXP(int);
  void setHP(int);
  void setMaxHealth(int);

  void setDamage();
  void setEXP();

  std::string getName;
  std::string getArea;

  int getLevel();
  int getEXP();
  int getHP();
  int getMaxHealth();
  int getDamage();
  int getEXP();

private:
  std::string mobName;
  std::string mobArea;
  int mobLevel;
  int mobHealth;
  int mobMaxHealth;
  int mobDamage;
  int mobEXP;
};

#endif

<|endoftext|>


<commit_before>#ifndef DATAMANAGER_H
#define DATAMANAGER_H

#include "StdIncl.hpp"
#include "types/Data.hpp"
#include "InvalidConfigException.hpp"
#include "Utils.hpp"

namespace uipf{
using namespace std;

// Provides and controls access to Parameters, Input and Outputdata
class DataManager
{

	public:
		DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output)
	:input_(input),params_(params),output_(output)
	{}

		~DataManager(){}

		//returns a typesafe readonly smartpointer to input/output data by name if it is available
		template <typename T>
		const T* getInputData( const std::string& strName) const;

		//returns a typesafe smartpointer to input/output data by name if it is available
		template <typename T>
		T* getOutputData( const std::string& strName) const;

		//returns a typesafe smartpointer to input/output data by name if it is available
		template <typename T>
		void setOutputData( const std::string& strName, T*) ;

		//returns a typesafe parameter by name if it is available. otherwise a defaultValue is used
		template <typename T>
		T getParam(const std::string& strName, T defaultValue) const;

		//print given parameters
		void listParams( ) const;

	private:
		std::map < std::string, Data::ptr& >& input_;
		std::map < std::string, std::string >& params_;
		std::map < std::string, Data::ptr >& output_;

};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//templates need to be implemented in headers

template <typename T>
const T* DataManager::getInputData( const std::string& strName) const
{
	if (input_.find(strName) != input_.end())
	{
		//do downcasting..
		Data::ptr& ptr = input_.find(strName)->second;
		return dynamic_cast<T*>(ptr.get());
	}
	else
	{
		throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
	}
}

template <typename T>
T* DataManager::getOutputData( const std::string& strName) const
{
	if (output_.find(strName) != output_.end())
	{
		//do downcasting..
		Data::ptr& ptr = output_.find(strName)->second;
		return dynamic_cast<T*>(ptr.get());
	}
	else
	{
		throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
	}
}

template <typename T>
void DataManager::setOutputData( const std::string& strName, T* outputData)
{
	output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData)));
}

//2DO other type specialisations e.g. float with atof() etc.
template <typename T>
T DataManager::getParam( const std::string& strName, T defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return static_cast<T>(params_[strName]);
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline int DataManager::getParam( const std::string& strName, int defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atoi(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline float DataManager::getParam(const std::string& strName, float defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atof(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline double DataManager::getParam( const std::string& strName, double defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atof(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline bool DataManager::getParam( const std::string& strName, bool defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return (utils::toLower(params_[strName]).compare("true")==0);
	}
	else
	{
		return defaultValue;
	}
}

} //namespace

#endif // DATAMANAGER_H

<commit_msg>shared pointers issue #56<commit_after>#ifndef DATAMANAGER_H
#define DATAMANAGER_H

#include "StdIncl.hpp"
#include "types/Data.hpp"
#include "InvalidConfigException.hpp"
#include "Utils.hpp"

namespace uipf{
using namespace std;

// Provides and controls access to Parameters, Input and Outputdata
class DataManager
{

	public:
		DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output)
	:input_(input),params_(params),output_(output)
	{}

		~DataManager(){}

		//returns a typesafe readonly smartpointer to input/output data by name if it is available
		template <typename T>
		const typename T::ptr getInputData( const std::string& strName) const;

		//returns a typesafe smartpointer to input/output data by name if it is available
		template <typename T>
		typename T::ptr getOutputData( const std::string& strName) const;

		//returns a typesafe smartpointer to input/output data by name if it is available
		template <typename T>
		void setOutputData( const std::string& strName, T*) ;

		//returns a typesafe parameter by name if it is available. otherwise a defaultValue is used
		template <typename T>
		T getParam(const std::string& strName, T defaultValue) const;

		//print given parameters
		void listParams( ) const;

	private:
		std::map < std::string, Data::ptr& >& input_;
		std::map < std::string, std::string >& params_;
		std::map < std::string, Data::ptr >& output_;

};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//templates need to be implemented in headers

template <typename T>
const typename T::ptr DataManager::getInputData( const std::string& strName) const
{
	if (input_.find(strName) != input_.end())
	{
		//do downcasting..
		Data::ptr& ptr = input_.find(strName)->second;
		return std::dynamic_pointer_cast<T>(ptr);
	}
	else
	{
		throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
	}
}

template <typename T>
typename T::ptr DataManager::getOutputData( const std::string& strName) const
{
	if (output_.find(strName) != output_.end())
	{
		//do downcasting..
		Data::ptr& ptr = input_.find(strName)->second;
		return std::dynamic_pointer_cast<T>(ptr);
	}
	else
	{
		throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
	}
}

template <typename T>
void DataManager::setOutputData( const std::string& strName, T* outputData)
{
	output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData)));
}

//2DO other type specialisations e.g. float with atof() etc.
template <typename T>
T DataManager::getParam( const std::string& strName, T defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return static_cast<T>(params_[strName]);
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline int DataManager::getParam( const std::string& strName, int defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atoi(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline float DataManager::getParam(const std::string& strName, float defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atof(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline double DataManager::getParam( const std::string& strName, double defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return atof(params_[strName].c_str());
	}
	else
	{
		return defaultValue;
	}
}

template <>
inline bool DataManager::getParam( const std::string& strName, bool defaultValue) const
{
	if (params_.find(strName) != params_.end())
	{
		return (utils::toLower(params_[strName]).compare("true")==0);
	}
	else
	{
		return defaultValue;
	}
}

} //namespace

#endif // DATAMANAGER_H

<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#ifndef RADIANS_TO_DEGREES
#define RADIANS_TO_DEGREES(x) (x * 180.0f / PI)
#endif

#include "gpgpu_test_scene.hpp"
#include "code/ylikuutio/snippets/keyboard_callback_snippets.hpp"
#include "code/ylikuutio/input/input.hpp"
#include "code/ylikuutio/callback/callback_object.hpp"
#include "code/ylikuutio/callback/callback_engine.hpp"
#include "code/ylikuutio/callback/callback_magic_numbers.hpp"
#include "code/ylikuutio/command_line/command_line_master.hpp"
#include "code/ylikuutio/ontology/universe.hpp"
#include "code/ylikuutio/ontology/font2D.hpp"
#include "code/ylikuutio/ontology/world.hpp"
#include "code/ylikuutio/ontology/world_struct.hpp"
#include "code/ylikuutio/ontology/scene.hpp"
#include "code/ylikuutio/ontology/shader.hpp"
#include "code/ylikuutio/ontology/shader_struct.hpp"
#include "code/ylikuutio/ontology/entity_factory.hpp"
#include "code/ylikuutio/opengl/opengl.hpp"
#include "code/ylikuutio/time/time.hpp"

// Include GLEW
#include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc.

#define SDL_main main

#include "SDL.h"

// Include standard headers
#include <exception>     // try, catch, std::exception
#include <iostream>      // std::cout, std::cin, std::cerr
#include <sstream>       // std::istringstream, std::ostringstream, std::stringstream

int main(const int argc, const char* const argv[]) try
{
    yli::command_line::CommandLineMaster command_line_master(argc, argv);

    if (command_line_master.is_key("version"))
    {
        std::cout << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version << "\n";
        return 0;
    }

    command_line_master.print_keys_and_values();

    // Create the `Universe`, store it in `my_universe`.
    std::cout << "Creating yli::ontology::Entity* my_universe_entity ...\n";
    yli::ontology::UniverseStruct universe_struct;
    std::stringstream window_title_stringstream;
    window_title_stringstream << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version;
    universe_struct.window_title = window_title_stringstream.str();
    universe_struct.window_width = 512;
    universe_struct.window_height = 512;
    yli::ontology::Universe* const my_universe = new yli::ontology::Universe(universe_struct);
    my_universe->set_global_name("universe");

    yli::ontology::EntityFactory* const entity_factory = my_universe->get_entity_factory();

    std::cout << "Creating yli::callback::CallbackEngine cleanup_callback_engine ...\n";
    yli::callback::CallbackEngine cleanup_callback_engine = yli::callback::CallbackEngine();
    cleanup_callback_engine.create_callback_object(nullptr);

    if (my_universe->get_window() == nullptr)
    {
        std::cerr << "Failed to open SDL window.\n";
        return -1;
    }

    // Initialize GLEW.
    if (!yli::opengl::init_glew())
    {
        cleanup_callback_engine.execute(nullptr);
        return -1;
    }

    yli::input::disable_cursor();
    yli::input::enable_relative_mouse_mode();

    // Enable depth test.
    yli::opengl::enable_depth_test();
    // Accept fragment if it closer to the camera than the former one.
    yli::opengl::set_depth_func_to_less();

    // Cull triangles which normal is not towards the camera.
    yli::opengl::cull_triangles();

    // Create the `World`.

    yli::ontology::WorldStruct world_struct;

    std::cout << "Creating yli::ontology::Entity* gpgpu_test_world_entity ...\n";
    yli::ontology::Entity* const gpgpu_test_world_entity = entity_factory->create_world(world_struct);
    std::cout << "Creating yli::ontology::World* gpgpu_test_world ...\n";
    yli::ontology::World* const gpgpu_test_world = dynamic_cast<yli::ontology::World*>(gpgpu_test_world_entity);

    if (gpgpu_test_world == nullptr)
    {
        return -1;
    }

    // Create the `Scene`s.

    // GPGPU test `Scene` begins here.

    std::cout << "Creating yli::ontology::Entity* gpgpu_test_scene_entity and its contents ...\n";
    yli::ontology::Entity* const gpgpu_test_scene_entity = gpgpu_test::create_gpgpu_test_scene(entity_factory, gpgpu_test_world);

    if (gpgpu_test_scene_entity == nullptr)
    {
        return -1;
    }

    std::cout << "Creating yli::ontology::Scene* gpgpu_test_scene ...\n";
    yli::ontology::Scene* const gpgpu_test_scene = dynamic_cast<yli::ontology::Scene*>(gpgpu_test_scene_entity);

    if (gpgpu_test_scene == nullptr)
    {
        cleanup_callback_engine.execute(nullptr);
        return -1;
    }

    // Set `gpgpu_test_scene` to be the currently active `Scene`.
    std::cout << "Setting gpgpu_test_scene as the active scene ...\n";
    my_universe->set_active_scene(gpgpu_test_scene);

    // GPGPU test `Scene` ends here.

    // Clear the screen.
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Render the `Universe`.
    my_universe->render();

    // do cleanup.
    cleanup_callback_engine.execute(nullptr);

    return 0;
}
catch (const std::exception& exception)
{
    std::cerr << "ERROR: exception: " << exception.what() << "\n";
}
<commit_msg>GPGPU test: remove obsolete cleanup code.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#ifndef RADIANS_TO_DEGREES
#define RADIANS_TO_DEGREES(x) (x * 180.0f / PI)
#endif

#include "gpgpu_test_scene.hpp"
#include "code/ylikuutio/snippets/keyboard_callback_snippets.hpp"
#include "code/ylikuutio/input/input.hpp"
#include "code/ylikuutio/callback/callback_object.hpp"
#include "code/ylikuutio/callback/callback_magic_numbers.hpp"
#include "code/ylikuutio/command_line/command_line_master.hpp"
#include "code/ylikuutio/ontology/universe.hpp"
#include "code/ylikuutio/ontology/font2D.hpp"
#include "code/ylikuutio/ontology/world.hpp"
#include "code/ylikuutio/ontology/world_struct.hpp"
#include "code/ylikuutio/ontology/scene.hpp"
#include "code/ylikuutio/ontology/shader.hpp"
#include "code/ylikuutio/ontology/shader_struct.hpp"
#include "code/ylikuutio/ontology/entity_factory.hpp"
#include "code/ylikuutio/opengl/opengl.hpp"
#include "code/ylikuutio/time/time.hpp"

// Include GLEW
#include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc.

#define SDL_main main

#include "SDL.h"

// Include standard headers
#include <exception>     // try, catch, std::exception
#include <iostream>      // std::cout, std::cin, std::cerr
#include <sstream>       // std::istringstream, std::ostringstream, std::stringstream

int main(const int argc, const char* const argv[]) try
{
    yli::command_line::CommandLineMaster command_line_master(argc, argv);

    if (command_line_master.is_key("version"))
    {
        std::cout << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version << "\n";
        return 0;
    }

    command_line_master.print_keys_and_values();

    // Create the `Universe`, store it in `my_universe`.
    std::cout << "Creating yli::ontology::Entity* my_universe_entity ...\n";
    yli::ontology::UniverseStruct universe_struct;
    std::stringstream window_title_stringstream;
    window_title_stringstream << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version;
    universe_struct.window_title = window_title_stringstream.str();
    universe_struct.window_width = 512;
    universe_struct.window_height = 512;
    yli::ontology::Universe* const my_universe = new yli::ontology::Universe(universe_struct);
    my_universe->set_global_name("universe");

    yli::ontology::EntityFactory* const entity_factory = my_universe->get_entity_factory();

    if (my_universe->get_window() == nullptr)
    {
        std::cerr << "Failed to open SDL window.\n";
        return -1;
    }

    // Initialize GLEW.
    if (!yli::opengl::init_glew())
    {
        return -1;
    }

    yli::input::disable_cursor();
    yli::input::enable_relative_mouse_mode();

    // Enable depth test.
    yli::opengl::enable_depth_test();
    // Accept fragment if it closer to the camera than the former one.
    yli::opengl::set_depth_func_to_less();

    // Cull triangles which normal is not towards the camera.
    yli::opengl::cull_triangles();

    // Create the `World`.

    yli::ontology::WorldStruct world_struct;

    std::cout << "Creating yli::ontology::Entity* gpgpu_test_world_entity ...\n";
    yli::ontology::Entity* const gpgpu_test_world_entity = entity_factory->create_world(world_struct);
    std::cout << "Creating yli::ontology::World* gpgpu_test_world ...\n";
    yli::ontology::World* const gpgpu_test_world = dynamic_cast<yli::ontology::World*>(gpgpu_test_world_entity);

    if (gpgpu_test_world == nullptr)
    {
        return -1;
    }

    // Create the `Scene`s.

    // GPGPU test `Scene` begins here.

    std::cout << "Creating yli::ontology::Entity* gpgpu_test_scene_entity and its contents ...\n";
    yli::ontology::Entity* const gpgpu_test_scene_entity = gpgpu_test::create_gpgpu_test_scene(entity_factory, gpgpu_test_world);

    if (gpgpu_test_scene_entity == nullptr)
    {
        return -1;
    }

    std::cout << "Creating yli::ontology::Scene* gpgpu_test_scene ...\n";
    yli::ontology::Scene* const gpgpu_test_scene = dynamic_cast<yli::ontology::Scene*>(gpgpu_test_scene_entity);

    if (gpgpu_test_scene == nullptr)
    {
        return -1;
    }

    // Set `gpgpu_test_scene` to be the currently active `Scene`.
    std::cout << "Setting gpgpu_test_scene as the active scene ...\n";
    my_universe->set_active_scene(gpgpu_test_scene);

    // GPGPU test `Scene` ends here.

    // Clear the screen.
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Render the `Universe`.
    my_universe->render();

    return 0;
}
catch (const std::exception& exception)
{
    std::cerr << "ERROR: exception: " << exception.what() << "\n";
}
<|endoftext|>


<commit_before>#include "TChain.h"
#include "TFile.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TLorentzVector.h"
#include <iostream>
#include "x.h"
#include "TCanvas.h"
#include <math.h>
#include <set>
#include "TString.h"
#include "TSystem.h"
using namespace mini;
const double PI = 4.0*atan(1.0);
#include "TH1.h"
#include "TH2.h"

void fakerate(TString const& _input)
{
  std::cout<<_input<<std::endl;
  TChain eventVars("eventVars");//define eventVars tree
  eventVars.Add("./"+_input+".root/eventVars");

  TChain selectedObjects("selectedObjects");  //define eventVars tree
  selectedObjects.Add("./"+_input+".root/selectedObjects");

  TChain allObjects("allObjects");  //define eventVars tree
  allObjects.Add("./"+_input+".root/allObjects");

  allObjects.AddFriend("selectedObjects");
  allObjects.AddFriend("eventVars");

  //define variables
  bool hlt0;
  bool hlt1;
  float met;
  float metPhi;
  photon   p, rp;
  muon     m, rm;
  electron e, re;
  jet      j, rj;
  genparticle gp;
  //link the branches to the variables defined above
  //this is where you add variables relevant to your analysis
  eventVars.SetBranchAddress("met", &met);
  eventVars.SetBranchAddress("metPhi", &metPhi);
  eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFHT400", &hlt0);
  eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFNoPUHT400", &hlt1);

  p.setAddress(selectedObjects);
  m.setAddress(selectedObjects);
  e.setAddress(selectedObjects);
  j.setAddress(selectedObjects);

  rp.setAddress(allObjects);
  re.setAddress(allObjects);
  rm.setAddress(allObjects);
  rj.setAddress(allObjects);

  gp.setAddress(eventVars);

  TH1F* h_N_tG = new TH1F("h_N_tG", "tight G Pt", 10, 0., 10.);
  TH1F* h_N_lE = new TH1F("h_N_lE", "Loose e Pt", 10, 0., 10.);
  TH1F* h_N_tE = new TH1F("h_N_tE", "Tight e Pt", 10, 0., 10.);
  TH1F* h_all_lE_pt = new TH1F("h_all_lE_pt", "Loose e Pt", 10, 0., 10.);
  TH1F* h_all_tE_pt = new TH1F("h_all_tE_pt", "Tight e Pt", 10, 0., 10.);
  TH1F* h_all_tG_pt = new TH1F("h_all_tG_pt", "Tight G Pt", 10, 0., 10.);
  TH1F* h_lE_pt = new TH1F("h_lE_pt", "Loose e Pt", 30, 0., 300.);
  TH1F* h_tE_pt = new TH1F("h_tE_pt", "Tight e Pt", 30, 0., 300.);
  TH1F* h_fE_pt = new TH1F("h_fE_pt", "Fail-tight e Pt", 30, 0., 300.);
  h_lE_pt->Sumw2();
  h_tE_pt->Sumw2();
  h_fE_pt->Sumw2();
  TH1F* h_lE1_pt = new TH1F("h_lE1_pt", "Loose e Pt", 30, 0., 300.);
  TH1F* h_tE1_pt = new TH1F("h_tE1_pt", "Tight e Pt", 30, 0., 300.);
  TH1F* h_fE1_pt = new TH1F("h_fE1_pt", "Fail-tight e Pt", 30, 0., 300.);
  h_lE1_pt->Sumw2();
  h_tE1_pt->Sumw2();
  h_fE1_pt->Sumw2();

  unsigned nCnt[20] = {0};
  //loop over events
  long iEntry = 0;
  while(allObjects.GetEntry(iEntry++) != 0){

    nCnt[0]++;

    std::set<unsigned> lE;
    std::set<unsigned> tE;
    std::set<unsigned> lG;
    std::set<unsigned>::iterator it;

    for(unsigned k(0);k<re.size;k++) {
      if(re.iSubdet[k]!=0) continue;
      if(re.isLoose[k]) {
        lE.insert(k);
        h_all_lE_pt->Fill(re.pt[k]);
      }
      if(re.isTight[k]) {
        tE.insert(k);
        h_all_tE_pt->Fill(re.pt[k]);
      }
    }

    h_N_lE->Fill(lE.size());
    h_N_tE->Fill(tE.size());

    for(unsigned k(0);k<rp.size;k++) {
      if (!p.isLoose[k]) continue;
      lG.insert(k);
      h_all_tG_pt->Fill(rp.pt[k]);
    }
    h_N_tG->Fill(lG.size());

    //consider event with only 1 loose electron
    if(lE.size()!=1) continue;
    it = lE.begin();
    ///remove electron close to a loose photon
    h_lE_pt->Fill(re.pt[*it]);

    if(tE.size()==1) {
      h_tE_pt->Fill(re.pt[*it]);
    } else {//did not pass tight
      h_fE_pt->Fill(re.pt[*it]);
    }

    int checkDR(0);
    for (std::set<unsigned int>::iterator ik=lG.begin(); ik!=lG.end(); ++ik) {
      if(deltaR(rp.eta[*ik],rp.phi[*ik],re.eta[*it],re.phi[*it])<0.1) {
          checkDR++;
      }
    }
    if(checkDR) continue;

    float MT = mini::mt(met,metPhi,re.pt[*it],re.phi[*it]);
    //if(MT>25.) continue;

    h_lE1_pt->Fill(re.pt[*it]);

    if(tE.size()==1) {
      h_tE1_pt->Fill(re.pt[*it]);
    } else {//did not pass tight
      h_fE1_pt->Fill(re.pt[*it]);
    }

  }//while

TCanvas *plots = new TCanvas("plots","fake rate plots",800,800);
plots->Divide(2,2);
plots->cd(1);
h_lE_pt->Draw();
h_tE_pt->Draw("same");
plots->cd(3);
TH1F *h3 = (TH1F*)h_tE_pt->Clone("h3");
h3->Divide(h_lE_pt);
h3->Draw("e");
plots->cd(2);
h_lE1_pt->Draw();
h_tE1_pt->Draw("same");
plots->cd(4);
TH1F *h4 = (TH1F*)h_tE1_pt->Clone("h3");
h4->Divide(h_lE1_pt);
h4->Draw("e");

//h_lE_pt->Draw();
//h_tE_pt->Draw("same");
//save histograms inside sampleAnalysis.root
TObjArray hlist(0);
hlist.Add(h_lE_pt);
hlist.Add(h_tE_pt);
hlist.Add(h_fE_pt);
hlist.Add(h_lE1_pt);
hlist.Add(h_tE1_pt);
hlist.Add(h_fE1_pt);

TFile fout("fakerate.root", "recreate");
hlist.Write();
fout.Close();

}

<commit_msg>fixed h3 bug in fakerate<commit_after>#include "TChain.h"
#include "TFile.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TLorentzVector.h"
#include <iostream>
#include "x.h"
#include "TCanvas.h"
#include <math.h>
#include <set>
#include "TString.h"
#include "TSystem.h"
using namespace mini;
const double PI = 4.0*atan(1.0);
#include "TH1.h"
#include "TH2.h"

void fakerate(TString const& _input)
{
  std::cout<<_input<<std::endl;
  TChain eventVars("eventVars");//define eventVars tree
  eventVars.Add("./"+_input+".root/eventVars");

  TChain selectedObjects("selectedObjects");  //define eventVars tree
  selectedObjects.Add("./"+_input+".root/selectedObjects");

  TChain allObjects("allObjects");  //define eventVars tree
  allObjects.Add("./"+_input+".root/allObjects");

  allObjects.AddFriend("selectedObjects");
  allObjects.AddFriend("eventVars");

  //define variables
  bool hlt0;
  bool hlt1;
  float met;
  float metPhi;
  photon   p, rp;
  muon     m, rm;
  electron e, re;
  jet      j, rj;
  genparticle gp;
  //link the branches to the variables defined above
  //this is where you add variables relevant to your analysis
  eventVars.SetBranchAddress("met", &met);
  eventVars.SetBranchAddress("metPhi", &metPhi);
  eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFHT400", &hlt0);
  eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFNoPUHT400", &hlt1);

  p.setAddress(selectedObjects);
  m.setAddress(selectedObjects);
  e.setAddress(selectedObjects);
  j.setAddress(selectedObjects);

  rp.setAddress(allObjects);
  re.setAddress(allObjects);
  rm.setAddress(allObjects);
  rj.setAddress(allObjects);

  gp.setAddress(eventVars);

  TH1F* h_N_tG = new TH1F("h_N_tG", "tight G Pt", 10, 0., 10.);
  TH1F* h_N_lE = new TH1F("h_N_lE", "Loose e Pt", 10, 0., 10.);
  TH1F* h_N_tE = new TH1F("h_N_tE", "Tight e Pt", 10, 0., 10.);
  TH1F* h_all_lE_pt = new TH1F("h_all_lE_pt", "Loose e Pt", 10, 0., 10.);
  TH1F* h_all_tE_pt = new TH1F("h_all_tE_pt", "Tight e Pt", 10, 0., 10.);
  TH1F* h_all_tG_pt = new TH1F("h_all_tG_pt", "Tight G Pt", 10, 0., 10.);
  TH1F* h_lE_pt = new TH1F("h_lE_pt", "Loose e Pt", 30, 0., 300.);
  TH1F* h_tE_pt = new TH1F("h_tE_pt", "Tight e Pt", 30, 0., 300.);
  TH1F* h_fE_pt = new TH1F("h_fE_pt", "Fail-tight e Pt", 30, 0., 300.);
  h_lE_pt->Sumw2();
  h_tE_pt->Sumw2();
  h_fE_pt->Sumw2();
  TH1F* h_lE1_pt = new TH1F("h_lE1_pt", "Loose e Pt", 30, 0., 300.);
  TH1F* h_tE1_pt = new TH1F("h_tE1_pt", "Tight e Pt", 30, 0., 300.);
  TH1F* h_fE1_pt = new TH1F("h_fE1_pt", "Fail-tight e Pt", 30, 0., 300.);
  h_lE1_pt->Sumw2();
  h_tE1_pt->Sumw2();
  h_fE1_pt->Sumw2();

  unsigned nCnt[20] = {0};
  //loop over events
  long iEntry = 0;
  while(allObjects.GetEntry(iEntry++) != 0){

    nCnt[0]++;

    std::set<unsigned> lE;
    std::set<unsigned> tE;
    std::set<unsigned> lG;
    std::set<unsigned>::iterator it;

    for(unsigned k(0);k<re.size;k++) {
      if(re.iSubdet[k]!=0) continue;
      if(re.isLoose[k]) {
        lE.insert(k);
        h_all_lE_pt->Fill(re.pt[k]);
      }
      if(re.isTight[k]) {
        tE.insert(k);
        h_all_tE_pt->Fill(re.pt[k]);
      }
    }

    h_N_lE->Fill(lE.size());
    h_N_tE->Fill(tE.size());

    for(unsigned k(0);k<rp.size;k++) {
      if (!p.isLoose[k]) continue;
      lG.insert(k);
      h_all_tG_pt->Fill(rp.pt[k]);
    }
    h_N_tG->Fill(lG.size());

    //consider event with only 1 loose electron
    if(lE.size()!=1) continue;
    it = lE.begin();
    ///remove electron close to a loose photon
    h_lE_pt->Fill(re.pt[*it]);

    if(tE.size()==1) {
      h_tE_pt->Fill(re.pt[*it]);
    } else {//did not pass tight
      h_fE_pt->Fill(re.pt[*it]);
    }

    int checkDR(0);
    for (std::set<unsigned int>::iterator ik=lG.begin(); ik!=lG.end(); ++ik) {
      if(deltaR(rp.eta[*ik],rp.phi[*ik],re.eta[*it],re.phi[*it])<0.1) {
          checkDR++;
      }
    }
    if(checkDR) continue;

    float MT = mini::mt(met,metPhi,re.pt[*it],re.phi[*it]);
    //if(MT>25.) continue;

    h_lE1_pt->Fill(re.pt[*it]);

    if(tE.size()==1) {
      h_tE1_pt->Fill(re.pt[*it]);
    } else {//did not pass tight
      h_fE1_pt->Fill(re.pt[*it]);
    }

  }//while

TCanvas *plots = new TCanvas("plots","fake rate plots",800,800);
plots->Divide(2,2);
plots->cd(1);
h_lE_pt->Draw();
h_tE_pt->Draw("same");
plots->cd(3);
TH1F *h3 = (TH1F*)h_tE_pt->Clone("h3");
h3->Divide(h_lE_pt);
h3->Draw("e");
plots->cd(2);
h_lE1_pt->Draw();
h_tE1_pt->Draw("same");
plots->cd(4);
TH1F *h4 = (TH1F*)h_tE1_pt->Clone("h4");
h4->Divide(h_lE1_pt);
h4->Draw("e");

//h_lE_pt->Draw();
//h_tE_pt->Draw("same");
//save histograms inside sampleAnalysis.root
TObjArray hlist(0);
hlist.Add(h_lE_pt);
hlist.Add(h_tE_pt);
hlist.Add(h_fE_pt);
hlist.Add(h_lE1_pt);
hlist.Add(h_tE1_pt);
hlist.Add(h_fE1_pt);

TFile fout("fakerate.root", "recreate");
hlist.Write();
fout.Close();

}

<|endoftext|>


<commit_before>#include "preferred_languages.hpp"

#include "../base/string_utils.hpp"
#include "../base/logging.hpp"

#include "../std/target_os.hpp"
#include "../std/set.hpp"

#if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  #include <CoreFoundation/CFLocale.h>
  #include <CoreFoundation/CFString.h>

#elif defined(OMIM_OS_WINDOWS)
  // @TODO

#else
  #error "Define language preferences for your platform"

#endif

namespace languages
{

class LangFilter
{
  set<string> & m_known;
public:
  LangFilter(set<string> & known) : m_known(known) {}
  bool operator()(string const & t)
  {
    return !m_known.insert(t).second;
  }
};

class NormalizeFilter
{
public:
  void operator()(string & t)
  {
    strings::SimpleTokenizer const iter(t, "-_ ");
    if (iter)
      t = *iter;
    else
    {
      LOG(LWARNING, ("Invalid language"));
    }
  }
};

void FilterLanguages(vector<string> & langs)
{
  // normalize languages: en-US -> en, ru_RU -> ru etc.
  for_each(langs.begin(), langs.end(), NormalizeFilter());
  { // tmp storage
    set<string> known;
    // remove duplicate languages
    langs.erase(remove_if(langs.begin(), langs.end(), LangFilter(known)), langs.end());
  }
}

void SystemPreferredLanguages(vector<string> & languages)
{
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  // Mac and iOS implementation
  CFArrayRef langs = CFLocaleCopyPreferredLanguages();
  char buf[30];
  for (CFIndex i = 0; i < CFArrayGetCount(langs); ++i)
  {
    CFStringRef strRef = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
    CFStringGetCString(strRef, buf, 30, kCFStringEncodingUTF8);
    languages.push_back(buf);
  }
  CFRelease(langs);

#elif defined(OMIM_OS_WINDOWS)
  // @TODO Windows implementation
#else
  #error "Define language preferences for your platform"
#endif

  FilterLanguages(languages);
}

string PreferredLanguages()
{
  vector<string> arr;

  SystemPreferredLanguages(arr);

  // generate output string
  string result;
  for (size_t i = 0; i < arr.size(); ++i)
  {
    result.append(arr[i]);
    result.push_back('|');
  }
  if (result.empty())
    result = "default";
  else
    result.resize(result.size() - 1);
  return result;
}

string CurrentLanguage()
{
  vector<string> arr;
  SystemPreferredLanguages(arr);
  if (arr.empty())
    return "en";
  else
    return arr[0];
}

}
<commit_msg>Added preferred languages support for Linux<commit_after>#include "preferred_languages.hpp"

#include "../base/string_utils.hpp"
#include "../base/logging.hpp"

#include "../std/target_os.hpp"
#include "../std/set.hpp"

#if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  #include <CoreFoundation/CFLocale.h>
  #include <CoreFoundation/CFString.h>

#elif defined(OMIM_OS_WINDOWS)
  // @TODO

#elif defined(OMIM_OS_LINUX)
  #include "../std/stdlib.hpp"

#else
  #error "Define language preferences for your platform"

#endif

namespace languages
{

class LangFilter
{
  set<string> & m_known;
public:
  LangFilter(set<string> & known) : m_known(known) {}
  bool operator()(string const & t)
  {
    return !m_known.insert(t).second;
  }
};

class NormalizeFilter
{
public:
  void operator()(string & t)
  {
    strings::SimpleTokenizer const iter(t, "-_ ");
    if (iter)
      t = *iter;
    else
    {
      LOG(LWARNING, ("Invalid language"));
    }
  }
};

void FilterLanguages(vector<string> & langs)
{
  // normalize languages: en-US -> en, ru_RU -> ru etc.
  for_each(langs.begin(), langs.end(), NormalizeFilter());
  { // tmp storage
    set<string> known;
    // remove duplicate languages
    langs.erase(remove_if(langs.begin(), langs.end(), LangFilter(known)), langs.end());
  }
}

void SystemPreferredLanguages(vector<string> & languages)
{
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  // Mac and iOS implementation
  CFArrayRef langs = CFLocaleCopyPreferredLanguages();
  char buf[30];
  for (CFIndex i = 0; i < CFArrayGetCount(langs); ++i)
  {
    CFStringRef strRef = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
    CFStringGetCString(strRef, buf, 30, kCFStringEncodingUTF8);
    languages.push_back(buf);
  }
  CFRelease(langs);

#elif defined(OMIM_OS_WINDOWS)
  // @TODO Windows implementation

#elif defined(OMIM_OS_LINUX)
  // check environment variables
  char const * p = getenv("LANGUAGE");
  if (p) // LANGUAGE can contain several values divided by ':'
  {
    string const str(p);
    strings::SimpleTokenizer iter(str, ":");
    while (iter)
    {
      languages.push_back(*iter);
      ++iter;
    }
  }
  else if ((p = getenv("LC_ALL")))
    languages.push_back(p);
  else if ((p = getenv("LC_MESSAGES")))
    languages.push_back(p);
  else if ((p = getenv("LANG")))
    languages.push_back(p);

#else
  #error "Define language preferences for your platform"
#endif

  FilterLanguages(languages);
}

string PreferredLanguages()
{
  vector<string> arr;

  SystemPreferredLanguages(arr);

  // generate output string
  string result;
  for (size_t i = 0; i < arr.size(); ++i)
  {
    result.append(arr[i]);
    result.push_back('|');
  }
  if (result.empty())
    result = "default";
  else
    result.resize(result.size() - 1);
  return result;
}

string CurrentLanguage()
{
  vector<string> arr;
  SystemPreferredLanguages(arr);
  if (arr.empty())
    return "en";
  else
    return arr[0];
}

}
<|endoftext|>


<commit_before>/* Copyright (c) 2015 The Squash Authors
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Authors:
 *   Evan Nemerson <evan@nemerson.com>
 *   Eugene Kliuchnikov <eustas.ru+squash@gmail.com>
 */

#include <assert.h>

#include <squash/squash.h>

#include "brotli/enc/encode.h"
#include "brotli/dec/decode.h"

enum SquashBrotliOptionIndex {
  SQUASH_BROTLI_OPT_LEVEL = 0,
  SQUASH_BROTLI_OPT_MODE
};

/* C++ doesn't allow us to initialize this correctly here (or, at
   least, I can't figure out how to do it), so there is some extra
   code in the init_plugin func to finish it off. */
static SquashOptionInfo squash_brotli_options[] = {
  { .name = (char*) "level",
    .type = SQUASH_OPTION_TYPE_RANGE_INT },
  { .name = (char*) "mode",
    .type = SQUASH_OPTION_TYPE_ENUM_STRING },
  { NULL, SQUASH_OPTION_TYPE_NONE, }
};

typedef struct SquashBrotliStream_s {
  SquashStream base_object;

  BrotliInput in;
  BrotliOutput out;
  BrotliState* decompressor;
  bool finished;
  brotli::BrotliCompressor* compressor;
  bool should_flush;
  size_t remaining_block_in;
  size_t remaining_out;
  uint8_t* next_out;
} SquashBrotliStream;

extern "C" SQUASH_PLUGIN_EXPORT
SquashStatus                squash_plugin_init_plugin     (SquashPlugin* plugin);
extern "C" SQUASH_PLUGIN_EXPORT
SquashStatus                squash_plugin_init_codec      (SquashCodec* codec, SquashCodecImpl* impl);

static void                 squash_brotli_stream_init     (SquashBrotliStream* stream,
                                                           SquashCodec* codec,
                                                           SquashStreamType stream_type,
                                                           SquashOptions* options,
                                                           SquashDestroyNotify destroy_notify);
static SquashBrotliStream*  squash_brotli_stream_new      (SquashCodec* codec,
                                                           SquashStreamType stream_type,
                                                           SquashOptions* options);
static void                 squash_brotli_stream_destroy  (void* stream);
static void                 squash_brotli_stream_free     (void* stream);

static int
squash_brotli_reader (void* user_data, uint8_t* buf, size_t size) {
  SquashBrotliStream* stream = (SquashBrotliStream*) user_data;
  size = (stream->base_object.avail_in < size) ? stream->base_object.avail_in : size;
  memcpy (buf, stream->base_object.next_in, size);
  stream->base_object.next_in += size;
  stream->base_object.avail_in -= size;
  return size;
}

static int
squash_brotli_writer (void* user_data, const uint8_t* buf, size_t size) {
  SquashBrotliStream* stream = (SquashBrotliStream*) user_data;
  size = (stream->base_object.avail_out < size) ? stream->base_object.avail_out : size;
  memcpy (stream->base_object.next_out, buf, size);
  stream->base_object.next_out += size;
  stream->base_object.avail_out -= size;
  return size;
}

static SquashBrotliStream*
squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) {
  SquashBrotliStream* stream;

  assert (codec != NULL);
  assert (stream_type == SQUASH_STREAM_COMPRESS || stream_type == SQUASH_STREAM_DECOMPRESS);

  stream = (SquashBrotliStream*) malloc (sizeof (SquashBrotliStream));
  squash_brotli_stream_init (stream, codec, stream_type, options, squash_brotli_stream_free);

  return stream;
}

static void
squash_brotli_stream_init (SquashBrotliStream* s,
                           SquashCodec* codec,
                           SquashStreamType stream_type,
                           SquashOptions* options,
                           SquashDestroyNotify destroy_notify) {
  SquashStream* stream = (SquashStream*) s;
  squash_stream_init (stream, codec, stream_type, (SquashOptions*) options, destroy_notify);

  s->finished = false;
  if (stream_type == SQUASH_STREAM_COMPRESS) {
    brotli::BrotliParams params;
    params.quality = squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_LEVEL);
    params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_MODE);
    s->compressor = new brotli::BrotliCompressor (params);
    s->remaining_block_in = s->compressor->input_block_size();
    s->remaining_out = 0;
    s->next_out = NULL;
    s->should_flush = false;
  } else if (stream_type == SQUASH_STREAM_DECOMPRESS) {
    s->in.cb_ = squash_brotli_reader;
    s->in.data_ = (void*) stream;
    s->out.cb_ = squash_brotli_writer;
    s->out.data_ = (void*) stream;
    s->decompressor = new BrotliState ();
    BrotliStateInit(s->decompressor);
  } else {
    squash_assert_unreachable();
  }
}

static void
squash_brotli_stream_destroy (void* stream) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;

  if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_COMPRESS) {
    delete s->compressor;
  } else if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_DECOMPRESS) {
    BrotliStateCleanup(s->decompressor);
    delete s->decompressor;
  } else {
    squash_assert_unreachable();
  }

  squash_stream_destroy (stream);
}

static void
squash_brotli_stream_free (void* stream) {
  squash_brotli_stream_destroy (stream);
  free (stream);
}

static SquashStream*
squash_brotli_create_stream (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) {
  return (SquashStream*) squash_brotli_stream_new (codec, stream_type, options);
}

static SquashStatus
squash_brotli_status_to_squash_status (BrotliResult status) {
  switch (status) {
    case BROTLI_RESULT_SUCCESS:
      return SQUASH_OK;
    case BROTLI_RESULT_NEEDS_MORE_INPUT:
      return squash_error (SQUASH_BUFFER_EMPTY);
    case BROTLI_RESULT_NEEDS_MORE_OUTPUT:
      return squash_error (SQUASH_BUFFER_FULL);
    case BROTLI_RESULT_ERROR:
    default:
      return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_compress_stream (SquashStream* stream, SquashOperation operation) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;
  if (operation == SQUASH_OPERATION_FLUSH) {
    s->should_flush = true;
  }

  bool end_of_input = false;
  while (true) {
    size_t out_size = s->remaining_out;
    if (out_size != 0) {
      out_size = (s->base_object.avail_out < out_size) ? s->base_object.avail_out : out_size;
      memcpy (s->base_object.next_out, s->next_out, out_size);
      s->base_object.next_out += out_size;
      s->base_object.avail_out -= out_size;
      s->next_out += out_size;
      s->remaining_out -= out_size;
      if (s->base_object.avail_out == 0) {
        return SQUASH_PROCESSING;
      }
    }

    if (end_of_input || s->finished) {
      return SQUASH_OK;
    }

    size_t in_size = s->base_object.avail_in;
    in_size = (in_size < s->remaining_block_in) ? in_size : s->remaining_block_in;
    if (in_size != 0) {
      s->compressor->CopyInputToRingBuffer (in_size, s->base_object.next_in);
      s->base_object.next_in += in_size;
      s->base_object.avail_in -= in_size;
      s->remaining_block_in -= in_size;
      if (s->remaining_block_in == 0) {
        s->remaining_block_in = s->compressor->input_block_size ();
      }
    }

    end_of_input = s->base_object.avail_in == 0;
    bool is_last = (operation == SQUASH_OPERATION_FINISH) && end_of_input;
    if (!s->compressor->WriteBrotliData(is_last,
                                        s->should_flush && end_of_input,
                                        &s->remaining_out, &s->next_out)) {
      return squash_error (SQUASH_FAILED);
    }
    if (is_last) {
      s->finished = true;
    }
    if (end_of_input) {
      s->should_flush = false;
    }
  }
}

static SquashStatus
squash_brotli_decompress_stream (SquashStream* stream, SquashOperation operation) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;

  if (s->finished) {
    return SQUASH_OK;
  }

  try {
    bool final = (operation == SQUASH_OPERATION_FINISH) || (s->base_object.avail_in == 0);
    BrotliResult res = BrotliDecompressStreaming (s->in, s->out, final, s->decompressor);
    if (res == BROTLI_RESULT_SUCCESS) {
      s->finished = true;
      return SQUASH_OK;
    }
    if (res ==  BROTLI_RESULT_NEEDS_MORE_OUTPUT || res == BROTLI_RESULT_NEEDS_MORE_INPUT) {
      return (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT) ? SQUASH_PROCESSING : SQUASH_OK;
    }
    return squash_error (SQUASH_FAILED);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_process_stream (SquashStream* stream, SquashOperation operation) {
  if (stream->stream_type == SQUASH_STREAM_COMPRESS)
    return squash_brotli_compress_stream (stream, operation);
  else
    return squash_brotli_decompress_stream (stream, operation);
}

static size_t
squash_brotli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_size) {
  return uncompressed_size + 5;
}

static SquashStatus
squash_brotli_decompress_buffer (SquashCodec* codec,
                                 size_t* decompressed_size,
                                 uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_size)],
                                 size_t compressed_size,
                                 const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_size)],
                                 SquashOptions* options) {
  try {
    BrotliResult res = BrotliDecompressBuffer (compressed_size, compressed,
                                               decompressed_size, decompressed);
    return squash_brotli_status_to_squash_status (res);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_compress_buffer (SquashCodec* codec,
                               size_t* compressed_size,
                               uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_size)],
                               size_t uncompressed_size,
                               const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_size)],
                               SquashOptions* options) {
  brotli::BrotliParams params;
  params.quality = squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_LEVEL);
  params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_MODE);
  try {
    int res = brotli::BrotliCompressBuffer (params,
                                            uncompressed_size, uncompressed,
                                            compressed_size, compressed);
    return (res == 1) ? SQUASH_OK : squash_error (SQUASH_FAILED);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

extern "C" SquashStatus
squash_plugin_init_plugin (SquashPlugin* plugin) {
  const SquashOptionInfoRangeInt level_range = { 1, 11, 0, false };
  squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].default_value.int_value = 11;
  squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].info.range_int = level_range;

  squash_brotli_options[SQUASH_BROTLI_OPT_MODE].default_value.int_value = brotli::BrotliParams::MODE_GENERIC;
  squash_brotli_options[SQUASH_BROTLI_OPT_MODE].info.enum_string = {
    (const SquashOptionInfoEnumStringMap []) {
      { "generic", brotli::BrotliParams::MODE_GENERIC },
      { "text", brotli::BrotliParams::MODE_TEXT },
      { "font", brotli::BrotliParams::MODE_FONT },
      { NULL, 0 } }
  };

  return SQUASH_OK;
}

extern "C" SquashStatus
squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) {
  const char* name = squash_codec_get_name (codec);

  if (strcmp ("brotli", name) == 0) {
    impl->options = squash_brotli_options;
    impl->get_max_compressed_size = squash_brotli_get_max_compressed_size;
    impl->create_stream = squash_brotli_create_stream;
    impl->process_stream = squash_brotli_process_stream;
    impl->decompress_buffer = squash_brotli_decompress_buffer;
    impl->compress_buffer = squash_brotli_compress_buffer;
  } else {
    return squash_error (SQUASH_UNABLE_TO_LOAD);
  }

  return SQUASH_OK;
}
<commit_msg>Fix use of designated initializers in C++ code<commit_after>/* Copyright (c) 2015 The Squash Authors
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Authors:
 *   Evan Nemerson <evan@nemerson.com>
 *   Eugene Kliuchnikov <eustas.ru+squash@gmail.com>
 */

#include <assert.h>

#include <squash/squash.h>

#include "brotli/enc/encode.h"
#include "brotli/dec/decode.h"

enum SquashBrotliOptionIndex {
  SQUASH_BROTLI_OPT_LEVEL = 0,
  SQUASH_BROTLI_OPT_MODE
};

/* C++ doesn't allow us to initialize this correctly here (or, at
   least, I can't figure out how to do it), so there is some extra
   code in the init_plugin func to finish it off. */
static SquashOptionInfo squash_brotli_options[] = {
  { "level", SQUASH_OPTION_TYPE_RANGE_INT },
  { "mode", SQUASH_OPTION_TYPE_ENUM_STRING },
  { NULL, SQUASH_OPTION_TYPE_NONE }
};

typedef struct SquashBrotliStream_s {
  SquashStream base_object;

  BrotliInput in;
  BrotliOutput out;
  BrotliState* decompressor;
  bool finished;
  brotli::BrotliCompressor* compressor;
  bool should_flush;
  size_t remaining_block_in;
  size_t remaining_out;
  uint8_t* next_out;
} SquashBrotliStream;

extern "C" SQUASH_PLUGIN_EXPORT
SquashStatus                squash_plugin_init_plugin     (SquashPlugin* plugin);
extern "C" SQUASH_PLUGIN_EXPORT
SquashStatus                squash_plugin_init_codec      (SquashCodec* codec, SquashCodecImpl* impl);

static void                 squash_brotli_stream_init     (SquashBrotliStream* stream,
                                                           SquashCodec* codec,
                                                           SquashStreamType stream_type,
                                                           SquashOptions* options,
                                                           SquashDestroyNotify destroy_notify);
static SquashBrotliStream*  squash_brotli_stream_new      (SquashCodec* codec,
                                                           SquashStreamType stream_type,
                                                           SquashOptions* options);
static void                 squash_brotli_stream_destroy  (void* stream);
static void                 squash_brotli_stream_free     (void* stream);

static int
squash_brotli_reader (void* user_data, uint8_t* buf, size_t size) {
  SquashBrotliStream* stream = (SquashBrotliStream*) user_data;
  size = (stream->base_object.avail_in < size) ? stream->base_object.avail_in : size;
  memcpy (buf, stream->base_object.next_in, size);
  stream->base_object.next_in += size;
  stream->base_object.avail_in -= size;
  return size;
}

static int
squash_brotli_writer (void* user_data, const uint8_t* buf, size_t size) {
  SquashBrotliStream* stream = (SquashBrotliStream*) user_data;
  size = (stream->base_object.avail_out < size) ? stream->base_object.avail_out : size;
  memcpy (stream->base_object.next_out, buf, size);
  stream->base_object.next_out += size;
  stream->base_object.avail_out -= size;
  return size;
}

static SquashBrotliStream*
squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) {
  SquashBrotliStream* stream;

  assert (codec != NULL);
  assert (stream_type == SQUASH_STREAM_COMPRESS || stream_type == SQUASH_STREAM_DECOMPRESS);

  stream = (SquashBrotliStream*) malloc (sizeof (SquashBrotliStream));
  squash_brotli_stream_init (stream, codec, stream_type, options, squash_brotli_stream_free);

  return stream;
}

static void
squash_brotli_stream_init (SquashBrotliStream* s,
                           SquashCodec* codec,
                           SquashStreamType stream_type,
                           SquashOptions* options,
                           SquashDestroyNotify destroy_notify) {
  SquashStream* stream = (SquashStream*) s;
  squash_stream_init (stream, codec, stream_type, (SquashOptions*) options, destroy_notify);

  s->finished = false;
  if (stream_type == SQUASH_STREAM_COMPRESS) {
    brotli::BrotliParams params;
    params.quality = squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_LEVEL);
    params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_MODE);
    s->compressor = new brotli::BrotliCompressor (params);
    s->remaining_block_in = s->compressor->input_block_size();
    s->remaining_out = 0;
    s->next_out = NULL;
    s->should_flush = false;
  } else if (stream_type == SQUASH_STREAM_DECOMPRESS) {
    s->in.cb_ = squash_brotli_reader;
    s->in.data_ = (void*) stream;
    s->out.cb_ = squash_brotli_writer;
    s->out.data_ = (void*) stream;
    s->decompressor = new BrotliState ();
    BrotliStateInit(s->decompressor);
  } else {
    squash_assert_unreachable();
  }
}

static void
squash_brotli_stream_destroy (void* stream) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;

  if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_COMPRESS) {
    delete s->compressor;
  } else if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_DECOMPRESS) {
    BrotliStateCleanup(s->decompressor);
    delete s->decompressor;
  } else {
    squash_assert_unreachable();
  }

  squash_stream_destroy (stream);
}

static void
squash_brotli_stream_free (void* stream) {
  squash_brotli_stream_destroy (stream);
  free (stream);
}

static SquashStream*
squash_brotli_create_stream (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) {
  return (SquashStream*) squash_brotli_stream_new (codec, stream_type, options);
}

static SquashStatus
squash_brotli_status_to_squash_status (BrotliResult status) {
  switch (status) {
    case BROTLI_RESULT_SUCCESS:
      return SQUASH_OK;
    case BROTLI_RESULT_NEEDS_MORE_INPUT:
      return squash_error (SQUASH_BUFFER_EMPTY);
    case BROTLI_RESULT_NEEDS_MORE_OUTPUT:
      return squash_error (SQUASH_BUFFER_FULL);
    case BROTLI_RESULT_ERROR:
    default:
      return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_compress_stream (SquashStream* stream, SquashOperation operation) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;
  if (operation == SQUASH_OPERATION_FLUSH) {
    s->should_flush = true;
  }

  bool end_of_input = false;
  while (true) {
    size_t out_size = s->remaining_out;
    if (out_size != 0) {
      out_size = (s->base_object.avail_out < out_size) ? s->base_object.avail_out : out_size;
      memcpy (s->base_object.next_out, s->next_out, out_size);
      s->base_object.next_out += out_size;
      s->base_object.avail_out -= out_size;
      s->next_out += out_size;
      s->remaining_out -= out_size;
      if (s->base_object.avail_out == 0) {
        return SQUASH_PROCESSING;
      }
    }

    if (end_of_input || s->finished) {
      return SQUASH_OK;
    }

    size_t in_size = s->base_object.avail_in;
    in_size = (in_size < s->remaining_block_in) ? in_size : s->remaining_block_in;
    if (in_size != 0) {
      s->compressor->CopyInputToRingBuffer (in_size, s->base_object.next_in);
      s->base_object.next_in += in_size;
      s->base_object.avail_in -= in_size;
      s->remaining_block_in -= in_size;
      if (s->remaining_block_in == 0) {
        s->remaining_block_in = s->compressor->input_block_size ();
      }
    }

    end_of_input = s->base_object.avail_in == 0;
    bool is_last = (operation == SQUASH_OPERATION_FINISH) && end_of_input;
    if (!s->compressor->WriteBrotliData(is_last,
                                        s->should_flush && end_of_input,
                                        &s->remaining_out, &s->next_out)) {
      return squash_error (SQUASH_FAILED);
    }
    if (is_last) {
      s->finished = true;
    }
    if (end_of_input) {
      s->should_flush = false;
    }
  }
}

static SquashStatus
squash_brotli_decompress_stream (SquashStream* stream, SquashOperation operation) {
  SquashBrotliStream* s = (SquashBrotliStream*) stream;

  if (s->finished) {
    return SQUASH_OK;
  }

  try {
    bool final = (operation == SQUASH_OPERATION_FINISH) || (s->base_object.avail_in == 0);
    BrotliResult res = BrotliDecompressStreaming (s->in, s->out, final, s->decompressor);
    if (res == BROTLI_RESULT_SUCCESS) {
      s->finished = true;
      return SQUASH_OK;
    }
    if (res ==  BROTLI_RESULT_NEEDS_MORE_OUTPUT || res == BROTLI_RESULT_NEEDS_MORE_INPUT) {
      return (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT) ? SQUASH_PROCESSING : SQUASH_OK;
    }
    return squash_error (SQUASH_FAILED);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_process_stream (SquashStream* stream, SquashOperation operation) {
  if (stream->stream_type == SQUASH_STREAM_COMPRESS)
    return squash_brotli_compress_stream (stream, operation);
  else
    return squash_brotli_decompress_stream (stream, operation);
}

static size_t
squash_brotli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_size) {
  return uncompressed_size + 5;
}

static SquashStatus
squash_brotli_decompress_buffer (SquashCodec* codec,
                                 size_t* decompressed_size,
                                 uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_size)],
                                 size_t compressed_size,
                                 const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_size)],
                                 SquashOptions* options) {
  try {
    BrotliResult res = BrotliDecompressBuffer (compressed_size, compressed,
                                               decompressed_size, decompressed);
    return squash_brotli_status_to_squash_status (res);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

static SquashStatus
squash_brotli_compress_buffer (SquashCodec* codec,
                               size_t* compressed_size,
                               uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_size)],
                               size_t uncompressed_size,
                               const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_size)],
                               SquashOptions* options) {
  brotli::BrotliParams params;
  params.quality = squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_LEVEL);
  params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_MODE);
  try {
    int res = brotli::BrotliCompressBuffer (params,
                                            uncompressed_size, uncompressed,
                                            compressed_size, compressed);
    return (res == 1) ? SQUASH_OK : squash_error (SQUASH_FAILED);
  } catch (const std::bad_alloc& e) {
    return squash_error (SQUASH_MEMORY);
  } catch (...) {
    return squash_error (SQUASH_FAILED);
  }
}

extern "C" SquashStatus
squash_plugin_init_plugin (SquashPlugin* plugin) {
  const SquashOptionInfoRangeInt level_range = { 1, 11, 0, false };
  squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].default_value.int_value = 11;
  squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].info.range_int = level_range;

  static const SquashOptionInfoEnumStringMap option_strings[] = {
      { "generic", brotli::BrotliParams::MODE_GENERIC },
      { "text", brotli::BrotliParams::MODE_TEXT },
      { "font", brotli::BrotliParams::MODE_FONT },
      { NULL, 0 }
  };
  squash_brotli_options[SQUASH_BROTLI_OPT_MODE].default_value.int_value = brotli::BrotliParams::MODE_GENERIC;
  squash_brotli_options[SQUASH_BROTLI_OPT_MODE].info.enum_string.values = option_strings;

  return SQUASH_OK;
}

extern "C" SquashStatus
squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) {
  const char* name = squash_codec_get_name (codec);

  if (strcmp ("brotli", name) == 0) {
    impl->options = squash_brotli_options;
    impl->get_max_compressed_size = squash_brotli_get_max_compressed_size;
    impl->create_stream = squash_brotli_create_stream;
    impl->process_stream = squash_brotli_process_stream;
    impl->decompress_buffer = squash_brotli_decompress_buffer;
    impl->compress_buffer = squash_brotli_compress_buffer;
  } else {
    return squash_error (SQUASH_UNABLE_TO_LOAD);
  }

  return SQUASH_OK;
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Scott Moreau
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <core.hpp>
#include <view.hpp>
#include <plugin.hpp>
#include <output.hpp>
#include "view-transform.hpp"
#include "workspace-manager.hpp"
#include <nonstd/make_unique.hpp>

class wayfire_alpha : public wayfire_plugin_t
{
    axis_callback axis_cb;

    public:
    void init(wayfire_config *config)
    {
        grab_interface->name = "alpha";
        grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM;

        axis_cb = [=] (wlr_event_pointer_axis* ev)
        {
            if (!output->activate_plugin(grab_interface))
                return;

            output->deactivate_plugin(grab_interface);

            auto focus = core->get_cursor_focus();

            if (!focus)
                return;

            auto view = core->find_view(focus->get_main_surface());

            auto layer = output->workspace->get_view_layer(view);

            if (layer == WF_LAYER_BACKGROUND)
                return;

            if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL)
                update_alpha_target(view, ev->delta);
        };

        auto section = config->get_section("alpha");
        auto modifier = section->get_option("modifier", "<alt>");

        output->add_axis(modifier, &axis_cb);
    }

    void update_alpha_target(wayfire_view view, float delta)
    {
        wf_2D_view *transformer;
        float alpha;

        if (!view->get_transformer("alpha"))
            view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha");

        transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get());
        alpha = transformer->alpha;

        alpha -= delta * 0.003;

        if (alpha > 1.0)
            alpha = 1.0;

        if (alpha == 1.0)
            return view->pop_transformer("alpha");

        if (alpha < 0)
            alpha = 0;

        if (transformer->alpha != alpha)
        {
            transformer->alpha = alpha;
            view->damage();
        }
    }

    void fini()
    {
        output->rem_axis(&axis_cb);
    }
};

extern "C"
{
    wayfire_plugin_t *newInstance()
    {
        return new wayfire_alpha();
    }
}
<commit_msg>alpha: Remove newline whitespace<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Scott Moreau
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <core.hpp>
#include <view.hpp>
#include <plugin.hpp>
#include <output.hpp>
#include "view-transform.hpp"
#include "workspace-manager.hpp"
#include <nonstd/make_unique.hpp>

class wayfire_alpha : public wayfire_plugin_t
{
    axis_callback axis_cb;

    public:
    void init(wayfire_config *config)
    {
        grab_interface->name = "alpha";
        grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM;

        axis_cb = [=] (wlr_event_pointer_axis* ev)
        {
            if (!output->activate_plugin(grab_interface))
                return;

            output->deactivate_plugin(grab_interface);

            auto focus = core->get_cursor_focus();

            if (!focus)
                return;

            auto view = core->find_view(focus->get_main_surface());
            auto layer = output->workspace->get_view_layer(view);

            if (layer == WF_LAYER_BACKGROUND)
                return;

            if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL)
                update_alpha_target(view, ev->delta);
        };

        auto section = config->get_section("alpha");
        auto modifier = section->get_option("modifier", "<alt>");

        output->add_axis(modifier, &axis_cb);
    }

    void update_alpha_target(wayfire_view view, float delta)
    {
        wf_2D_view *transformer;
        float alpha;

        if (!view->get_transformer("alpha"))
            view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha");

        transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get());
        alpha = transformer->alpha;

        alpha -= delta * 0.003;

        if (alpha > 1.0)
            alpha = 1.0;

        if (alpha == 1.0)
            return view->pop_transformer("alpha");

        if (alpha < 0)
            alpha = 0;

        if (transformer->alpha != alpha)
        {
            transformer->alpha = alpha;
            view->damage();
        }
    }

    void fini()
    {
        output->rem_axis(&axis_cb);
    }
};

extern "C"
{
    wayfire_plugin_t *newInstance()
    {
        return new wayfire_alpha();
    }
}
<|endoftext|>


<commit_before>// System Dependencies
#include <sys/time.h>

// Local Dependencies
#include "../include/datetime.h"
#include "../include/exception.h"

/** Divisors: The number of milliseconds per item. */
#define DAY_DIVISOR		86400000
#define HOUR_DIVISOR	3600000
#define MINUTE_DIVISOR	60000
#define SECOND_DIVISOR	1000

namespace native
{
	DateTime::DateTime()
	{
		struct timeval tv;
		struct timezone tz;

		::gettimeofday(&tv, &tz);

        _offset = short(-tz.tz_minuteswest);
		_value = (int64_t(tv.tv_sec) * 1000) + (tv.tv_usec / 1000) + (_offset * MINUTE_DIVISOR);
	}

	DateTime::DateTime(int year, int month, int day)
	{
		throw NotImplementedException();
	}

	DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset)
	{
	}

	void DateTime::addDays(int days)
	{
		_value += int64_t(days) * DAY_DIVISOR;
	}

	void DateTime::addHours(int hours)
	{
		_value += int64_t(hours) * HOUR_DIVISOR;
	}

	void DateTime::addMinutes(int minutes)
	{
		_value += int64_t(minutes) * MINUTE_DIVISOR;
	}

	void DateTime::addSeconds(int seconds)
	{
		_value += int64_t(seconds) * SECOND_DIVISOR;
	}

	void DateTime::addMilliSeconds(int milliseconds)
	{
		_value += milliseconds;
	}

	short DateTime::getDay() const
	{
		throw NotImplementedException();
	}

	WeekDay DateTime::getWeekDay() const
	{
		throw NotImplementedException();
	}

	Month DateTime::getMonth() const
	{
		throw NotImplementedException();
	}

	int DateTime::getYear() const
	{
		throw NotImplementedException();
	}

	short DateTime::getHour() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMinute() const
	{
		throw NotImplementedException();
	}

	short DateTime::getSecond() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMilliSecond() const
	{
		throw NotImplementedException();
	}

	String DateTime::toString() const
	{
		const wchar_t* format;

		if (getTimeZoneOffset() == 0)
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z";
		else
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}";

		return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(),
			getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60);
	}
}
<commit_msg>Stash changes for a sec...<commit_after>// System Dependencies
#include <sys/time.h>

// Local Dependencies
#include "../include/datetime.h"
#include "../include/exception.h"

/** Divisors: The number of milliseconds per item. */
#define DAY_DIVISOR		86400000
#define HOUR_DIVISOR	3600000
#define MINUTE_DIVISOR	60000
#define SECOND_DIVISOR	1000

namespace native
{
	DateTime::DateTime()
	{
		struct timeval tv;
		struct timezone tz;

		::gettimeofday(&tv, &tz);

        _offset = short(-tz.tz_minuteswest);
		_value = (int64_t(tv.tv_sec) * 1000) + (tv.tv_usec / 1000) + (_offset * MINUTE_DIVISOR);
	}

	DateTime::DateTime(int year, int month, int day)
	{
		throw NotImplementedException();
	}

	DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset)
	{
	}

	void DateTime::addDays(int days)
	{
		_value += int64_t(days) * DAY_DIVISOR;
	}

	void DateTime::addHours(int hours)
	{
		_value += int64_t(hours) * HOUR_DIVISOR;
	}

	void DateTime::addMinutes(int minutes)
	{
		_value += int64_t(minutes) * MINUTE_DIVISOR;
	}

	void DateTime::addSeconds(int seconds)
	{
		_value += int64_t(seconds) * SECOND_DIVISOR;
	}

	void DateTime::addMilliSeconds(int milliseconds)
	{
		_value += milliseconds;
	}

	short DateTime::getDay() const
	{
		throw NotImplementedException();
	}

	WeekDay DateTime::getWeekDay() const
	{
		throw NotImplementedException();
	}

	Month DateTime::getMonth() const
	{
		throw NotImplementedException();
	}

	int DateTime::getYear() const
	{
		throw NotImplementedException();
	}

	short DateTime::getHour() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMinute() const
	{
		throw NotImplementedException();
	}

	short DateTime::getSecond() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMilliSecond() const
	{
		return _value % 1000;
	}

	String DateTime::toString() const
	{
		const wchar_t* format;

		if (getTimeZoneOffset() == 0)
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z";
		else
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}";

		return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(),
			getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60);
	}
}
<|endoftext|>