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

////////////////////////////////////////////////
//                                            //
//  Manager class for TRD   hits              //
//                                            //
////////////////////////////////////////////////

#include "AliTRDtrackHits.h"
#include "TClonesArray.h"
#include "AliTRDhit.h"

#include <iostream.h>

ClassImp(AliTRDtrackHits)

void  AliTRDtrackHits::AddHitTRD(Int_t volumeID, Int_t trackID, Double_t x,
		    Double_t y, Double_t z,Int_t q, Bool_t inDrift)
{
  //
  // Add one TRD hit
  //

  if (inDrift) q=2*q+1;
  else q=2*q;
  AddHitKartez(volumeID, trackID,x,y,z,q);
}

Bool_t AliTRDtrackHits::First()
{
  //
  //set Current hit for the first hit
  //
  AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(0);
  if (!fHit)
    fHit = new AliTRDhit;
  if (!(param) ) {
    fCurrentHit->fStatus = kFALSE;
    return kFALSE;
  }
  //
  fCurrentHit->fParamIndex = 0;
  fCurrentHit->fStackIndex = 0;
  //
  //
  ((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
  ((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
  ((AliTRDhit*)fHit)->SetX(param->fR*TMath::Cos(param->fFi));
  ((AliTRDhit*)fHit)->SetY(param->fR*TMath::Sin(param->fFi));
  ((AliTRDhit*)fHit)->SetZ(param->fZ);
  ((AliTRDhit*)fHit)->SetQ(param->fCharge[0]/2);
  if (param->fCharge[0]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
  else ((AliTRDhit*)fHit)->SetDrift();
  fCurrentHit->fR = param->fR;

  return fCurrentHit->fStatus = kTRUE;
}

Bool_t AliTRDtrackHits::Next()
{
  //
  //
  if (!(fCurrentHit->fStatus))
    return kFALSE;

  fCurrentHit->fStackIndex++;

  AliTrackHitsParamV2 *param =  (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
  if (fCurrentHit->fStackIndex>=((UInt_t) param->fNHits)){
    fCurrentHit->fParamIndex++;
    if (fCurrentHit->fParamIndex>=((UInt_t) fArray->GetEntriesFast())){
      fCurrentHit->fStatus=kFALSE;
      return kFALSE;
    }
    param =  (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
    fCurrentHit->fStackIndex=0;
    fCurrentHit->fR = param->fR;
  }

  Double_t ratio;

  //    Double_t dfi2 = param->fAn+2*param->fAd*(fCurrentHit->fR-param->fR);
  Double_t dfi2 = param->fAn;
  dfi2*=dfi2*fCurrentHit->fR*fCurrentHit->fR;
  //    Double_t ddz2 = param->fTheta+2*param->fThetaD*(fCurrentHit->fR-param->fR);
  Double_t ddz2 =  param->fTheta;
  ddz2*=ddz2;
  ratio = TMath::Sqrt(1.+ dfi2+ ddz2);

  fCurrentHit->fR += fStep*param->fHitDistance[fCurrentHit->fStackIndex]/ratio;

  Double_t dR = fCurrentHit->fR - param->fR;
  Double_t fi = param->fFi + (param->fAn*dR+param->fAd*dR*dR);
  Double_t z  = param->fZ + (param->fTheta*dR+param->fThetaD*dR*dR);

  ((AliTRDhit*)fHit)->SetQ(param->fCharge[fCurrentHit->fStackIndex]/2);
  if ( param->fCharge[fCurrentHit->fStackIndex]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
  else ((AliTRDhit*)fHit)->SetDrift();
  ((AliTRDhit*)fHit)->SetX(fCurrentHit->fR*TMath::Cos(fi));
  ((AliTRDhit*)fHit)->SetY(fCurrentHit->fR*TMath::Sin(fi));
  ((AliTRDhit*)fHit)->SetZ(z);
  ((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
  ((AliTRDhit*)fHit)->SetTrack(param->fTrackID);

  return kTRUE;
}

<commit_msg>The size of the array is checked in First() (M.Ivanov)<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.                  *
 **************************************************************************/

////////////////////////////////////////////////
//                                            //
//  Manager class for TRD   hits              //
//                                            //
////////////////////////////////////////////////

#include "AliTRDtrackHits.h"
#include "TClonesArray.h"
#include "AliTRDhit.h"

#include <iostream.h>

ClassImp(AliTRDtrackHits)

void  AliTRDtrackHits::AddHitTRD(Int_t volumeID, Int_t trackID, Double_t x,
		    Double_t y, Double_t z,Int_t q, Bool_t inDrift)
{
  //
  // Add one TRD hit
  //

  if (inDrift) q=2*q+1;
  else q=2*q;
  AddHitKartez(volumeID, trackID,x,y,z,q);
}

Bool_t AliTRDtrackHits::First()
{
  //
  //set Current hit for the first hit
  //

  if (fArray->GetSize()<=0) {
    fCurrentHit->fStatus = kFALSE;
    return kFALSE;
  }

  AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(0);
  if (!fHit)
    fHit = new AliTRDhit;
  if (!(param) ) {
    fCurrentHit->fStatus = kFALSE;
    return kFALSE;
  }
  //
  fCurrentHit->fParamIndex = 0;
  fCurrentHit->fStackIndex = 0;
  //
  //
  ((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
  ((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
  ((AliTRDhit*)fHit)->SetX(param->fR*TMath::Cos(param->fFi));
  ((AliTRDhit*)fHit)->SetY(param->fR*TMath::Sin(param->fFi));
  ((AliTRDhit*)fHit)->SetZ(param->fZ);
  ((AliTRDhit*)fHit)->SetQ(param->fCharge[0]/2);
  if (param->fCharge[0]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
  else ((AliTRDhit*)fHit)->SetDrift();
  fCurrentHit->fR = param->fR;

  return fCurrentHit->fStatus = kTRUE;
}

Bool_t AliTRDtrackHits::Next()
{
  //
  //
  if (!(fCurrentHit->fStatus))
    return kFALSE;

  fCurrentHit->fStackIndex++;

  AliTrackHitsParamV2 *param =  (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
  if (fCurrentHit->fStackIndex>=((UInt_t) param->fNHits)){
    fCurrentHit->fParamIndex++;
    if (fCurrentHit->fParamIndex>=((UInt_t) fArray->GetEntriesFast())){
      fCurrentHit->fStatus=kFALSE;
      return kFALSE;
    }
    param =  (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
    fCurrentHit->fStackIndex=0;
    fCurrentHit->fR = param->fR;
  }

  Double_t ratio;

  //    Double_t dfi2 = param->fAn+2*param->fAd*(fCurrentHit->fR-param->fR);
  Double_t dfi2 = param->fAn;
  dfi2*=dfi2*fCurrentHit->fR*fCurrentHit->fR;
  //    Double_t ddz2 = param->fTheta+2*param->fThetaD*(fCurrentHit->fR-param->fR);
  Double_t ddz2 =  param->fTheta;
  ddz2*=ddz2;
  ratio = TMath::Sqrt(1.+ dfi2+ ddz2);

  fCurrentHit->fR += fStep*param->fHitDistance[fCurrentHit->fStackIndex]/ratio;

  Double_t dR = fCurrentHit->fR - param->fR;
  Double_t fi = param->fFi + (param->fAn*dR+param->fAd*dR*dR);
  Double_t z  = param->fZ + (param->fTheta*dR+param->fThetaD*dR*dR);

  ((AliTRDhit*)fHit)->SetQ(param->fCharge[fCurrentHit->fStackIndex]/2);
  if ( param->fCharge[fCurrentHit->fStackIndex]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
  else ((AliTRDhit*)fHit)->SetDrift();
  ((AliTRDhit*)fHit)->SetX(fCurrentHit->fR*TMath::Cos(fi));
  ((AliTRDhit*)fHit)->SetY(fCurrentHit->fR*TMath::Sin(fi));
  ((AliTRDhit*)fHit)->SetZ(z);
  ((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
  ((AliTRDhit*)fHit)->SetTrack(param->fTrackID);

  return kTRUE;
}

<|endoftext|>


<commit_before>/* <x0/request.hpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 *
 * (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
 */

#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)

#include <x0/io/fileinfo.hpp>
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/strutils.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>

namespace x0 {

class plugin;

//! \addtogroup core
//@{

/**
 * \brief a client HTTP reuqest object, holding the parsed x0 request data.
 *
 * \see header, response, connection, server
 */
struct X0_API request
{
public:
	explicit request(x0::connection& connection);

	x0::connection& connection;					///< the TCP/IP connection this request has been sent through

	// request properties
	buffer_ref method;							///< HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
	buffer_ref uri;								///< parsed request uri
	buffer_ref path;							///< decoded path-part
	fileinfo_ptr fileinfo;						///< the final entity to be served, for example the full path to the file on disk.
	buffer_ref query;							///< decoded query-part
	int http_version_major;						///< HTTP protocol version major part that this request was formed in
	int http_version_minor;						///< HTTP protocol version minor part that this request was formed in
	std::vector<x0::request_header> headers;	///< request headers
	std::string body;							///< body

	/** retrieve value of a given request header */
	buffer_ref header(const std::string& name) const;

	// accumulated request data
	buffer_ref username;						///< username this client has authenticated with.
	std::string document_root;					///< the document root directory for this request.

//	std::string if_modified_since;				//!< "If-Modified-Since" request header value, if specified.
//	std::shared_ptr<range_def> range;			//!< parsed "Range" request header

	// custom data bindings
	std::map<plugin *, custom_data_ptr> custom_data;

	// utility methods
	bool supports_protocol(int major, int minor) const;
	std::string hostid() const;
	void set_hostid(const std::string& custom);

private:
	mutable std::string hostid_;
};

// {{{ request impl
inline request::request(x0::connection& conn) :
	connection(conn)
{
}

inline bool request::supports_protocol(int major, int minor) const
{
	if (major == http_version_major && minor <= http_version_minor)
		return true;

	if (major < http_version_major)
		return true;

	return false;
}
// }}}

//@}

} // namespace x0

#endif
<commit_msg>core: properly initialize request object variables<commit_after>/* <x0/request.hpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 *
 * (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
 */

#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)

#include <x0/io/fileinfo.hpp>
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/strutils.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>

namespace x0 {

class plugin;

//! \addtogroup core
//@{

/**
 * \brief a client HTTP reuqest object, holding the parsed x0 request data.
 *
 * \see header, response, connection, server
 */
struct X0_API request
{
public:
	explicit request(x0::connection& connection);

	x0::connection& connection;					///< the TCP/IP connection this request has been sent through

	// request properties
	buffer_ref method;							///< HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
	buffer_ref uri;								///< parsed request uri
	buffer_ref path;							///< decoded path-part
	fileinfo_ptr fileinfo;						///< the final entity to be served, for example the full path to the file on disk.
	buffer_ref query;							///< decoded query-part
	int http_version_major;						///< HTTP protocol version major part that this request was formed in
	int http_version_minor;						///< HTTP protocol version minor part that this request was formed in
	std::vector<x0::request_header> headers;	///< request headers
	std::string body;							///< body

	/** retrieve value of a given request header */
	buffer_ref header(const std::string& name) const;

	// accumulated request data
	buffer_ref username;						///< username this client has authenticated with.
	std::string document_root;					///< the document root directory for this request.

//	std::string if_modified_since;				//!< "If-Modified-Since" request header value, if specified.
//	std::shared_ptr<range_def> range;			//!< parsed "Range" request header

	// custom data bindings
	std::map<plugin *, custom_data_ptr> custom_data;

	// utility methods
	bool supports_protocol(int major, int minor) const;
	std::string hostid() const;
	void set_hostid(const std::string& custom);

private:
	mutable std::string hostid_;
};

// {{{ request impl
inline request::request(x0::connection& conn) :
	connection(conn),
	method(),
	uri(),
	path(),
	fileinfo(),
	query(),
	http_version_major(0),
	http_version_minor(0),
	headers(),
	body(),
	username(),
	document_root(),
	custom_data(),
	hostid_()
{
}

inline bool request::supports_protocol(int major, int minor) const
{
	if (major == http_version_major && minor <= http_version_minor)
		return true;

	if (major < http_version_major)
		return true;

	return false;
}
// }}}

//@}

} // namespace x0

#endif
<|endoftext|>


<commit_before>#include "Galaxy.h"
extern "C"
{
#include <png.h>
#include <pngconf.h>
}
#include <fstream>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <direct.h>

Galaxy::Galaxy()
{
	mWidth = 2000;
	mHeight = 2000;

	mAverageStellarDensity = 0.1;
	mAverageStellarTemperature = 0.5;
	mAverageStellarRadius = 4.0;

	mBaseSeed = time(0);
	mLayerScale = 4;
	mLayerCount = 3;

	mTwister = new std::mt19937();
	mTwister->seed(mBaseSeed);
	mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}

Galaxy::~Galaxy()
{
	delete mRandomDistribution;
	delete mTwister;
}

void Galaxy::ParseSettings(int argc, char* arguments[])
{
	int iter = 0;
	while (iter < argc)
	{
		if (strcmp(arguments[iter], "-w") == 0)
		{
			mWidth = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-h") == 0) {
			mHeight = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-s") == 0) {
			mBaseSeed = atol(arguments[++iter]);
			delete mRandomDistribution;
			delete mTwister;
			mTwister = new std::mt19937;
			mTwister->seed(mBaseSeed);
			mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
		}
		else if (strcmp(arguments[iter], "-l") == 0) {
			mLayerCount = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-c") == 0) {
			mLayerCount = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-r") == 0) {
			mAverageStellarRadius = atof(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-d") == 0) {
			mAverageStellarDensity = atof(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-t") == 0) {
			mAverageStellarTemperature = atof(arguments[++iter]);
		}
		++iter;
	}
}

bool Galaxy::CreateDirectoryTree()
{
	char dir[128];
	for (int i = 0; i < mLayerCount; ++i)
	{
		sprintf_s(dir, "layer_%03d", i);
		if (_mkdir(dir) == ENOENT)
		{
			return false;
		}
	}
	return true;
}

void Galaxy::ExportPng(unsigned int* data, int z, int slice)
{
	char slice_name[128];
	sprintf_s(slice_name, "slice%06d", slice);
	char path[256];
	sprintf_s(path, "layer_%03d/slice_%s.png", z, slice_name);
	fprintf(stdout, "Exported to %s\n", path);
	FILE *fp;
	png_structp png_ptr;
	png_infop info_ptr;
	png_bytep row;
	fopen_s(&fp, path, "wb");
	if (fp == NULL)
	{
		fprintf(stderr, "Could not open %s for writing\n", path);
		return;
	}
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (png_ptr == NULL)
	{
		fprintf(stderr, "Could not allocate write struct\n");
		return;
	}
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL)
	{
		fprintf(stderr, "Could not allocate info struct\n");
		return;
	}
	png_init_io(png_ptr, fp);

	png_set_IHDR(png_ptr,
		info_ptr,
		mWidth, mHeight,
		8,
		PNG_COLOR_TYPE_RGBA,
		PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_DEFAULT,
		PNG_FILTER_TYPE_DEFAULT);

	png_write_info(png_ptr, info_ptr);

	row = (png_bytep) malloc(4 * mWidth * sizeof(png_byte));
	for (int y = 0; y < mHeight; y++)
	{
		for (int x = 0; x < mWidth; x++)
		{
			memcpy(&(row[x*4]), &(data[(mWidth * mHeight * slice)+(y*mWidth) + x]), 4);
		}
		png_write_row(png_ptr, row);
	}
	png_write_end(png_ptr, NULL);

	fclose(fp);
	png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
	png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
	free(row);
}

void Galaxy::Generate()
{
	CreateDirectoryTree();
	for (int z = 0; z < mLayerCount; ++z)
	{
		GenerateLayer(z);
	}
}

void Galaxy::DrawStar(unsigned int* buffer, unsigned long cx, unsigned long cy, unsigned long w, unsigned long h, double radius, double temperature)
{
	unsigned long interior = floor(radius * 0.6);
	long length = ceil(radius);
	unsigned long hyp = pow(radius, 2);
	unsigned long distance = 0;
	unsigned long x = 0;
	unsigned long y = 0;
	unsigned int color = 0x00000000;
	for (long y = -length; y < length; ++y)
	{
		for (long x = -length; x < length; ++x)
		{
			distance = pow(y,2) + pow(x, 2);
			if (((distance < interior) && (distance < hyp)) || ((x == 0) && (y == 0)))
			{
				color = CoreTemperatureToColor(temperature).values.intValue;
			}
			else
			{
				double magnitude = pow((double)x/(double)length,2.0) + pow((double)y/(double)length,2.0);
				if (magnitude > 1)
				{
					color = 0x00000000;
				}
				else
				{
					Color corona = CoreTemperatureToColor(temperature);
					corona.values.argbValues.a = 255.0 * (1.0 - magnitude);
					color = corona.values.intValue;
				}
			}

			if (((cy + y) < h) && ((cy + y) > 0) && ((cx + x) < w) && ((cx + x) > 0) && (color != 0x00000000))
			{
				buffer[((cy + y) * w) + (cx + x)] = color;
			}
		}
	}
}

Color Galaxy::CoreTemperatureToColor(double temperature)
{

	int index = floor(COLOR_COUNT * temperature);
	return ScaleColor(coreColors[index], GetTemperatureBrightness(temperature));
}

Color Galaxy::CoronaTemperatureToColor(double temperature)
{

	int index = floor(COLOR_COUNT * temperature);
	return ScaleColor(coronaColors[index], GetTemperatureBrightness(temperature));
}

Color Galaxy::ScaleColor(Color color, double amount)
{
	color.values.argbValues.r *= amount;
	color.values.argbValues.g *= amount;
	color.values.argbValues.b *= amount;
	return color;
}

double Galaxy::GetTemperatureBrightness(double temperature)
{
	double fraction = 1.0 / COLOR_COUNT;
	while (temperature > fraction)
	{
		temperature -= fraction;
	}

	return temperature/fraction;
}

double Galaxy::Random()
{
	return (*mRandomDistribution)(*mTwister);
}

void Galaxy::GenerateLayer(int z)
{
	int length = sqrt((pow(4, z))); //1, 4, 16, 64
	unsigned long layerW = mWidth * length;
	unsigned long layerH = mHeight * length;
	unsigned int* buffer = new unsigned int[layerW * layerH];
	for (unsigned long k = 0; k < (layerW * layerH); ++k)
	{
		buffer[k] = 0x00000000;
	}
	double density = 0;
	double starCount = 0;
	unsigned long x = 0;
	unsigned long y = 0;
	double radius = 0.0;
	double temperature = 0.0;
	while (density < mAverageStellarDensity)
	{
		x = layerW * Random();
		y = layerH * Random();
		radius = 2 * mAverageStellarRadius * Random();
		temperature = 2 * mAverageStellarTemperature * Random();
		DrawStar(buffer, x, y, layerW, layerH, radius, temperature);
		starCount += 1.0;
		density = starCount / (layerW * layerH);
	}
	for (int y = 0; y < length; ++y)
	{
		for (int x = 0; x < length; ++x)
		{
			unsigned long index = (y * length) + x;
			ExportPng(buffer, z, index);
		}
	}
	delete [] buffer;
}<commit_msg>MoarShapes<commit_after>#include "Galaxy.h"
extern "C"
{
#include <png.h>
#include <pngconf.h>
}
#include <fstream>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <direct.h>

Galaxy::Galaxy()
{
	mWidth = 2000;
	mHeight = 2000;

	mAverageStellarDensity = 0.1;
	mAverageStellarTemperature = 0.5;
	mAverageStellarRadius = 4.0;

	mBaseSeed = time(0);
	mLayerScale = 4;
	mLayerCount = 3;

	mTwister = new std::mt19937();
	mTwister->seed(mBaseSeed);
	mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}

Galaxy::~Galaxy()
{
	delete mRandomDistribution;
	delete mTwister;
}

void Galaxy::ParseSettings(int argc, char* arguments[])
{
	int iter = 0;
	while (iter < argc)
	{
		if (strcmp(arguments[iter], "-w") == 0)
		{
			mWidth = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-h") == 0) {
			mHeight = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-s") == 0) {
			mBaseSeed = atol(arguments[++iter]);
			delete mRandomDistribution;
			delete mTwister;
			mTwister = new std::mt19937;
			mTwister->seed(mBaseSeed);
			mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
		}
		else if (strcmp(arguments[iter], "-l") == 0) {
			mLayerCount = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-c") == 0) {
			mLayerCount = atol(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-r") == 0) {
			mAverageStellarRadius = atof(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-d") == 0) {
			mAverageStellarDensity = atof(arguments[++iter]);
		}
		else if (strcmp(arguments[iter], "-t") == 0) {
			mAverageStellarTemperature = atof(arguments[++iter]);
		}
		++iter;
	}
}

bool Galaxy::CreateDirectoryTree()
{
	char dir[128];
	for (int i = 0; i < mLayerCount; ++i)
	{
		sprintf_s(dir, "layer_%03d", i);
		if (_mkdir(dir) == ENOENT)
		{
			return false;
		}
	}
	return true;
}

void Galaxy::ExportPng(unsigned int* data, int z, int slice)
{
	char slice_name[128];
	sprintf_s(slice_name, "slice%06d", slice);
	char path[256];
	sprintf_s(path, "layer_%03d/slice_%s.png", z, slice_name);
	fprintf(stdout, "Exported to %s\n", path);
	FILE *fp;
	png_structp png_ptr;
	png_infop info_ptr;
	png_bytep row;
	fopen_s(&fp, path, "wb");
	if (fp == NULL)
	{
		fprintf(stderr, "Could not open %s for writing\n", path);
		return;
	}
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (png_ptr == NULL)
	{
		fprintf(stderr, "Could not allocate write struct\n");
		return;
	}
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL)
	{
		fprintf(stderr, "Could not allocate info struct\n");
		return;
	}
	png_init_io(png_ptr, fp);

	png_set_IHDR(png_ptr,
		info_ptr,
		mWidth, mHeight,
		8,
		PNG_COLOR_TYPE_RGBA,
		PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_DEFAULT,
		PNG_FILTER_TYPE_DEFAULT);

	png_write_info(png_ptr, info_ptr);

	row = (png_bytep) malloc(4 * mWidth * sizeof(png_byte));
	for (int y = 0; y < mHeight; y++)
	{
		for (int x = 0; x < mWidth; x++)
		{
			memcpy(&(row[x*4]), &(data[(mWidth * mHeight * slice)+(y*mWidth) + x]), 4);
		}
		png_write_row(png_ptr, row);
	}
	png_write_end(png_ptr, NULL);

	fclose(fp);
	png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
	png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
	free(row);
}

void Galaxy::Generate()
{
	CreateDirectoryTree();
	for (int z = 0; z < mLayerCount; ++z)
	{
		GenerateLayer(z);
	}
}

void Galaxy::DrawStar(unsigned int* buffer, unsigned long cx, unsigned long cy, unsigned long w, unsigned long h, double radius, double temperature)
{
	unsigned long interior = floor(radius * 0.6);
	long length = ceil(radius);
	unsigned long hyp = pow(radius, 2);
	unsigned long distance = 0;
	unsigned long x = 0;
	unsigned long y = 0;
	unsigned int color = 0x00000000;
	for (long y = -length; y < length; ++y)
	{
		for (long x = -length; x < length; ++x)
		{
			//Determine radial distance from any corner
			double corner_dist = pow((length/2) - abs(x),2) + pow((length/2) - abs(y), 2);
			distance = pow(x, 2) + pow(y, 2);

			if ((distance < interior) || ((x == 0) && (y == 0)))
			{
				color = CoreTemperatureToColor(temperature).values.intValue;
			}
			else
			{
				double magnitude = pow((double)x/(double)length,2.0) + pow((double)y/(double)length,2.0);
				if (magnitude > 1)
				{
					color = 0x00000000;
				}
				else
				{
					Color corona = CoreTemperatureToColor(temperature);
					corona.values.argbValues.a = 255.0 * (1.0 - magnitude);
					color = corona.values.intValue;
				}
			}

			if (((cy + y) < h) && ((cy + y) > 0) && ((cx + x) < w) && ((cx + x) > 0) && (color != 0x00000000))
			{
				buffer[((cy + y) * w) + (cx + x)] = color;
			}
		}
	}
}

Color Galaxy::CoreTemperatureToColor(double temperature)
{

	int index = floor(COLOR_COUNT * temperature);
	return ScaleColor(coreColors[index], GetTemperatureBrightness(temperature));
}

Color Galaxy::CoronaTemperatureToColor(double temperature)
{

	int index = floor(COLOR_COUNT * temperature);
	return ScaleColor(coronaColors[index], GetTemperatureBrightness(temperature));
}

Color Galaxy::ScaleColor(Color color, double amount)
{
	color.values.argbValues.r *= amount;
	color.values.argbValues.g *= amount;
	color.values.argbValues.b *= amount;
	return color;
}

double Galaxy::GetTemperatureBrightness(double temperature)
{
	double fraction = 1.0 / COLOR_COUNT;
	while (temperature > fraction)
	{
		temperature -= fraction;
	}

	return temperature/fraction;
}

double Galaxy::Random()
{
	return (*mRandomDistribution)(*mTwister);
}

void Galaxy::GenerateLayer(int z)
{
	int length = sqrt((pow(4, z))); //1, 4, 16, 64
	unsigned long layerW = mWidth * length;
	unsigned long layerH = mHeight * length;
	unsigned int* buffer = new unsigned int[layerW * layerH];
	for (unsigned long k = 0; k < (layerW * layerH); ++k)
	{
		buffer[k] = 0x00000000;
	}
	double density = 0;
	double starCount = 0;
	unsigned long x = 0;
	unsigned long y = 0;
	double radius = 0.0;
	double temperature = 0.0;
	while (density < mAverageStellarDensity)
	{
		x = layerW * Random();
		y = layerH * Random();
		radius = 2 * mAverageStellarRadius * Random();
		temperature = 2 * mAverageStellarTemperature * Random();
		DrawStar(buffer, x, y, layerW, layerH, radius, temperature);
		starCount += 1.0;
		density = starCount / (layerW * layerH);
	}
	for (int y = 0; y < length; ++y)
	{
		for (int x = 0; x < length; ++x)
		{
			unsigned long index = (y * length) + x;
			ExportPng(buffer, z, index);
		}
	}
	delete [] buffer;
}<|endoftext|>


<commit_before>// Copyright (c) 2009-2019 The libsfz Authors
//
// This file is part of libsfz, a free software project.  You can redistribute it and/or modify it
// under the terms of the MIT License.

#include <sfz/string-utils.hpp>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <pn/string>
#include <sfz/encoding.hpp>

using testing::Eq;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Test;

namespace sfz {
namespace {

template <typename T>
struct ValueOrMessage {
    template <typename U>
    ValueOrMessage(U u) : value(u), message(NULL) {}
    ValueOrMessage(const char* m) : value(0), message(m) {}

    T           value;
    const char* message;
};

template <>
struct ValueOrMessage<const char*> {
    ValueOrMessage(const char* m) : value(m), message(m) {}

    const char* value;
    const char* message;
};

using StringUtilitiesTest = ::testing::Test;

TEST_F(StringUtilitiesTest, Upper) {
    std::pair<pn::string_view, pn::string_view> inputs[] = {
            {"", ""},         {"a", "A"},         {"Na", "NA"},         {"WTF", "WTF"},
            {"w00t", "W00T"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
    };
    for (const auto& input : inputs) {
        pn::string      actual   = upper(input.first);
        pn::string_view expected = input.second;
        EXPECT_THAT(actual, Eq(expected))
                << "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
    }
}

TEST_F(StringUtilitiesTest, Lower) {
    std::pair<pn::string_view, pn::string_view> inputs[] = {
            {"", ""},         {"A", "a"},         {"Na", "na"},         {"ill", "ill"},
            {"HNO2", "hno2"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
    };
    for (const auto& input : inputs) {
        pn::string      actual   = lower(input.first);
        pn::string_view expected = input.second;
        EXPECT_THAT(actual, Eq(expected))
                << "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
    }
}

}  // namespace
}  // namespace sfz
<commit_msg>Remove test for Greek upper/lowercase<commit_after>// Copyright (c) 2009-2019 The libsfz Authors
//
// This file is part of libsfz, a free software project.  You can redistribute it and/or modify it
// under the terms of the MIT License.

#include <sfz/string-utils.hpp>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <pn/string>
#include <sfz/encoding.hpp>

using testing::Eq;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Test;

namespace sfz {
namespace {

template <typename T>
struct ValueOrMessage {
    template <typename U>
    ValueOrMessage(U u) : value(u), message(NULL) {}
    ValueOrMessage(const char* m) : value(0), message(m) {}

    T           value;
    const char* message;
};

template <>
struct ValueOrMessage<const char*> {
    ValueOrMessage(const char* m) : value(m), message(m) {}

    const char* value;
    const char* message;
};

using StringUtilitiesTest = ::testing::Test;

TEST_F(StringUtilitiesTest, Upper) {
    std::pair<pn::string_view, pn::string_view> inputs[] = {
            {"", ""},       {"a", "A"},       {"Na", "NA"},
            {"WTF", "WTF"}, {"w00t", "W00T"}, {"林さん", "林さん"},
    };
    for (const auto& input : inputs) {
        pn::string      actual   = upper(input.first);
        pn::string_view expected = input.second;
        EXPECT_THAT(actual, Eq(expected))
                << "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
    }
}

TEST_F(StringUtilitiesTest, Lower) {
    std::pair<pn::string_view, pn::string_view> inputs[] = {
            {"", ""},       {"A", "a"},       {"Na", "na"},
            {"ill", "ill"}, {"HNO2", "hno2"}, {"林さん", "林さん"},
    };
    for (const auto& input : inputs) {
        pn::string      actual   = lower(input.first);
        pn::string_view expected = input.second;
        EXPECT_THAT(actual, Eq(expected))
                << "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
    }
}

}  // namespace
}  // namespace sfz
<|endoftext|>


<commit_before>/*
* Memory Mapping Allocator
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/mmap_mem.h>
#include <cstring>

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

#ifndef MAP_FAILED
   #define MAP_FAILED -1
#endif

namespace Botan {

namespace {

/*
* MemoryMapping_Allocator Exception
*/
class BOTAN_DLL MemoryMapping_Failed : public Exception
   {
   public:
      MemoryMapping_Failed(const std::string& msg) :
         Exception("MemoryMapping_Allocator: " + msg) {}
   };

}

/*
* Memory Map a File into Memory
*/
void* MemoryMapping_Allocator::alloc_block(u32bit n)
   {
   class TemporaryFile
      {
      public:
         int get_fd() const { return fd; }
         const std::string path() const { return filepath; }

         TemporaryFile(const std::string& base)
            {
            const std::string path = base + "XXXXXX";

            filepath = new char[path.length() + 1];
            std::strcpy(filepath, path.c_str());

            mode_t old_umask = ::umask(077);
            fd = ::mkstemp(filepath);
            ::umask(old_umask);
            }

         ~TemporaryFile()
            {
            delete[] filepath;
            if(fd != -1 && ::close(fd) == -1)
               throw MemoryMapping_Failed("Could not close file");
            }
      private:
         int fd;
         char* filepath;
      };

   TemporaryFile file("/tmp/botan_");

   if(file.get_fd() == -1)
      throw MemoryMapping_Failed("Could not create file");

   if(::unlink(file.path().c_str()))
      throw MemoryMapping_Failed("Could not unlink file '" + file.path() + "'");

   if(::lseek(file.get_fd(), n-1, SEEK_SET) < 0)
      throw MemoryMapping_Failed("Could not seek file");

   if(::write(file.get_fd(), "\0", 1) != 1)
      throw MemoryMapping_Failed("Could not write to file");

#ifndef MAP_NOSYNC
   #define MAP_NOSYNC 0
#endif

   void* ptr = ::mmap(0, n,
                      PROT_READ | PROT_WRITE,
                      MAP_SHARED | MAP_NOSYNC,
                      file.get_fd(), 0);

   if(ptr == static_cast<void*>(MAP_FAILED))
      throw MemoryMapping_Failed("Could not map file");

   return ptr;
   }

/*
* Remove a Memory Mapping
*/
void MemoryMapping_Allocator::dealloc_block(void* ptr, u32bit n)
   {
   if(ptr == 0)
      return;

   const byte PATTERNS[] = { 0x00, 0xFF, 0xAA, 0x55, 0x73, 0x8C, 0x5F, 0xA0,
                             0x6E, 0x91, 0x30, 0xCF, 0xD3, 0x2C, 0xAC, 0x00 };

   for(u32bit j = 0; j != sizeof(PATTERNS); j++)
      {
      std::memset(ptr, PATTERNS[j], n);

      if(::msync(ptr, n, MS_SYNC))
         throw MemoryMapping_Failed("Sync operation failed");
      }

   if(::munmap(ptr, n))
      throw MemoryMapping_Failed("Could not unmap file");
   }

}
<commit_msg>Change how alloc_mmap's TemporaryFile class works. Don't expose the name at all; instead unlink it at the end of the constructor, so by the time it is fully constructed it is purely an anonymous file descriptor.<commit_after>/*
* Memory Mapping Allocator
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/mmap_mem.h>
#include <vector>
#include <cstring>

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

#ifndef MAP_FAILED
   #define MAP_FAILED -1
#endif

namespace Botan {

namespace {

/*
* MemoryMapping_Allocator Exception
*/
class BOTAN_DLL MemoryMapping_Failed : public Exception
   {
   public:
      MemoryMapping_Failed(const std::string& msg) :
         Exception("MemoryMapping_Allocator: " + msg) {}
   };

}

/*
* Memory Map a File into Memory
*/
void* MemoryMapping_Allocator::alloc_block(u32bit n)
   {
   class TemporaryFile
      {
      public:
         int get_fd() const { return fd; }

         TemporaryFile(const std::string& base)
            {
            const std::string mkstemp_template = base + "XXXXXX";

            std::vector<char> filepath(mkstemp_template.begin(),
                                       mkstemp_template.end());
            filepath.push_back(0); // add terminating NULL

            mode_t old_umask = ::umask(077);
            fd = ::mkstemp(&filepath[0]);
            ::umask(old_umask);

            if(fd == -1)
               throw MemoryMapping_Failed("Temporary file allocation failed");

            if(::unlink(&filepath[0]) != 0)
               throw MemoryMapping_Failed("Could not unlink temporary file");
            }

         ~TemporaryFile()
            {
            /*
            * We can safely close here, because post-mmap the file
            * will continue to exist until the mmap is unmapped from
            * our address space upon deallocation.
            */
            if(fd != -1 && ::close(fd) == -1)
               throw MemoryMapping_Failed("Could not close file");
            }
      private:
         int fd;
      };

   TemporaryFile file("/tmp/botan_");

   if(file.get_fd() == -1)
      throw MemoryMapping_Failed("Could not create file");

   if(::lseek(file.get_fd(), n-1, SEEK_SET) < 0)
      throw MemoryMapping_Failed("Could not seek file");

   if(::write(file.get_fd(), "\0", 1) != 1)
      throw MemoryMapping_Failed("Could not write to file");

#ifndef MAP_NOSYNC
   #define MAP_NOSYNC 0
#endif

   void* ptr = ::mmap(0, n,
                      PROT_READ | PROT_WRITE,
                      MAP_SHARED | MAP_NOSYNC,
                      file.get_fd(), 0);

   if(ptr == static_cast<void*>(MAP_FAILED))
      throw MemoryMapping_Failed("Could not map file");

   return ptr;
   }

/*
* Remove a Memory Mapping
*/
void MemoryMapping_Allocator::dealloc_block(void* ptr, u32bit n)
   {
   if(ptr == 0)
      return;

   const byte PATTERNS[] = { 0x00, 0xFF, 0xAA, 0x55, 0x73, 0x8C, 0x5F, 0xA0,
                             0x6E, 0x91, 0x30, 0xCF, 0xD3, 0x2C, 0xAC, 0x00 };

   for(u32bit j = 0; j != sizeof(PATTERNS); j++)
      {
      std::memset(ptr, PATTERNS[j], n);

      if(::msync(ptr, n, MS_SYNC))
         throw MemoryMapping_Failed("Sync operation failed");
      }

   if(::munmap(ptr, n))
      throw MemoryMapping_Failed("Could not unmap file");
   }

}
<|endoftext|>


<commit_before>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"

#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"

int
GenerateConfigFile::operator() () {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );

	std::map< std::string, std::string > mapping;
	mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
	mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
	mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
	mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
	mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
	mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
	mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
	mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";

	// FIXME: Do something clever for versioning.
	// (Should these be in the param table?)
	scratchpad->Assign( "odiDefaultInstanceType", "m4.large" );
	mapping[ "odiDefaultInstanceType" ] = "ANNEX_DEFAULT_ODI_INSTANCE_TYPE";
	scratchpad->Assign( "odiDefaultImageID", "ami-83269195" );
	mapping[ "odiDefaultImageID" ] = "ANNEX_DEFAULT_ODI_IMAGE_ID";

	// Append the annex configuration to the user config file.
	FILE * configFile = NULL;

	// Consider using createUserConfigDir() from CreateKeyPair.cpp.
	std::string userConfigName;
	MyString userConfigSource;
	param( userConfigName, "USER_CONFIG_FILE" );
	if(! userConfigName.empty()) {
		find_user_file( userConfigSource, userConfigName.c_str(), false );
		if(! userConfigSource.empty()) {
			// Create the containing directory if necessary, and only the
			// containing directory -- don't do anything stupid if the
			// user configuration directory is misconfigured.
			std::string dir, file;
			filename_split( userConfigSource.c_str(), dir, file );
			if(! IsDirectory( dir.c_str() )) {
				mkdir( dir.c_str(), 0755 );
			}

			configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
				"a", 0644 );
			if( configFile == NULL ) {
				fprintf( stderr, "Failed to open user configuration file '%s': %s (%d).  Printing configuration...\n",
					userConfigSource.c_str(), strerror( errno ), errno );
				configFile = stdout;
			}
		} else {
			fprintf( stderr, "Unable to locate your user configuration file.  Printing configuration...\n" );
			configFile = stdout;
		}
	} else {
		fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files.  Contact your system administrator.  Printing configuration...\n" );
		configFile = stdout;
	}

	fprintf( configFile, "\n" );
	fprintf( configFile, "# Generated by condor_annex -setup.\n" );

	std::string value;
	for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
		value.clear();
		scratchpad->LookupString( i->first.c_str(), value );
		if(! value.empty()) {
			fprintf( configFile, "%s = %s\n", i->second.c_str(), value.c_str() );
		}
	}

	std::string keyPath;
	scratchpad->LookupString( "KeyPath", keyPath );
	if(! keyPath.empty()) {
		fprintf( configFile, "# For debugging:\n" );
		fprintf( configFile, "# ssh -i %s +ec2-user@<address>\n", keyPath.c_str() );
	}

	fprintf( configFile, "\n" );

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}

int
GenerateConfigFile::rollback() {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );

	// This functor does nothing (to the service), so don't undo anything.

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}
<commit_msg>(#6216)  Update the default AMI.<commit_after>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"

#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"

int
GenerateConfigFile::operator() () {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );

	std::map< std::string, std::string > mapping;
	mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
	mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
	mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
	mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
	mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
	mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
	mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
	mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";

	// FIXME: Do something clever for versioning.
	scratchpad->Assign( "odiDefaultInstanceType", "m4.large" );
	mapping[ "odiDefaultInstanceType" ] = "ANNEX_DEFAULT_ODI_INSTANCE_TYPE";
	scratchpad->Assign( "odiDefaultImageID", "ami-35b13223" );
	mapping[ "odiDefaultImageID" ] = "ANNEX_DEFAULT_ODI_IMAGE_ID";

	// Append the annex configuration to the user config file.
	FILE * configFile = NULL;

	// Consider using createUserConfigDir() from CreateKeyPair.cpp.
	std::string userConfigName;
	MyString userConfigSource;
	param( userConfigName, "USER_CONFIG_FILE" );
	if(! userConfigName.empty()) {
		find_user_file( userConfigSource, userConfigName.c_str(), false );
		if(! userConfigSource.empty()) {
			// Create the containing directory if necessary, and only the
			// containing directory -- don't do anything stupid if the
			// user configuration directory is misconfigured.
			std::string dir, file;
			filename_split( userConfigSource.c_str(), dir, file );
			if(! IsDirectory( dir.c_str() )) {
				mkdir( dir.c_str(), 0755 );
			}

			configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
				"a", 0644 );
			if( configFile == NULL ) {
				fprintf( stderr, "Failed to open user configuration file '%s': %s (%d).  Printing configuration...\n",
					userConfigSource.c_str(), strerror( errno ), errno );
				configFile = stdout;
			}
		} else {
			fprintf( stderr, "Unable to locate your user configuration file.  Printing configuration...\n" );
			configFile = stdout;
		}
	} else {
		fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files.  Contact your system administrator.  Printing configuration...\n" );
		configFile = stdout;
	}

	fprintf( configFile, "\n" );
	fprintf( configFile, "# Generated by condor_annex -setup.\n" );

	std::string value;
	for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
		value.clear();
		scratchpad->LookupString( i->first.c_str(), value );
		if(! value.empty()) {
			fprintf( configFile, "%s = %s\n", i->second.c_str(), value.c_str() );
		}
	}

	std::string keyPath;
	scratchpad->LookupString( "KeyPath", keyPath );
	if(! keyPath.empty()) {
		fprintf( configFile, "# For debugging:\n" );
		fprintf( configFile, "# ssh -i %s +ec2-user@<address>\n", keyPath.c_str() );
	}

	fprintf( configFile, "\n" );

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}

int
GenerateConfigFile::rollback() {
	dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );

	// This functor does nothing (to the service), so don't undo anything.

	daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
	return PASS_STREAM;
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/*
 *   cliAppInit.c --
 *
 *
 *    This file initiliazes the application by calling all
 *    the new commands and thier respective arguments
 *
 *
 *
 *    Dated  : 12/13/2000.
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Not sure if we need to worry about old gcc compilers any more, but ... /leif
#if (__GNUC__ >= 3)
#include <iostream>
#else
#include <iostream.h>
#endif
//#include "tclExtend.h"
#include "tcl.h"
#include <unistd.h>
#include <sys/types.h>
#include "CliMgmtUtils.h"
#include "createCommand.h"
#include "hashtable.h"
#include "createArgument.h"
#include "definitions.h"
#include "ShowCmd.h"
#include "ConfigCmd.h"
#include "CliCreateCommands.h"

#if HAVE_EDITLINE_READLINE_H
#include <editline/readline.h>
#elif HAVE_READLINE_READLINE_H
#include <readline/readline.h>
#if HAVE_READLINE_HISTORY_H
#include <readline/history.h>
#endif
#endif

Tcl_Interp *interp;
extern Tcl_HashTable CommandHashtable;

int
Tcl_AppInit(Tcl_Interp * app_interp)
{
  /*
   * Intialize the Tcl interpreter.
   */
  if (Tcl_Init(app_interp) == TCL_ERROR)
    return TCL_ERROR;

  interp = app_interp;

#ifdef TCL_MEM_DEBUG
  Tcl_InitMemory(interp);
#endif

  cliCreateCommandHashtable();

  // root users are automatically enabled
  if (getuid() == 0) {
    enable_restricted_commands = TRUE;
  }

  if (CliCreateCommands() != CLI_OK)
    return CMD_ERROR;

  Tcl_SetVar(interp, "tcl_rcFileName", "~/.tshellstartup", TCL_GLOBAL_ONLY);

/* Evaluating a application specific tcl script After creating
   all the commands and sourcing the statup file */
/* Always this should be at the end of this function. */
  /*
   * Parse command-line arguments.  A leading "-file" argument is
   * ignored (a historical relic from the distant past).  If the
   * next argument doesn't start with a "-" then strip it off and
   * use it as the name of a script file to process.
   */

  const char *fileName = Tcl_GetVar(interp, "argv", TCL_LEAVE_ERR_MSG);
  /*
   * Invoke the script specified on the command line, if any.
   */

  if (fileName[0] != '\0') {
    int listArgc;
    const char **listArgv;

    if (Tcl_SplitList(interp, fileName, &listArgc, &listArgv) != TCL_OK) {
      return TCL_ERROR;
    }
    int length = strlen(listArgv[0]);
    if ((length >= 2) && (strncmp(listArgv[0], "-file", length) == 0)) {
      for (int index = 1; index < listArgc; index++) {
        Tcl_ResetResult(interp);
        if (Tcl_EvalFile(interp, listArgv[index]) != TCL_OK) {
          Tcl_AddErrorInfo(interp, "");
          Tcl_DeleteInterp(interp);
          Tcl_Exit(1);
        }
      }
    }
    ckfree((char *) listArgv);
  }

  Tcl_ResetResult(interp);

  return TCL_OK;
}

#if HAVE_LIBREADLINE

// TCL main read, eval, print loop. We don't use Tcl_Main because we want to
// use readline to get line editing and command history.
void Tcl_ReadlineMain(void)
{
  char * line;

  for (;;) {
    line = readline("trafficserver> ");
    if (line == NULL) {
      // Received EOF. Bound this into a TCL exit command just like Tcl_Main
      // does.
      Tcl_Eval(interp, "exit;");
    }

    if (*line) {
      add_history(line);
      Tcl_Eval(interp, line);
    }

    free(line);
  }

  exit(0);
}

#endif // HAVE_LIBREADLINE

// vim: set ts=2 sw=2 et :
<commit_msg>TS-1251 Adding ink_port.h include since this relies on it.<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/*
 *   cliAppInit.c --
 *
 *
 *    This file initiliazes the application by calling all
 *    the new commands and thier respective arguments
 *
 *
 *
 *    Dated  : 12/13/2000.
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Not sure if we need to worry about old gcc compilers any more, but ... /leif
#if (__GNUC__ >= 3)
#include <iostream>
#else
#include <iostream.h>
#endif
//#include "tclExtend.h"
#include "tcl.h"
#include <unistd.h>
#include <sys/types.h>
#include "CliMgmtUtils.h"
#include "createCommand.h"
#include "hashtable.h"
#include "createArgument.h"
#include "definitions.h"
#include "ShowCmd.h"
#include "ConfigCmd.h"
#include "CliCreateCommands.h"
#include "ink_port.h"

#if HAVE_EDITLINE_READLINE_H
#include <editline/readline.h>
#elif HAVE_READLINE_READLINE_H
#include <readline/readline.h>
#if HAVE_READLINE_HISTORY_H
#include <readline/history.h>
#endif
#endif

Tcl_Interp *interp;
extern Tcl_HashTable CommandHashtable;

int
Tcl_AppInit(Tcl_Interp * app_interp)
{
  /*
   * Intialize the Tcl interpreter.
   */
  if (Tcl_Init(app_interp) == TCL_ERROR)
    return TCL_ERROR;

  interp = app_interp;

#ifdef TCL_MEM_DEBUG
  Tcl_InitMemory(interp);
#endif

  cliCreateCommandHashtable();

  // root users are automatically enabled
  if (getuid() == 0) {
    enable_restricted_commands = TRUE;
  }

  if (CliCreateCommands() != CLI_OK)
    return CMD_ERROR;

  Tcl_SetVar(interp, "tcl_rcFileName", "~/.tshellstartup", TCL_GLOBAL_ONLY);

/* Evaluating a application specific tcl script After creating
   all the commands and sourcing the statup file */
/* Always this should be at the end of this function. */
  /*
   * Parse command-line arguments.  A leading "-file" argument is
   * ignored (a historical relic from the distant past).  If the
   * next argument doesn't start with a "-" then strip it off and
   * use it as the name of a script file to process.
   */

  const char *fileName = Tcl_GetVar(interp, "argv", TCL_LEAVE_ERR_MSG);
  /*
   * Invoke the script specified on the command line, if any.
   */

  if (fileName[0] != '\0') {
    int listArgc;
    const char **listArgv;

    if (Tcl_SplitList(interp, fileName, &listArgc, &listArgv) != TCL_OK) {
      return TCL_ERROR;
    }
    int length = strlen(listArgv[0]);
    if ((length >= 2) && (strncmp(listArgv[0], "-file", length) == 0)) {
      for (int index = 1; index < listArgc; index++) {
        Tcl_ResetResult(interp);
        if (Tcl_EvalFile(interp, listArgv[index]) != TCL_OK) {
          Tcl_AddErrorInfo(interp, "");
          Tcl_DeleteInterp(interp);
          Tcl_Exit(1);
        }
      }
    }
    ckfree((char *) listArgv);
  }

  Tcl_ResetResult(interp);

  return TCL_OK;
}

#if HAVE_LIBREADLINE

// TCL main read, eval, print loop. We don't use Tcl_Main because we want to
// use readline to get line editing and command history.
void Tcl_ReadlineMain(void)
{
  char * line;

  for (;;) {
    line = readline("trafficserver> ");
    if (line == NULL) {
      // Received EOF. Bound this into a TCL exit command just like Tcl_Main
      // does.
      Tcl_Eval(interp, "exit;");
    }

    if (*line) {
      add_history(line);
      Tcl_Eval(interp, line);
    }

    free(line);
  }

  exit(0);
}

#endif // HAVE_LIBREADLINE

// vim: set ts=2 sw=2 et :
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private slots:
    void initTestCase();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
    void typeForKey();
    void docForKey();
    void pluginForKey();
    void keyExists();
    void constructionStringForKey();
    void keyProvided();
};

void InfoCdbBackendUnitTest::initTestCase()
{
    // FIXME: LOCAL_DIR
    CDBWriter writer("cache.cdb");
    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
    writer.add("Battery.Charging:KEYTYPE", "TRUTH");
    writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");
    writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
    writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
    writer.close();

    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoCdbBackendUnitTest::listKeysForPlugin()
{
    QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
    QCOMPARE(keys1.count(), 2);
    QVERIFY(keys1.contains("Battery.Charging"));
    QVERIFY(keys1.contains("Internet.BytesOut"));

    QStringList keys2 = backend->listKeysForPlugin("non-existant");
    QCOMPARE(keys2.count(), 0);
}

void InfoCdbBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::docForKey()
{
    QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::pluginForKey()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));

    QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyExists()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->keyExists(key), true);

    QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
    QCOMPARE(backend->keyExists("Battery.Charging"), true);
}

void InfoCdbBackendUnitTest::constructionStringForKey()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->constructionStringForKey(key) != QString());

    QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
    QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyProvided()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->keyProvided(key) == true);

    QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>databaseExists.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private slots:
    void initTestCase();
    void databaseExists();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
    void typeForKey();
    void docForKey();
    void pluginForKey();
    void keyExists();
    void constructionStringForKey();
    void keyProvided();
};

void InfoCdbBackendUnitTest::initTestCase()
{
    // FIXME: LOCAL_DIR
    CDBWriter writer("cache.cdb");
    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
    writer.add("Battery.Charging:KEYTYPE", "TRUTH");
    writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");
    writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
    writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
    writer.close();

    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::databaseExists()
{
    QCOMPARE(backend->databaseExists(), true);
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoCdbBackendUnitTest::listKeysForPlugin()
{
    QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
    QCOMPARE(keys1.count(), 2);
    QVERIFY(keys1.contains("Battery.Charging"));
    QVERIFY(keys1.contains("Internet.BytesOut"));

    QStringList keys2 = backend->listKeysForPlugin("non-existant");
    QCOMPARE(keys2.count(), 0);
}

void InfoCdbBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::docForKey()
{
    QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::pluginForKey()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));

    QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyExists()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->keyExists(key), true);

    QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
    QCOMPARE(backend->keyExists("Battery.Charging"), true);
}

void InfoCdbBackendUnitTest::constructionStringForKey()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->constructionStringForKey(key) != QString());

    QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
    QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyProvided()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->keyProvided(key) == true);

    QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|>


<commit_before>#include "libdialog.h"
#include <qfiledialog.h>

libraryDialog::libraryDialog(ssmp *parent, Qt::WFlags flags)
	: QDialog(parent, flags)
{
	myparent = parent;
	ui.setupUi(this);
	connect(ui.browseBtn,SIGNAL(clicked()),this,SLOT(getDir()));
	if(parent->settings->value("libdir") != QVariant())
		ui.libDirTxt->setText(parent->settings->value("libdir").toString());
}

void libraryDialog::getDir()
{
	libdir = QFileDialog::getExistingDirectory(this, "Select Libdir",ui.libDirTxt->text(),
		QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
	ui.libDirTxt->setText(libdir);
}

void libraryDialog::accept()
{
	myparent->settings->setValue("libdir", ui.libDirTxt->text());
	ui.buttonBox->setDisabled(true);
	addDir2Lib(ui.libDirTxt->text());
	this->close();
}

//Adds dir & its contents to the library
void libraryDialog::addDir2Lib(QDir dir)
{
	dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
	QDirIterator di(dir, QDirIterator::Subdirectories);

	while(di.hasNext())
	{
		di.next();
		QString fpath = di.filePath();
		QFileInfo f = di.fileInfo();
		if(isAudioFile(f))//Add this song to the database
		{
			TagLib::FileName fname = fpath.toStdString().c_str();
			QMap<QString, QString> stmap;
			QMap<QString, int> itmap;

			TagLib::FileRef file = TagLib::FileRef(fname);
			if(file.isNull())
				continue; //TODO: Error out here
			//MP3 Means we can check for additional info in ID3v2 tags
			if(f.suffix() == "mp3")
			{
				TagLib::MPEG::File* fr = new TagLib::MPEG::File(fname);
				if(fr->ID3v2Tag())
				{
					//Somehow this means album artist / band. http://www.id3.org/id3v2.4.0-frames
					TagLib::ID3v2::FrameList l = fr->ID3v2Tag()->frameList("TPE2");
					if(!l.isEmpty())
						stmap["albumartist"] = l.front()->toString().toCString();
				}
				delete fr;
			}

			TagLib::Tag* genTag = file.tag();
			stmap["name"] = genTag->title().toCString();
			stmap["genre"] = genTag->genre().toCString();
			itmap["year"] = genTag->year();
			itmap["tracknum"] = genTag->track();
			stmap["album"] = genTag->album().toCString();
			stmap["artist"] = genTag->artist().toCString();
			itmap["length"] = file.audioProperties()->length();
			stmap["path"] = fpath;
			//Add collected info to db
			DBItem s;
			s.strVals = stmap;
			s.intVals = itmap;

			myparent->dbi->addSong(s);
		}
		else if(f.isDir())
			ui.curDirLbl->setText(fpath);
		//if(top) //If we're the top level of recursion update prog bar
		//	ui.progressBar->setValue(di./siz * 100);
		qApp->processEvents();
	}
}

bool libraryDialog::isAudioFile(QFileInfo f)
{
	QString type = f.suffix();
	return std::accumulate(myparent->supportedFileFormats.begin(), myparent->supportedFileFormats.end(), false,
		[type](bool a, std::string b) {return (a || b == type.toStdString());});
}

libraryDialog::~libraryDialog()
{
}
<commit_msg>Unicode was easy, turns out. Next: m4as break on file not null check<commit_after>#include "libdialog.h"
#include <qfiledialog.h>

libraryDialog::libraryDialog(ssmp *parent, Qt::WFlags flags)
	: QDialog(parent, flags)
{
	myparent = parent;
	ui.setupUi(this);
	connect(ui.browseBtn,SIGNAL(clicked()),this,SLOT(getDir()));
	if(parent->settings->value("libdir") != QVariant())
		ui.libDirTxt->setText(parent->settings->value("libdir").toString());
}

void libraryDialog::getDir()
{
	libdir = QFileDialog::getExistingDirectory(this, "Select Libdir",ui.libDirTxt->text(),
		QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
	ui.libDirTxt->setText(libdir);
}

void libraryDialog::accept()
{
	myparent->settings->setValue("libdir", ui.libDirTxt->text());
	ui.buttonBox->setDisabled(true);
	addDir2Lib(ui.libDirTxt->text());
	this->close();
}

//Adds dir & its contents to the library
void libraryDialog::addDir2Lib(QDir dir)
{
	dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
	QDirIterator di(dir, QDirIterator::Subdirectories);

	while(di.hasNext())
	{
		di.next();
		QString fpath = di.filePath();
		QFileInfo f = di.fileInfo();
		if(isAudioFile(f))//Add this song to the database
		{
			wchar_t wname[200]; //TODO: Better way than static?
			wname[fpath.toWCharArray(wname)] = 0;
			TagLib::FileName fname(wname);
			QMap<QString, QString> stmap;
			QMap<QString, int> itmap;

			TagLib::FileRef file = TagLib::FileRef(fname);
			if(file.isNull())
				continue; //TODO: Error out here
			//MP3 Means we can check for additional info in ID3v2 tags
			if(f.suffix() == "mp3")
			{
				TagLib::MPEG::File* fr = new TagLib::MPEG::File(fname);
				if(fr->ID3v2Tag())
				{
					//Somehow this means album artist / band. http://www.id3.org/id3v2.4.0-frames
					TagLib::ID3v2::FrameList l = fr->ID3v2Tag()->frameList("TPE2");
					if(!l.isEmpty())
						stmap["albumartist"] = l.front()->toString().toCString();
				}
				delete fr;
			}

			TagLib::Tag* genTag = file.tag();
			stmap["name"] = genTag->title().toCString();
			stmap["genre"] = genTag->genre().toCString();
			itmap["year"] = genTag->year();
			itmap["tracknum"] = genTag->track();
			stmap["album"] = genTag->album().toCString();
			stmap["artist"] = genTag->artist().toCString();
			itmap["length"] = file.audioProperties()->length();
			stmap["path"] = fpath;
			//Add collected info to db
			DBItem s;
			s.strVals = stmap;
			s.intVals = itmap;

			myparent->dbi->addSong(s);
		}
		else if(f.isDir())
			ui.curDirLbl->setText(fpath);
		//if(top) //If we're the top level of recursion update prog bar
		//	ui.progressBar->setValue(di./siz * 100);
		qApp->processEvents();
	}
}

bool libraryDialog::isAudioFile(QFileInfo f)
{
	QString type = f.suffix();
	return std::accumulate(myparent->supportedFileFormats.begin(), myparent->supportedFileFormats.end(), false,
		[type](bool a, std::string b) {return (a || b == type.toStdString());});
}

libraryDialog::~libraryDialog()
{
}
<|endoftext|>


<commit_before>#include "StaticLibrary.h"

#include <fstream>
#include <stdio.h>

#include "Error.h"

namespace Halide {
namespace Internal {

namespace {

std::string pad_right(std::string s, size_t max) {
    internal_assert(s.size() <= max) << s.size() << " " << s;
    while (s.size() < max) {
        s += " ";
    }
    return s;
}

std::string decimal_string(int value, size_t pad) {
    return pad_right(std::to_string(value), pad);
}

std::string octal_string(int value, size_t pad) {
    char buf[256];
    #ifdef _MSC_VER
    _snprintf(buf, sizeof(buf), "%o", value);
    #else
    snprintf(buf, sizeof(buf), "%o", value);
    #endif
    return pad_right(buf, pad);
}

}  // namespace

void create_ar_file(const std::vector<std::string> &src_files,
                    const std::string &dst_file, bool deterministic) {
    std::ofstream ar(dst_file, std::ofstream::out | std::ofstream::binary);
    user_assert(ar.good());
    ar << "!<arch>\x0A";
    for (const std::string &src_path : src_files) {
        FileStat stat = file_stat(src_path);

        // Each member must begin on an even byte boundary; insert LF as needed
        if (ar.tellp() & 1) {
            ar << "\x0A";
        }
        // Need to embed just the leaf name
        std::string src_name = base_name(src_path, '/');
        uint64_t filesize = stat.file_size;
        if (src_name.size() > 16) {
            ar << "#1/" << decimal_string(src_name.size(), 13);
            filesize += src_name.size();
        } else {
            ar << pad_right(src_name, 16);
        }
        ar << decimal_string(deterministic ? 0 : stat.mod_time, 12);  // mod time
        ar << decimal_string(deterministic ? 0 : stat.uid, 6);  // user id
        ar << decimal_string(deterministic ? 0 : stat.gid, 6);  // group id
        ar << octal_string(deterministic ? 0644 : stat.mode, 8);  // mode
        ar << decimal_string(filesize, 10);  // filesize
        ar << "\x60\x0A";  // magic
        if (src_name.size() > 16) {
            ar << src_name;
        }
        {
            std::ifstream src(src_path, std::ifstream::in | std::ifstream::binary);
            ar << src.rdbuf();
        }
    }
}

void static_library_test() {
    {
        std::ofstream a("a.tmp", std::ofstream::out);
        a << "a123b";
        user_assert(a.good());
    }
    {
        std::ofstream b("b_long_name_is_long.tmp", std::ofstream::out);
        b << "c456d";
        user_assert(b.good());
    }
    {
        std::ofstream c("./c_path.tmp", std::ofstream::out);
        c << "e789f";
        user_assert(c.good());
    }

    create_ar_file({"a.tmp", "b_long_name_is_long.tmp", "./c_path.tmp"}, "arfile.a");

    {
        std::ifstream ar("arfile.a", std::ifstream::in);
        std::ostringstream actual;
        actual << ar.rdbuf();
        const std::string expected = R"literal(!<arch>
a.tmp           0           0     0     644     5         `
a123b
#1/23           0           0     0     644     28        `
b_long_name_is_long.tmpc456dc_path.tmp      0           0     0     644     5         `
e789f)literal";
        internal_assert(actual.str() == expected)
            << "File contents wrong, expected:(" << expected << ")\nactual:(" << actual.str() << ")\n";
    }
    file_unlink("a.tmp");
    file_unlink("b_long_name_is_long.tmp");
    file_unlink("./c_path.tmp");
    file_unlink("arfile.a");

    debug(0) << "static_library_test passed\n";
}

}  // namespace Internal
}  // namespace Halide
<commit_msg>Move assert to end<commit_after>#include "StaticLibrary.h"

#include <fstream>
#include <stdio.h>

#include "Error.h"

namespace Halide {
namespace Internal {

namespace {

std::string pad_right(std::string s, size_t max) {
    internal_assert(s.size() <= max) << s.size() << " " << s;
    while (s.size() < max) {
        s += " ";
    }
    return s;
}

std::string decimal_string(int value, size_t pad) {
    return pad_right(std::to_string(value), pad);
}

std::string octal_string(int value, size_t pad) {
    char buf[256];
    #ifdef _MSC_VER
    _snprintf(buf, sizeof(buf), "%o", value);
    #else
    snprintf(buf, sizeof(buf), "%o", value);
    #endif
    return pad_right(buf, pad);
}

}  // namespace

void create_ar_file(const std::vector<std::string> &src_files,
                    const std::string &dst_file, bool deterministic) {
    std::ofstream ar(dst_file, std::ofstream::out | std::ofstream::binary);
    ar << "!<arch>\x0A";
    for (const std::string &src_path : src_files) {
        FileStat stat = file_stat(src_path);

        // Each member must begin on an even byte boundary; insert LF as needed
        if (ar.tellp() & 1) {
            ar << "\x0A";
        }
        // Need to embed just the leaf name
        std::string src_name = base_name(src_path, '/');
        uint64_t filesize = stat.file_size;
        if (src_name.size() > 16) {
            ar << "#1/" << decimal_string(src_name.size(), 13);
            filesize += src_name.size();
        } else {
            ar << pad_right(src_name, 16);
        }
        ar << decimal_string(deterministic ? 0 : stat.mod_time, 12);  // mod time
        ar << decimal_string(deterministic ? 0 : stat.uid, 6);  // user id
        ar << decimal_string(deterministic ? 0 : stat.gid, 6);  // group id
        ar << octal_string(deterministic ? 0644 : stat.mode, 8);  // mode
        ar << decimal_string(filesize, 10);  // filesize
        ar << "\x60\x0A";  // magic
        if (src_name.size() > 16) {
            ar << src_name;
        }
        {
            std::ifstream src(src_path, std::ifstream::in | std::ifstream::binary);
            ar << src.rdbuf();
        }
    }
    user_assert(ar.good());
}

void static_library_test() {
    {
        std::ofstream a("a.tmp", std::ofstream::out);
        a << "a123b";
        user_assert(a.good());
    }
    {
        std::ofstream b("b_long_name_is_long.tmp", std::ofstream::out);
        b << "c456d";
        user_assert(b.good());
    }
    {
        std::ofstream c("./c_path.tmp", std::ofstream::out);
        c << "e789f";
        user_assert(c.good());
    }

    create_ar_file({"a.tmp", "b_long_name_is_long.tmp", "./c_path.tmp"}, "arfile.a");

    {
        std::ifstream ar("arfile.a", std::ifstream::in);
        std::ostringstream actual;
        actual << ar.rdbuf();
        const std::string expected = R"literal(!<arch>
a.tmp           0           0     0     644     5         `
a123b
#1/23           0           0     0     644     28        `
b_long_name_is_long.tmpc456dc_path.tmp      0           0     0     644     5         `
e789f)literal";
        internal_assert(actual.str() == expected)
            << "File contents wrong, expected:(" << expected << ")\nactual:(" << actual.str() << ")\n";
    }
    file_unlink("a.tmp");
    file_unlink("b_long_name_is_long.tmp");
    file_unlink("./c_path.tmp");
    file_unlink("arfile.a");

    debug(0) << "static_library_test passed\n";
}

}  // namespace Internal
}  // namespace Halide
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
/** @file StringHelpers.cxx
 ** Implementation of widely useful string functions.
 **/
// Copyright 2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <string.h>

#include <string>
#include <vector>

#include "Scintilla.h"

#include "GUI.h"
//~ #include "SString.h"
#include "StringHelpers.h"

bool StartsWith(GUI::gui_string const &s, GUI::gui_string const &start) {
	return (s.size() >= start.size()) &&
		(std::equal(s.begin(), s.begin() + start.size(), start.begin()));
}

bool EndsWith(GUI::gui_string const &s, GUI::gui_string const &end) {
	return (s.size() >= end.size()) &&
		(std::equal(s.begin() + s.size() - end.size(), s.end(), end.begin()));
}

int Substitute(GUI::gui_string &s, const GUI::gui_string &sFind, const GUI::gui_string &sReplace) {
	int c = 0;
	size_t lenFind = sFind.size();
	size_t lenReplace = sReplace.size();
	size_t posFound = s.find(sFind);
	while (posFound != GUI::gui_string::npos) {
		s.replace(posFound, lenFind, sReplace);
		posFound = s.find(sFind, posFound + lenReplace);
		c++;
	}
	return c;
}

/**
 * Convert a string into C string literal form using \a, \b, \f, \n, \r, \t, \v, and \ooo.
 * The return value is a newly allocated character array containing the result.
 * 4 bytes are allocated for each byte of the input because that is the maximum
 * expansion needed when all of the input needs to be output using the octal form.
 * The return value should be deleted with delete[].
 */
char *Slash(const char *s, bool quoteQuotes) {
	char *oRet = new char[strlen(s) * 4 + 1];
	char *o = oRet;
	while (*s) {
		if (*s == '\a') {
			*o++ = '\\';
			*o++ = 'a';
		} else if (*s == '\b') {
			*o++ = '\\';
			*o++ = 'b';
		} else if (*s == '\f') {
			*o++ = '\\';
			*o++ = 'f';
		} else if (*s == '\n') {
			*o++ = '\\';
			*o++ = 'n';
		} else if (*s == '\r') {
			*o++ = '\\';
			*o++ = 'r';
		} else if (*s == '\t') {
			*o++ = '\\';
			*o++ = 't';
		} else if (*s == '\v') {
			*o++ = '\\';
			*o++ = 'v';
		} else if (*s == '\\') {
			*o++ = '\\';
			*o++ = '\\';
		} else if (quoteQuotes && (*s == '\'')) {
			*o++ = '\\';
			*o++ = '\'';
		} else if (quoteQuotes && (*s == '\"')) {
			*o++ = '\\';
			*o++ = '\"';
		} else if (isascii(*s) && (*s < ' ')) {
			*o++ = '\\';
			*o++ = static_cast<char>((*s >> 6) + '0');
			*o++ = static_cast<char>((*s >> 3) + '0');
			*o++ = static_cast<char>((*s & 0x7) + '0');
		} else {
			*o++ = *s;
		}
		s++;
	}
	*o = '\0';
	return oRet;
}

/**
 * Is the character an octal digit?
 */
static bool IsOctalDigit(char ch) {
	return ch >= '0' && ch <= '7';
}

/**
 * If the character is an hexa digit, get its value.
 */
static int GetHexaDigit(char ch) {
	if (ch >= '0' && ch <= '9') {
		return ch - '0';
	}
	if (ch >= 'A' && ch <= 'F') {
		return ch - 'A' + 10;
	}
	if (ch >= 'a' && ch <= 'f') {
		return ch - 'a' + 10;
	}
	return -1;
}

/**
 * Convert C style \a, \b, \f, \n, \r, \t, \v, \ooo and \xhh into their indicated characters.
 */
unsigned int UnSlash(char *s) {
	char *sStart = s;
	char *o = s;

	while (*s) {
		if (*s == '\\') {
			s++;
			if (*s == 'a') {
				*o = '\a';
			} else if (*s == 'b') {
				*o = '\b';
			} else if (*s == 'f') {
				*o = '\f';
			} else if (*s == 'n') {
				*o = '\n';
			} else if (*s == 'r') {
				*o = '\r';
			} else if (*s == 't') {
				*o = '\t';
			} else if (*s == 'v') {
				*o = '\v';
			} else if (IsOctalDigit(*s)) {
				int val = *s - '0';
				if (IsOctalDigit(*(s + 1))) {
					s++;
					val *= 8;
					val += *s - '0';
					if (IsOctalDigit(*(s + 1))) {
						s++;
						val *= 8;
						val += *s - '0';
					}
				}
				*o = static_cast<char>(val);
			} else if (*s == 'x') {
				s++;
				int val = 0;
				int ghd = GetHexaDigit(*s);
				if (ghd >= 0) {
					s++;
					val = ghd;
					ghd = GetHexaDigit(*s);
					if (ghd >= 0) {
						s++;
						val *= 16;
						val += ghd;
					}
				}
				*o = static_cast<char>(val);
			} else {
				*o = *s;
			}
		} else {
			*o = *s;
		}
		o++;
		if (*s) {
			s++;
		}
	}
	*o = '\0';
	return o - sStart;
}

/**
 * Convert C style \0oo into their indicated characters.
 * This is used to get control characters into the regular expresion engine.
 */
unsigned int UnSlashLowOctal(char *s) {
	char *sStart = s;
	char *o = s;
	while (*s) {
		if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigit(s[2]) && IsOctalDigit(s[3])) {
			*o = static_cast<char>(8 * (s[2] - '0') + (s[3] - '0'));
			s += 3;
		} else {
			*o = *s;
		}
		o++;
		if (*s)
			s++;
	}
	*o = '\0';
	return o - sStart;
}
<commit_msg>Removed dead code.<commit_after>// SciTE - Scintilla based Text Editor
/** @file StringHelpers.cxx
 ** Implementation of widely useful string functions.
 **/
// Copyright 2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <string.h>

#include <string>
#include <vector>

#include "Scintilla.h"

#include "GUI.h"
#include "StringHelpers.h"

bool StartsWith(GUI::gui_string const &s, GUI::gui_string const &start) {
	return (s.size() >= start.size()) &&
		(std::equal(s.begin(), s.begin() + start.size(), start.begin()));
}

bool EndsWith(GUI::gui_string const &s, GUI::gui_string const &end) {
	return (s.size() >= end.size()) &&
		(std::equal(s.begin() + s.size() - end.size(), s.end(), end.begin()));
}

int Substitute(GUI::gui_string &s, const GUI::gui_string &sFind, const GUI::gui_string &sReplace) {
	int c = 0;
	size_t lenFind = sFind.size();
	size_t lenReplace = sReplace.size();
	size_t posFound = s.find(sFind);
	while (posFound != GUI::gui_string::npos) {
		s.replace(posFound, lenFind, sReplace);
		posFound = s.find(sFind, posFound + lenReplace);
		c++;
	}
	return c;
}

/**
 * Convert a string into C string literal form using \a, \b, \f, \n, \r, \t, \v, and \ooo.
 * The return value is a newly allocated character array containing the result.
 * 4 bytes are allocated for each byte of the input because that is the maximum
 * expansion needed when all of the input needs to be output using the octal form.
 * The return value should be deleted with delete[].
 */
char *Slash(const char *s, bool quoteQuotes) {
	char *oRet = new char[strlen(s) * 4 + 1];
	char *o = oRet;
	while (*s) {
		if (*s == '\a') {
			*o++ = '\\';
			*o++ = 'a';
		} else if (*s == '\b') {
			*o++ = '\\';
			*o++ = 'b';
		} else if (*s == '\f') {
			*o++ = '\\';
			*o++ = 'f';
		} else if (*s == '\n') {
			*o++ = '\\';
			*o++ = 'n';
		} else if (*s == '\r') {
			*o++ = '\\';
			*o++ = 'r';
		} else if (*s == '\t') {
			*o++ = '\\';
			*o++ = 't';
		} else if (*s == '\v') {
			*o++ = '\\';
			*o++ = 'v';
		} else if (*s == '\\') {
			*o++ = '\\';
			*o++ = '\\';
		} else if (quoteQuotes && (*s == '\'')) {
			*o++ = '\\';
			*o++ = '\'';
		} else if (quoteQuotes && (*s == '\"')) {
			*o++ = '\\';
			*o++ = '\"';
		} else if (isascii(*s) && (*s < ' ')) {
			*o++ = '\\';
			*o++ = static_cast<char>((*s >> 6) + '0');
			*o++ = static_cast<char>((*s >> 3) + '0');
			*o++ = static_cast<char>((*s & 0x7) + '0');
		} else {
			*o++ = *s;
		}
		s++;
	}
	*o = '\0';
	return oRet;
}

/**
 * Is the character an octal digit?
 */
static bool IsOctalDigit(char ch) {
	return ch >= '0' && ch <= '7';
}

/**
 * If the character is an hexa digit, get its value.
 */
static int GetHexaDigit(char ch) {
	if (ch >= '0' && ch <= '9') {
		return ch - '0';
	}
	if (ch >= 'A' && ch <= 'F') {
		return ch - 'A' + 10;
	}
	if (ch >= 'a' && ch <= 'f') {
		return ch - 'a' + 10;
	}
	return -1;
}

/**
 * Convert C style \a, \b, \f, \n, \r, \t, \v, \ooo and \xhh into their indicated characters.
 */
unsigned int UnSlash(char *s) {
	char *sStart = s;
	char *o = s;

	while (*s) {
		if (*s == '\\') {
			s++;
			if (*s == 'a') {
				*o = '\a';
			} else if (*s == 'b') {
				*o = '\b';
			} else if (*s == 'f') {
				*o = '\f';
			} else if (*s == 'n') {
				*o = '\n';
			} else if (*s == 'r') {
				*o = '\r';
			} else if (*s == 't') {
				*o = '\t';
			} else if (*s == 'v') {
				*o = '\v';
			} else if (IsOctalDigit(*s)) {
				int val = *s - '0';
				if (IsOctalDigit(*(s + 1))) {
					s++;
					val *= 8;
					val += *s - '0';
					if (IsOctalDigit(*(s + 1))) {
						s++;
						val *= 8;
						val += *s - '0';
					}
				}
				*o = static_cast<char>(val);
			} else if (*s == 'x') {
				s++;
				int val = 0;
				int ghd = GetHexaDigit(*s);
				if (ghd >= 0) {
					s++;
					val = ghd;
					ghd = GetHexaDigit(*s);
					if (ghd >= 0) {
						s++;
						val *= 16;
						val += ghd;
					}
				}
				*o = static_cast<char>(val);
			} else {
				*o = *s;
			}
		} else {
			*o = *s;
		}
		o++;
		if (*s) {
			s++;
		}
	}
	*o = '\0';
	return o - sStart;
}

/**
 * Convert C style \0oo into their indicated characters.
 * This is used to get control characters into the regular expresion engine.
 */
unsigned int UnSlashLowOctal(char *s) {
	char *sStart = s;
	char *o = s;
	while (*s) {
		if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigit(s[2]) && IsOctalDigit(s[3])) {
			*o = static_cast<char>(8 * (s[2] - '0') + (s[3] - '0'));
			s += 3;
		} else {
			*o = *s;
		}
		o++;
		if (*s)
			s++;
	}
	*o = '\0';
	return o - sStart;
}
<|endoftext|>