<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: DCDFile_test.C,v 1.21 2004/03/17 11:18:41 amoll Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>
#include <BALL/MOLMEC/AMBER/amber.h>
///////////////////////////

START_TEST(DCDFile, "$Id: DCDFile_test.C,v 1.21 2004/03/17 11:18:41 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

String dcd_test_file("data/DCD_test.dcd");

DCDFile* p = new DCDFile;

CHECK(DCDFile() throw())
  p = new DCDFile;
	TEST_NOT_EQUAL(p, 0)
RESULT

CHECK(~DCDFile() throw())
	delete p;
RESULT

CHECK(DCDFile(const DCDFile& file) throw(Exception::FileNotFound))
  DCDFile first_file(dcd_test_file);
	DCDFile second_file(first_file);
	bool test = (first_file == second_file);
	TEST_EQUAL(test, true)
RESULT

CHECK(DCDFile(const String& name, File::OpenMode open_mode = std::ios::in) throw())
  DCDFile test_file(dcd_test_file, std::ios::in);
	TEST_EQUAL(test_file.isOpen(), true)
	TEST_EQUAL(test_file.getOpenMode(), std::ios::in)
	test_file.close();
	TEST_EQUAL(test_file.isOpen(), false)

	String filename;
	NEW_TMP_FILE(filename)
	DCDFile test_file2(filename, std::ios::out);
	TEST_EQUAL(test_file2.isOpen(), true)
	TEST_EQUAL(test_file2.getOpenMode(), std::ios::out)
	test_file2.close();
	TEST_EQUAL(test_file2.isOpen(), false)
RESULT

CHECK(const DCDFile& operator = (const DCDFile& file) throw())
  DCDFile one(dcd_test_file, std::ios::in);
	DCDFile two;
	two = one;
	bool test = (one == two);
	TEST_EQUAL(test, true)
RESULT

CHECK(void clear() throw())
	DCDFile file(dcd_test_file, std::ios::in);
	file.clear();
	DCDFile empty;
	bool test = (file == empty);
	TEST_EQUAL(test, true)
RESULT

CHECK(bool operator == (const DCDFile& file) const throw())
  DCDFile one(dcd_test_file, std::ios::in);
  DCDFile two(dcd_test_file, std::ios::in);
	bool test = (one == two);
	TEST_EQUAL(test, true)
	DCDFile three;
	test = (one == three);
	TEST_EQUAL(test, false)
RESULT

String filename;
System system;
CHECK([EXTRA] full test writing)
	PDBFile pfile("data/DCDFile_test.pdb");
	pfile.read(system);
	AmberFF amberFF;
	NEW_TMP_FILE(filename);
	DCDFile dcd(filename, std::ios::out);
	TEST_EQUAL(dcd.isAccessible(), true)
	Options options;
	SnapShotManager ssm(&system, &amberFF, options, &dcd, true);
	ssm.takeSnapShot();
	system.getAtom(0)->setPosition(Vector3(1,2,1111));
	system.getAtom(0)->setForce(Vector3(3,4,5));
	system.getAtom(0)->setVelocity(Vector3(6,7,8));
	ssm.takeSnapShot();
	ssm.flushToDisk();
	dcd.close();
	TEST_NOT_EQUAL(dcd.getSize(), 0)
RESULT

SnapShot ss;
CHECK(bool read(SnapShot& snapshot) throw())
	DCDFile dcd(filename);
	bool result = dcd.read(ss);
	TEST_EQUAL(result, true)
	ss.applySnapShot(system);
	TEST_EQUAL(system.getAtom(0)->getPosition(), Vector3(11.936, 104.294, 10.149))
	result = dcd.read(ss);
	TEST_EQUAL(result, true)
	ss.applySnapShot(system);
	TEST_EQUAL(system.getAtom(0)->getPosition(), Vector3(1,2,1111))
	TEST_EQUAL(system.getAtom(0)->getForce(), Vector3(3,4,5))
	TEST_EQUAL(system.getAtom(0)->getVelocity(), Vector3(6,7,8))
	TEST_EQUAL(dcd.read(ss), false)
RESULT

CHECK(bool readHeader() throw())
  DCDFile one(dcd_test_file, std::ios::in);
	bool test = one.readHeader();
	TEST_EQUAL(test, false)
	one.close();
	DCDFile two("data/INIFile_test.ini", std::ios::in);
	test = two.readHeader();
	TEST_EQUAL(test, false)

	DCDFile three(filename);
	test = three.readHeader();
	TEST_EQUAL(test, false)
RESULT

CHECK(bool writeHeader() throw())
	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile one(temporary, std::ios::out);
	bool test = one.writeHeader();
	TEST_EQUAL(test, true);
	one.close();
	TEST_NOT_EQUAL(one.getSize(), 0)
	DCDFile two(temporary, std::ios::in);
	test = two.readHeader();
	TEST_EQUAL(test, true);  // got false
RESULT

CHECK(bool append(const SnapShot& snapshot) throw())
	System system;
	Molecule mol;
	Atom atom;

	atom.setPosition(Vector3(1.0, 2.0, 3.0));

	mol.insert(atom);
	system.insert(mol);

	SnapShot snap;
	snap.takeSnapShot(system);

	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile one(temporary, std::ios::out);
	for (Size i = 0; i < 100; i++) one.append(snap);
	one.close();
	DCDFile two(temporary, std::ios::in);
	SnapShot snap2;
	two.read(snap2);
	// ?????
	// DCDFile lacks something like updateHeader(). As long as such a
	// function doesn't exist, appending cannot work.
	// bool test = (snap == snap2);
	// TEST_EQUAL(test, true);
RESULT

CHECK(bool flushToDisk(const std::vector<SnapShot>& buffer) throw(File::CannotWrite))
	vector<SnapShot> v;
	v.push_back(ss);
	TEST_EQUAL(ss.getNumberOfAtoms(), 892)
	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile dcd(temporary, std::ios::out);
	TEST_EQUAL(dcd.isOpen(), true)
	TEST_EQUAL(dcd.isWritable(), true)
	TEST_EQUAL(dcd.getOpenMode(), std::ios::out)
	TEST_EQUAL(dcd.isAccessible(), true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 0)
	bool result = dcd.flushToDisk(v);
	TEST_EQUAL(result, true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 1)

	result = dcd.flushToDisk(v);
	TEST_EQUAL(result, true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 2)
	dcd.close();
	TEST_NOT_EQUAL(dcd.getSize(), 0)   // got 0

	DCDFile empty;
	TEST_EXCEPTION(File::CannotWrite, empty.flushToDisk(v))
RESULT

CHECK(BALL_CREATE(DCDFile))
	DCDFile dcd(filename);
	DCDFile* dcd_ptr = (DCDFile*) dcd.create();
	TEST_NOT_EQUAL(dcd_ptr, 0)
	TEST_EQUAL(dcd_ptr->getName(), filename)
RESULT

CHECK(bool init() throw())
	// init() is called every time an object is constructed, so we won't have a
	// dedicated test here. There is no reasonable way to test it, anyway.
	DCDFile d;
	d.init();
RESULT

CHECK(bool isSwappingBytes() const throw())
	DCDFile d;
	d.isSwappingBytes();
RESULT

CHECK(bool open(const String& name, File::OpenMode open_mode = std::ios::in) throw(Exception::FileNotFound))
	DCDFile dcd;
	TEST_EXCEPTION(Exception::FileNotFound, dcd.open(""))
RESULT

CHECK(bool seekAndWriteHeader() throw())
	DCDFile d;
	TEST_EQUAL(d.seekAndWriteHeader(), false)
RESULT

CHECK(bool hasVelocities() const throw())
	DCDFile d;
	TEST_EQUAL(d.hasVelocities(), false)
RESULT

CHECK(void disableVelocityStorage() throw())
	DCDFile d;
	d.enableVelocityStorage();
	d.disableVelocityStorage();
	TEST_EQUAL(d.hasVelocities(), false)
RESULT

CHECK(void enableVelocityStorage() throw())
	DCDFile d;
	d.disableVelocityStorage();
	d.enableVelocityStorage();
	TEST_EQUAL(d.hasVelocities(), true)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: DCDFile_test.C,v 1.22 2004/03/17 13:37:35 amoll Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>
#include <BALL/MOLMEC/AMBER/amber.h>
///////////////////////////

START_TEST(DCDFile, "$Id: DCDFile_test.C,v 1.22 2004/03/17 13:37:35 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

String dcd_test_file("data/DCD_test.dcd");

DCDFile* p = new DCDFile;

CHECK(DCDFile() throw())
  p = new DCDFile;
	TEST_NOT_EQUAL(p, 0)
RESULT

CHECK(~DCDFile() throw())
	delete p;
RESULT

CHECK(DCDFile(const DCDFile& file) throw(Exception::FileNotFound))
  DCDFile first_file(dcd_test_file);
	DCDFile second_file(first_file);
	bool test = (first_file == second_file);
	TEST_EQUAL(test, true)
RESULT

CHECK(DCDFile(const String& name, File::OpenMode open_mode = std::ios::in) throw())
  DCDFile test_file(dcd_test_file, std::ios::in);
	TEST_EQUAL(test_file.isOpen(), true)
	TEST_EQUAL(test_file.getOpenMode(), std::ios::in)
	test_file.close();
	TEST_EQUAL(test_file.isOpen(), false)

	String filename;
	NEW_TMP_FILE(filename)
	DCDFile test_file2(filename, std::ios::out);
	TEST_EQUAL(test_file2.isOpen(), true)
	TEST_EQUAL(test_file2.getOpenMode(), std::ios::out)
	test_file2.close();
	TEST_EQUAL(test_file2.isOpen(), false)
RESULT

CHECK(const DCDFile& operator = (const DCDFile& file) throw())
  DCDFile one(dcd_test_file, std::ios::in);
	DCDFile two;
	two = one;
	bool test = (one == two);
	TEST_EQUAL(test, true)
RESULT

CHECK(void clear() throw())
	DCDFile file(dcd_test_file, std::ios::in);
	file.clear();
	DCDFile empty;
	bool test = (file == empty);
	TEST_EQUAL(test, true)
RESULT

CHECK(bool operator == (const DCDFile& file) const throw())
  DCDFile one(dcd_test_file, std::ios::in);
  DCDFile two(dcd_test_file, std::ios::in);
	bool test = (one == two);
	TEST_EQUAL(test, true)
	DCDFile three;
	test = (one == three);
	TEST_EQUAL(test, false)
RESULT

String filename;
System system;
CHECK([EXTRA] full test writing)
	PDBFile pfile("data/DCDFile_test.pdb");
	pfile.read(system);
	AmberFF amberFF;
	NEW_TMP_FILE(filename);
	DCDFile dcd(filename, std::ios::out);
	dcd.enableVelocityStorage();
	TEST_EQUAL(dcd.isAccessible(), true)
	Options options;
	SnapShotManager ssm(&system, &amberFF, options, &dcd, true);
	ssm.takeSnapShot();
	system.getAtom(0)->setPosition(Vector3(1,2,1111));
	system.getAtom(0)->setForce(Vector3(3,4,5));
	system.getAtom(0)->setVelocity(Vector3(6,7,8));
	ssm.takeSnapShot();
	ssm.flushToDisk();
	dcd.close();
	TEST_NOT_EQUAL(dcd.getSize(), 0)
	system.getAtom(0)->setVelocity(Vector3(1,2,3));
RESULT

SnapShot ss;
CHECK(bool read(SnapShot& snapshot) throw())
	DCDFile dcd(filename);
	bool result = dcd.read(ss);
	TEST_EQUAL(result, true)
	ss.applySnapShot(system);
	TEST_EQUAL(system.getAtom(0)->getPosition(), Vector3(11.936, 104.294, 10.149))
	TEST_EQUAL(system.getAtom(0)->getVelocity(), Vector3(0,0,0))
	result = dcd.read(ss);
	TEST_EQUAL(result, true)
	ss.applySnapShot(system);
	TEST_EQUAL(system.getAtom(0)->getPosition(), Vector3(1,2,1111))
	TEST_EQUAL(system.getAtom(0)->getForce(), Vector3(3,4,5))
	TEST_EQUAL(system.getAtom(0)->getVelocity(), Vector3(6,7,8))
	result = dcd.read(ss);
	TEST_EQUAL(result, true)
RESULT

CHECK(bool readHeader() throw())
  DCDFile one(dcd_test_file, std::ios::in);
	bool test = one.readHeader();
	TEST_EQUAL(test, false)
	one.close();
	DCDFile two("data/INIFile_test.ini", std::ios::in);
	test = two.readHeader();
	TEST_EQUAL(test, false)

	DCDFile three(filename);
	test = three.readHeader();
	TEST_EQUAL(test, false)
RESULT

CHECK(bool writeHeader() throw())
	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile one(temporary, std::ios::out);
	bool test = one.writeHeader();
	TEST_EQUAL(test, true);
	one.close();
	TEST_NOT_EQUAL(one.getSize(), 0)
	DCDFile two(temporary, std::ios::in);
	test = two.readHeader();
	TEST_EQUAL(test, true);  // got false
RESULT

CHECK(bool append(const SnapShot& snapshot) throw())
	System system;
	Molecule mol;
	Atom atom;

	atom.setPosition(Vector3(1.0, 2.0, 3.0));

	mol.insert(atom);
	system.insert(mol);

	SnapShot snap;
	snap.takeSnapShot(system);

	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile one(temporary, std::ios::out);
	for (Size i = 0; i < 100; i++) one.append(snap);
	one.close();
	DCDFile two(temporary, std::ios::in);
	SnapShot snap2;
	two.read(snap2);
	// ?????
	// DCDFile lacks something like updateHeader(). As long as such a
	// function doesn't exist, appending cannot work.
	// bool test = (snap == snap2);
	// TEST_EQUAL(test, true);
RESULT

CHECK(bool flushToDisk(const std::vector<SnapShot>& buffer) throw(File::CannotWrite))
	vector<SnapShot> v;
	v.push_back(ss);
	TEST_EQUAL(ss.getNumberOfAtoms(), 892)
	String temporary;
	NEW_TMP_FILE(temporary)
	DCDFile dcd(temporary, std::ios::out);
	TEST_EQUAL(dcd.isOpen(), true)
	TEST_EQUAL(dcd.isWritable(), true)
	TEST_EQUAL(dcd.getOpenMode(), std::ios::out)
	TEST_EQUAL(dcd.isAccessible(), true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 0)
	bool result = dcd.flushToDisk(v);
	TEST_EQUAL(result, true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 1)

	result = dcd.flushToDisk(v);
	TEST_EQUAL(result, true)
	TEST_EQUAL(dcd.getNumberOfSnapShots(), 2)
	dcd.close();
	TEST_NOT_EQUAL(dcd.getSize(), 0)   // got 0

	DCDFile empty;
	TEST_EXCEPTION(File::CannotWrite, empty.flushToDisk(v))
RESULT

CHECK(BALL_CREATE(DCDFile))
	DCDFile dcd(filename);
	DCDFile* dcd_ptr = (DCDFile*) dcd.create();
	TEST_NOT_EQUAL(dcd_ptr, 0)
	TEST_EQUAL(dcd_ptr->getName(), filename)
RESULT

CHECK(bool init() throw())
	// init() is called every time an object is constructed, so we won't have a
	// dedicated test here. There is no reasonable way to test it, anyway.
	DCDFile d;
	d.init();
RESULT

CHECK(bool isSwappingBytes() const throw())
	DCDFile d;
	d.isSwappingBytes();
RESULT

CHECK(bool open(const String& name, File::OpenMode open_mode = std::ios::in) throw(Exception::FileNotFound))
	DCDFile dcd;
	TEST_EXCEPTION(Exception::FileNotFound, dcd.open(""))
RESULT

CHECK(bool seekAndWriteHeader() throw())
	DCDFile d;
	TEST_EQUAL(d.seekAndWriteHeader(), false)
RESULT

CHECK(bool hasVelocities() const throw())
	DCDFile d;
	TEST_EQUAL(d.hasVelocities(), false)
RESULT

CHECK(void disableVelocityStorage() throw())
	DCDFile d;
	d.enableVelocityStorage();
	d.disableVelocityStorage();
	TEST_EQUAL(d.hasVelocities(), false)
RESULT

CHECK(void enableVelocityStorage() throw())
	DCDFile d;
	d.disableVelocityStorage();
	d.enableVelocityStorage();
	TEST_EQUAL(d.hasVelocities(), true)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2008 Simon Peter <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * imf.cpp - IMF Player by Simon Peter <dn.tlp@gmx.net>
 *
 * FILE FORMAT:
 * There seem to be 2 different flavors of IMF formats out there. One version
 * contains just the raw IMF music data. In this case, the first word of the
 * file is always 0 (because the music data starts this way). This is already
 * the music data! So read in the entire file and play it.
 *
 * If this word is greater than 0, it specifies the size of the following
 * song data in bytes. In this case, the file has a footer that contains
 * arbitrary infos about it. Mostly, this is plain ASCII text with some words
 * of the author. Read and play the specified amount of song data and display
 * the remaining data as ASCII text.
 *
 * NOTES:
 * This player handles the two above mentioned formats, as well as a third
 * type, invented by Martin Fernandez <mfernan@cnba.uba.ar>, that's got a
 * proper header to add title/game name information. After the header starts
 * the normal IMF file in one of the two above mentioned formats.
 *
 * This player also handles a special footer format by Adam Nielsen,
 * which has defined fields of information about the song, the author
 * and more.
 */

#include <string.h>

#include "imf.h"
#include "database.h"

/*** public methods *************************************/

CPlayer *CimfPlayer::factory(Copl *newopl)
{
  return new CimfPlayer(newopl);
}

bool CimfPlayer::load(const std::string &filename, const CFileProvider &fp)
{
  binistream *f = fp.open(filename); if(!f) return false;
  unsigned long fsize, flsize, mfsize = 0;
  unsigned int i;

  // file validation section
  {
    char	header[5];
    int		version;

    f->readString(header, 5);
    version = f->readInt(1);

    if(strncmp(header, "ADLIB", 5) || version != 1) {
      if(!fp.extension(filename, ".imf") && !fp.extension(filename, ".wlf")) {
	// It's no IMF file at all
	fp.close(f);
	return false;
      } else
	f->seek(0);	// It's a normal IMF file
    } else {
      // It's a IMF file with header
      track_name = f->readString('\0');
      game_name = f->readString('\0');
      f->ignore(1);
      mfsize = f->pos() + 2;
    }
  }

  // load section
  if(mfsize)
    fsize = f->readInt(4);
  else
    fsize = f->readInt(2);
  flsize = fp.filesize(f);
  if (mfsize + 4 > flsize || fsize >= flsize - 2 - mfsize || fsize & 3) {
    fp.close(f);        // truncated file or bad size record
    return false;
  }
  if(!fsize) {		// footerless file (raw music data)
    if(mfsize)
      f->seek(-4, binio::Add);
    else
      f->seek(-2, binio::Add);
    size = (flsize - mfsize) / 4;
  } else		// file has got a footer
    size = fsize / 4;

  data = new Sdata[size];
  for(i = 0; i < size; i++) {
    data[i].reg = f->readInt(1); data[i].val = f->readInt(1);
    data[i].time = f->readInt(2);
  }

  // read footer, if any
  if(fsize && (fsize < flsize - 2 - mfsize)) {
    if(f->readInt(1) == 0x1a) {
      // Adam Nielsen's footer format
      track_name = f->readString();
      author_name = f->readString();
      remarks = f->readString();
    } else {
      // Generic footer
      unsigned long footerlen = flsize - fsize - 2 - mfsize;

      footer = new char[footerlen + 1];
      f->readString(footer, footerlen);
      footer[footerlen] = '\0';	// Make ASCIIZ string
    }
  }

  rate = getrate(filename, fp, f);
  fp.close(f);
  rewind(0);
  return true;
}

bool CimfPlayer::update()
{
	do {
		opl->write(data[pos].reg,data[pos].val);
		del = data[pos].time;
		pos++;
	} while(!del && pos < size);

	if(pos >= size) {
		pos = 0;
		songend = true;
	}
	else timer = rate / (float)del;

	return !songend;
}

void CimfPlayer::rewind(int subsong)
{
	pos = 0; del = 0; timer = rate; songend = false;
	opl->init(); opl->write(1,32);	// go to OPL2 mode
}

std::string CimfPlayer::gettitle()
{
  std::string	title;

  title = track_name;

  if(!track_name.empty() && !game_name.empty())
    title += " - ";

  title += game_name;

  return title;
}

std::string CimfPlayer::getdesc()
{
  std::string	desc;

  if(footer)
    desc = std::string(footer);

  if(!remarks.empty() && footer)
    desc += "\n\n";

  desc += remarks;

  return desc;
}

/*** private methods *************************************/

float CimfPlayer::getrate(const std::string &filename, const CFileProvider &fp, binistream *f)
{
  if(db) {	// Database available
    f->seek(0, binio::Set);
    CClockRecord *record = (CClockRecord *)db->search(CAdPlugDatabase::CKey(*f));
    if (record && record->type == CAdPlugDatabase::CRecord::ClockSpeed)
      return record->clock;
  }

  // Otherwise the database is either unavailable, or there's no entry for this file
  if (fp.extension(filename, ".imf")) return 560.0f;
  if (fp.extension(filename, ".wlf")) return 700.0f;
  return 700.0f; // default speed for unknown files that aren't .IMF or .WLF
}
<commit_msg>imf: Allow empty footer for imf files with size header<commit_after>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2008 Simon Peter <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * imf.cpp - IMF Player by Simon Peter <dn.tlp@gmx.net>
 *
 * FILE FORMAT:
 * There seem to be 2 different flavors of IMF formats out there. One version
 * contains just the raw IMF music data. In this case, the first word of the
 * file is always 0 (because the music data starts this way). This is already
 * the music data! So read in the entire file and play it.
 *
 * If this word is greater than 0, it specifies the size of the following
 * song data in bytes. In this case, the file has a footer that contains
 * arbitrary infos about it. Mostly, this is plain ASCII text with some words
 * of the author. Read and play the specified amount of song data and display
 * the remaining data as ASCII text.
 *
 * NOTES:
 * This player handles the two above mentioned formats, as well as a third
 * type, invented by Martin Fernandez <mfernan@cnba.uba.ar>, that's got a
 * proper header to add title/game name information. After the header starts
 * the normal IMF file in one of the two above mentioned formats.
 *
 * This player also handles a special footer format by Adam Nielsen,
 * which has defined fields of information about the song, the author
 * and more.
 */

#include <string.h>

#include "imf.h"
#include "database.h"

/*** public methods *************************************/

CPlayer *CimfPlayer::factory(Copl *newopl)
{
  return new CimfPlayer(newopl);
}

bool CimfPlayer::load(const std::string &filename, const CFileProvider &fp)
{
  binistream *f = fp.open(filename); if(!f) return false;
  unsigned long fsize, flsize, mfsize = 0;
  unsigned int i;

  // file validation section
  {
    char	header[5];
    int		version;

    f->readString(header, 5);
    version = f->readInt(1);

    if(strncmp(header, "ADLIB", 5) || version != 1) {
      if(!fp.extension(filename, ".imf") && !fp.extension(filename, ".wlf")) {
	// It's no IMF file at all
	fp.close(f);
	return false;
      } else
	f->seek(0);	// It's a normal IMF file
    } else {
      // It's a IMF file with header
      track_name = f->readString('\0');
      game_name = f->readString('\0');
      f->ignore(1);
      mfsize = f->pos() + 2;
    }
  }

  // load section
  if(mfsize)
    fsize = f->readInt(4);
  else
    fsize = f->readInt(2);
  flsize = fp.filesize(f);
  if (mfsize + 4 > flsize || fsize > flsize - 2 - mfsize || fsize & 3) {
    fp.close(f);        // truncated file or bad size record
    return false;
  }
  if(!fsize) {		// footerless file (raw music data)
    if(mfsize)
      f->seek(-4, binio::Add);
    else
      f->seek(-2, binio::Add);
    size = (flsize - mfsize) / 4;
  } else		// file has got a footer
    size = fsize / 4;

  data = new Sdata[size];
  for(i = 0; i < size; i++) {
    data[i].reg = f->readInt(1); data[i].val = f->readInt(1);
    data[i].time = f->readInt(2);
  }

  // read footer, if any
  if(fsize && (fsize < flsize - 2 - mfsize)) {
    if(f->readInt(1) == 0x1a) {
      // Adam Nielsen's footer format
      track_name = f->readString();
      author_name = f->readString();
      remarks = f->readString();
    } else {
      // Generic footer
      unsigned long footerlen = flsize - fsize - 2 - mfsize;

      footer = new char[footerlen + 1];
      f->readString(footer, footerlen);
      footer[footerlen] = '\0';	// Make ASCIIZ string
    }
  }

  rate = getrate(filename, fp, f);
  fp.close(f);
  rewind(0);
  return true;
}

bool CimfPlayer::update()
{
	do {
		opl->write(data[pos].reg,data[pos].val);
		del = data[pos].time;
		pos++;
	} while(!del && pos < size);

	if(pos >= size) {
		pos = 0;
		songend = true;
	}
	else timer = rate / (float)del;

	return !songend;
}

void CimfPlayer::rewind(int subsong)
{
	pos = 0; del = 0; timer = rate; songend = false;
	opl->init(); opl->write(1,32);	// go to OPL2 mode
}

std::string CimfPlayer::gettitle()
{
  std::string	title;

  title = track_name;

  if(!track_name.empty() && !game_name.empty())
    title += " - ";

  title += game_name;

  return title;
}

std::string CimfPlayer::getdesc()
{
  std::string	desc;

  if(footer)
    desc = std::string(footer);

  if(!remarks.empty() && footer)
    desc += "\n\n";

  desc += remarks;

  return desc;
}

/*** private methods *************************************/

float CimfPlayer::getrate(const std::string &filename, const CFileProvider &fp, binistream *f)
{
  if(db) {	// Database available
    f->seek(0, binio::Set);
    CClockRecord *record = (CClockRecord *)db->search(CAdPlugDatabase::CKey(*f));
    if (record && record->type == CAdPlugDatabase::CRecord::ClockSpeed)
      return record->clock;
  }

  // Otherwise the database is either unavailable, or there's no entry for this file
  if (fp.extension(filename, ".imf")) return 560.0f;
  if (fp.extension(filename, ".wlf")) return 700.0f;
  return 700.0f; // default speed for unknown files that aren't .IMF or .WLF
}
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "../../../php_opencv.h"
#include "mat.h"

zend_object_handlers mat_object_handlers;

zend_class_entry *mat_ce;

/**
 * @param type
 * @return
 */
zend_object* mat_create_handler(zend_class_entry *type)
{
    int size = sizeof(mat_object);
    mat_object *obj = (mat_object *)ecalloc(1,size);
    memset(obj, 0, sizeof(mat_object));
    zend_object_std_init(&obj->std, type);
    object_properties_init(&obj->std, type);
    obj->std.ce = type;
    obj->std.handlers = &mat_object_handlers;
    return &obj->std;
}

void mat_free_handler(zend_object *object)
{
    mat_object *obj;
    obj = get_mat_obj(object);
    delete obj->mat;
    zend_object_std_dtor(object);
}

/**
 * Mat __construct
 * @param execute_data
 * @param return_value
 */
PHP_METHOD(Mat, __construct)
{
    long rows, cols, type;
    //获取请求的参数
    if (zend_parse_parameters(ZEND_NUM_ARGS(), "lll", &rows, &cols, &type) == FAILURE) {
        RETURN_NULL();
    }
    mat_object *obj = Z_PHP_MAT_OBJ_P(getThis());
    obj->mat = new Mat((int)rows, (int)cols, (int)type, Scalar(0));
    //obj->mat = new Mat((int)rows, (int)cols, (int)type); //TODO Why Mat array not correct
    zend_update_property_long(mat_ce, getThis(), "rows", sizeof("rows")-1, rows);
    zend_update_property_long(mat_ce, getThis(), "cols", sizeof("cols")-1, cols);
    zend_update_property_long(mat_ce, getThis(), "type", sizeof("type")-1, type);
}

/**
 * print Mat data
 * @param execute_data
 * @param return_value
 */
PHP_METHOD(Mat, print)
{
    mat_object *obj = Z_PHP_MAT_OBJ_P(getThis());
    std::cout <<*(obj->mat)<< std::endl;
    RETURN_NULL();
}

/**
 * mat_methods[]
 */
const zend_function_entry mat_methods[] = {
        PHP_ME(Mat, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
        PHP_ME(Mat, print, NULL, ZEND_ACC_PUBLIC)
        PHP_FE_END
};
/* }}} */

/**
 * Mat Class write_property
 * @param object
 * @param member
 * @param value
 * @param cache_slot
 */
void mat_write_property(zval *object, zval *member, zval *value, void **cache_slot){
    zend_string *str = zval_get_string(member);
    char *memberName=ZSTR_VAL(str);
    if(strcmp(memberName, "cols") == 0){
        mat_object *obj = Z_PHP_MAT_OBJ_P(object);
        obj->mat->cols=(int)zval_get_long(value);
    }else if(strcmp(memberName, "rows") == 0){
        mat_object *obj = Z_PHP_MAT_OBJ_P(object);
        obj->mat->rows=(int)zval_get_long(value);
    }
    zend_string_release(str);//free zend_string not memberName(zend_string->val)
    std_object_handlers.write_property(object,member,value,cache_slot);

}

/**
 * Mat Init
 */
void mat_init(){
    zend_class_entry ce;
    INIT_NS_CLASS_ENTRY(ce,"OpenCV", "Mat", mat_methods);
    mat_ce = zend_register_internal_class(&ce);
//    zend_declare_property_long(mat_ce,"rows",sizeof("rows") - 1,0,ZEND_ACC_PUBLIC);
    mat_ce->create_object = mat_create_handler;
    memcpy(&mat_object_handlers,
           zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    mat_object_handlers.clone_obj = NULL;
    mat_object_handlers.write_property = mat_write_property;
//    mat_object_handlers.free_obj = mat_free_handler;
}

<commit_msg>private declare Mat->type<commit_after>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "../../../php_opencv.h"
#include "mat.h"

zend_object_handlers mat_object_handlers;

zend_class_entry *mat_ce;

/**
 * @param type
 * @return
 */
zend_object* mat_create_handler(zend_class_entry *type)
{
    int size = sizeof(mat_object);
    mat_object *obj = (mat_object *)ecalloc(1,size);
    memset(obj, 0, sizeof(mat_object));
    zend_object_std_init(&obj->std, type);
    object_properties_init(&obj->std, type);
    obj->std.ce = type;
    obj->std.handlers = &mat_object_handlers;
    return &obj->std;
}

void mat_free_handler(zend_object *object)
{
    mat_object *obj;
    obj = get_mat_obj(object);
    delete obj->mat;
    zend_object_std_dtor(object);
}

/**
 * Mat __construct
 * @param execute_data
 * @param return_value
 */
PHP_METHOD(Mat, __construct)
{
    long rows, cols, type;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "lll", &rows, &cols, &type) == FAILURE) {
        RETURN_NULL();
    }
    mat_object *obj = Z_PHP_MAT_OBJ_P(getThis());
    obj->mat = new Mat((int)rows, (int)cols, (int)type, Scalar(0));
    //obj->mat = new Mat((int)rows, (int)cols, (int)type); //TODO Why Mat array not correct
    zend_update_property_long(mat_ce, getThis(), "rows", sizeof("rows")-1, rows);
    zend_update_property_long(mat_ce, getThis(), "cols", sizeof("cols")-1, cols);
    zend_update_property_long(mat_ce, getThis(), "type", sizeof("type")-1, type);
}

/**
 * print Mat data
 * @param execute_data
 * @param return_value
 */
PHP_METHOD(Mat, print)
{
    mat_object *obj = Z_PHP_MAT_OBJ_P(getThis());
    std::cout <<*(obj->mat)<< std::endl;
    RETURN_NULL();
}

/**
 * mat_methods[]
 */
const zend_function_entry mat_methods[] = {
        PHP_ME(Mat, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
        PHP_ME(Mat, print, NULL, ZEND_ACC_PUBLIC)
        PHP_FE_END
};
/* }}} */

/**
 * Mat Class write_property
 * @param object
 * @param member
 * @param value
 * @param cache_slot
 */
void mat_write_property(zval *object, zval *member, zval *value, void **cache_slot){

    zend_string *str = zval_get_string(member);
    char *memberName=ZSTR_VAL(str);
    mat_object *obj = Z_PHP_MAT_OBJ_P(object);

    if(strcmp(memberName, "cols") == 0 && obj->mat->cols!=(int)zval_get_long(value)){
        obj->mat->cols=(int)zval_get_long(value);
    }else if(strcmp(memberName, "rows") == 0 && obj->mat->rows!=(int)zval_get_long(value)){
        obj->mat->rows=(int)zval_get_long(value);
    }
    zend_string_release(str);//free zend_string not memberName(zend_string->val)
    std_object_handlers.write_property(object,member,value,cache_slot);

}

/**
 * Mat Init
 */
void mat_init(){
    zend_class_entry ce;
    INIT_NS_CLASS_ENTRY(ce,"OpenCV", "Mat", mat_methods);
    mat_ce = zend_register_internal_class(&ce);

    mat_ce->create_object = mat_create_handler;
    memcpy(&mat_object_handlers,
           zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    mat_object_handlers.clone_obj = NULL;
    mat_object_handlers.write_property = mat_write_property;

    zend_declare_property_null(mat_ce,"type",sizeof("type") - 1,ZEND_ACC_PRIVATE);//private Mat->type
//    mat_object_handlers.free_obj = mat_free_handler;
}

<|endoftext|>


<commit_before>#ifndef PK_PREFIXFUNCTION_HPP
#define PK_PREFIXFUNCTION_HPP

namespace pk
{

/**
 * Computes Knuth's prefix function in linear time complexity.
 *
 * Can be used as a string searching algorithm.
 * For a given pattern and string call run() function
 * with text = pattern#string and find all occurances of
 * pattern's size in the computed prefix-suffix table.
 */
template<int MaxTextSize>
class prefix_function
{
public:
    /**
     * Computes Knuth's prefix function for a given text.
     * The result can be obtained by get_prefix_suffix_table() function.
     */
    void run(const char* text, const int text_size)
    {
        prefix_suffix_table[0] = 0;
        int t = prefix_suffix_table[0];

        for(int i = 1; i < text_size; ++i)
        {
            while(t > 0 && text[t] != text[i])
                t = prefix_suffix_table[t-1];

            if(text[t] == text[i])
                ++t;
            prefix_suffix_table[i] = t;
        }
    }

    /**
     * Return a prefix-suffix table for a text computed by run() function,
     * where i'th element of the table is the longest (but shorter that i+1)
     * prefix-suffix of a substring text[0,..,i].
     */
    const int* get_prefix_suffix_table() const
    {
        return prefix_suffix_table;
    }

private:
    int prefix_suffix_table[MaxTextSize];
};

} // namespace pk

#endif // PK_PREFIXFUNCTION_HPP
<commit_msg>Typo fix<commit_after>#ifndef PK_PREFIXFUNCTION_HPP
#define PK_PREFIXFUNCTION_HPP

namespace pk
{

/**
 * Computes Knuth's prefix function in linear time complexity.
 *
 * Can be used as a string searching algorithm.
 * For a given pattern and string call run() function
 * with text = pattern#string and find all occurances of
 * pattern's size in the computed prefix-suffix table.
 */
template<int MaxTextSize>
class prefix_function
{
public:
    /**
     * Computes Knuth's prefix function for a given text.
     * The result can be obtained by get_prefix_suffix_table() function.
     */
    void run(const char* text, const int text_size)
    {
        prefix_suffix_table[0] = 0;
        int t = prefix_suffix_table[0];

        for(int i = 1; i < text_size; ++i)
        {
            while(t > 0 && text[t] != text[i])
                t = prefix_suffix_table[t-1];

            if(text[t] == text[i])
                ++t;
            prefix_suffix_table[i] = t;
        }
    }

    /**
     * Returns a prefix-suffix table for a text computed by run() function,
     * where i'th element of the table is the longest (but shorter that i+1)
     * prefix-suffix of a substring text[0,..,i].
     */
    const int* get_prefix_suffix_table() const
    {
        return prefix_suffix_table;
    }

private:
    int prefix_suffix_table[MaxTextSize];
};

} // namespace pk

#endif // PK_PREFIXFUNCTION_HPP
<|endoftext|>


<commit_before>/*
* Copyright 2016 Jaskaran Singh <jvsg1303@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*        http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "log.hxx"

void logger (enum category eCategory, enum destination eDestination, const char* pSourceFile, const char* pMessage)
{
    char* pFullMessage = malloc(200);

    switch (eCategory)
    {
        case EMERGENCY : strcpy(pFullMessage, "EMERGENCY >>"); break;
        case WARNING : strcpy(pFullMessage, "WARNING   >>"); break;
        case DEBUG : strcpy(pFullMessage, "DEBUG     >>"); break;
        case INFO : strcpy(pFullMessage, "INFO      >>"); break;
        default: strcpy(pFullMessage, "INFO      >>");
    }

    strcat(pFullMessage, pSourceFile);
    strcat(pFullMessage, " : ");
    strcat(pFullMessage, pMessage);

    errno = 0;
    FILE* file;
    file = fopen("./../log/Memory_Smith.log", "a");

    if (!file)
        printf ("Unable to open logging file for appending. errorno = %d\n", errno);
    else
    {
        eDestination == 0 ? fprintf(file, pFullMessage) : printf("%s", pFullMessage);
        fclose(file);
    }
    return;
}
<commit_msg>Explicitly state type onversion<commit_after>/*
* Copyright 2016 Jaskaran Singh <jvsg1303@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*        http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "log.hxx"

void logger (enum category eCategory, enum destination eDestination, const char* pSourceFile, const char* pMessage)
{
    char* pFullMessage = (char *) malloc(200);

    switch (eCategory)
    {
        case EMERGENCY : strcpy(pFullMessage, "EMERGENCY >>"); break;
        case WARNING : strcpy(pFullMessage, "WARNING   >>"); break;
        case DEBUG : strcpy(pFullMessage, "DEBUG     >>"); break;
        case INFO : strcpy(pFullMessage, "INFO      >>"); break;
        default: strcpy(pFullMessage, "INFO      >>");
    }

    strcat(pFullMessage, pSourceFile);
    strcat(pFullMessage, " : ");
    strcat(pFullMessage, pMessage);

    errno = 0;
    FILE* file;
    file = fopen("./../log/Memory_Smith.log", "a");

    if (!file)
        printf ("Unable to open logging file for appending. errorno = %d\n", errno);
    else
    {
        eDestination == 0 ? fprintf(file, pFullMessage) : printf("%s", pFullMessage);
        fclose(file);
    }
    return;
}
<|endoftext|>


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

QGroundControl Open Source Ground Control Station

(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

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

    QGROUNDCONTROL 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Main executable
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QtGui/QApplication>
#include "QGCCore.h"
#include "MainWindow.h"
#include "configuration.h"
#include "SerialLink.h"
#include "TCPLink.h"
#ifdef QT_DEBUG
#include "AutoTest.h"
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif

/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif

#ifdef Q_OS_WIN

/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler( QtMsgType type, const char* msg )
{
    const char symbols[] = { 'I', 'E', '!', 'X' };
    QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg );
    std::cerr << output.toStdString() << std::endl;
    if( type == QtFatalMsg ) abort();
}

/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
    Q_UNUSED(reportType);

    std::cerr << message << std::endl;  // Output message to stderr
    *returnValue = 0;                   // Don't break into debugger
    return true;                        // We handled this fully ourselves
}

#endif

/**
 * @brief Starts the application
 *
 * @param argc Number of commandline arguments
 * @param argv Commandline arguments
 * @return exit code, 0 for normal exit and !=0 for error cases
 */

int main(int argc, char *argv[])
{
// install the message handler
#ifdef Q_OS_WIN
    qInstallMsgHandler( msgHandler );
#endif

    // The following calls to qRegisterMetaType are done to silence debug output which warns
    // that we use these types in signals, and without calling qRegisterMetaType we can't queue
    // these signals. In general we don't queue these signals, but we do what the warning says
    // anyway to silence the debug output.
    qRegisterMetaType<QSerialPort::SerialPortError>();
    qRegisterMetaType<QAbstractSocket::SocketError>();

#ifdef QT_DEBUG
    // We parse a small set of command line options here prior to QGCCore in order to handle the ones
    // which need to be handled before a QApplication object is started.

    bool runUnitTests = false;          // Run unit test
    bool quietWindowsAsserts = false;   // Don't let asserts pop dialog boxes

    CmdLineOpt_t rgCmdLineOptions[] = {
        { "--unittest",             &runUnitTests },
        { "--no-windows-assert-ui", &quietWindowsAsserts },
        // Add additional command line option flags here
    };

    ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), true);

    if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
        _CrtSetReportHook(WindowsCrtReportHook);
#endif
    }

    if (runUnitTests) {
        // Run the test
        int failures = AutoTest::run(argc-1, argv);
        if (failures == 0)
        {
            qDebug() << "ALL TESTS PASSED";
        }
        else
        {
            qDebug() << failures << " TESTS FAILED!";
        }
        return failures;
    }
#endif

    QGCCore* core = NULL;
    int val;
    bool firstStart = true;

    do {
        if (core) {
            delete core;
            firstStart = false;
        }
        core = new QGCCore(firstStart, argc, argv);
        val = core->exec();
    } while (core->getRestartRequested());

    return val;
}
<commit_msg>Tell MacOS to not push us to nap<commit_after>/*=====================================================================

QGroundControl Open Source Ground Control Station

(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

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

    QGROUNDCONTROL 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Main executable
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QtGui/QApplication>
#include "QGCCore.h"
#include "MainWindow.h"
#include "configuration.h"
#include "SerialLink.h"
#include "TCPLink.h"
#ifdef QT_DEBUG
#include "AutoTest.h"
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif

/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif

#ifdef Q_OS_WIN

/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler( QtMsgType type, const char* msg )
{
    const char symbols[] = { 'I', 'E', '!', 'X' };
    QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg );
    std::cerr << output.toStdString() << std::endl;
    if( type == QtFatalMsg ) abort();
}

/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
    Q_UNUSED(reportType);

    std::cerr << message << std::endl;  // Output message to stderr
    *returnValue = 0;                   // Don't break into debugger
    return true;                        // We handled this fully ourselves
}

#endif

/**
 * @brief Starts the application
 *
 * @param argc Number of commandline arguments
 * @param argv Commandline arguments
 * @return exit code, 0 for normal exit and !=0 for error cases
 */

int main(int argc, char *argv[])
{

    // Prevent Apple's app nap from screwing us over
    // tip: the domain can be cross-checked on the command line with <defaults domains>
    QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES");

    // install the message handler
#ifdef Q_OS_WIN
    qInstallMsgHandler( msgHandler );
#endif

    // The following calls to qRegisterMetaType are done to silence debug output which warns
    // that we use these types in signals, and without calling qRegisterMetaType we can't queue
    // these signals. In general we don't queue these signals, but we do what the warning says
    // anyway to silence the debug output.
    qRegisterMetaType<QSerialPort::SerialPortError>();
    qRegisterMetaType<QAbstractSocket::SocketError>();

#ifdef QT_DEBUG
    // We parse a small set of command line options here prior to QGCCore in order to handle the ones
    // which need to be handled before a QApplication object is started.

    bool runUnitTests = false;          // Run unit test
    bool quietWindowsAsserts = false;   // Don't let asserts pop dialog boxes

    CmdLineOpt_t rgCmdLineOptions[] = {
        { "--unittest",             &runUnitTests },
        { "--no-windows-assert-ui", &quietWindowsAsserts },
        // Add additional command line option flags here
    };

    ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), true);

    if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
        _CrtSetReportHook(WindowsCrtReportHook);
#endif
    }

    if (runUnitTests) {
        // Run the test
        int failures = AutoTest::run(argc-1, argv);
        if (failures == 0)
        {
            qDebug() << "ALL TESTS PASSED";
        }
        else
        {
            qDebug() << failures << " TESTS FAILED!";
        }
        return failures;
    }
#endif

    QGCCore* core = NULL;
    int val;
    bool firstStart = true;

    do {
        if (core) {
            delete core;
            firstStart = false;
        }
        core = new QGCCore(firstStart, argc, argv);
        val = core->exec();
    } while (core->getRestartRequested());

    return val;
}
<|endoftext|>


<commit_before>#include <iostream>

#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <llvm/Support/CommandLine.h>

#include "DetectSkeletonsAction.hh"
#include "DetectDynamicAction.hh"
#include "AnnotateSkeletonsAction.hh"
#include "Log.hh"

using namespace llvm;
using namespace clang;
using namespace clang::tooling;
using std::string;

enum ProgramMode {
  Static,
  FindReorderable
};

static cl::OptionCategory OptionsCategory("skel options");
static cl::opt<bool> Overwrite("overwrite", cl::desc("Overwrite source files"),
                               cl::cat(OptionsCategory));
static cl::alias OverwriteA("w", cl::desc("Alias for -overwrite"), cl::aliasopt(Overwrite));

static cl::opt<ProgramMode> Mode(cl::desc("choose application mode"),
    cl::values(
      clEnumVal(Static, "Statically analyse the program"),
      clEnumVal(FindReorderable, "Dynamically find reorderable loops"),
      nullptr
    ), cl::cat(OptionsCategory), cl::Required);

int main(int argc, const char **argv) {
  CommonOptionsParser op(argc, argv, OptionsCategory);
  ClangTool Tool(op.getCompilations(), op.getSourcePathList());

  if(Mode == Static) {
    if(Overwrite) {
      return Tool.run(
          newFrontendActionFactory<AnnotateSkeletonsAction>().get());
    } else {
      return Tool.run(
          newFrontendActionFactory<DetectSkeletonsAction>().get());
    }
  }

  return Tool.run(newFrontendActionFactory<DetectDynamicAction>().get());
}
<commit_msg>Add strategy flags to command line<commit_after>#include <iostream>

#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <llvm/Support/CommandLine.h>

#include "AnnotateSkeletonsAction.hh"
#include "DetectSkeletonsAction.hh"
#include "DetectDynamicAction.hh"
#include "Log.hh"
#include "LoopReorderer.hh"

using namespace llvm;
using namespace clang;
using namespace clang::tooling;
using std::string;

enum ProgramMode {
  Static,
  FindReorderable
};

static cl::OptionCategory OptionsCategory("skel options");
static cl::opt<bool> Overwrite("overwrite", cl::desc("Overwrite source files"),
                               cl::cat(OptionsCategory));
static cl::alias OverwriteA("w", cl::desc("Alias for -overwrite"), cl::aliasopt(Overwrite));

static cl::opt<ProgramMode> Mode(cl::desc("Application mode"),
    cl::values(
      clEnumValN(Static, "static", "Statically analyse the program"),
      clEnumValN(FindReorderable, "reorder", "Dynamically find reorderable loops"),
      nullptr
    ), cl::cat(OptionsCategory), cl::Required);

static cl::opt<Strategy::Type> StrategyMode(cl::desc("Reordering strategy"),
    cl::values(
      clEnumValN(Strategy::Reverse, "reverse", "Reverse the order of loop iteration"),
      nullptr
    ), cl::cat(OptionsCategory), cl::Required);

int main(int argc, const char **argv) {
  CommonOptionsParser op(argc, argv, OptionsCategory);
  ClangTool Tool(op.getCompilations(), op.getSourcePathList());

  if(Mode == Static) {
    if(Overwrite) {
      return Tool.run(
          newFrontendActionFactory<AnnotateSkeletonsAction>().get());
    } else {
      return Tool.run(
          newFrontendActionFactory<DetectSkeletonsAction>().get());
    }
  }

  return Tool.run(newFrontendActionFactory<DetectDynamicAction>().get());
}
<|endoftext|>


<commit_before>// Copyright 2014 Ryuichi Ueda
// Released under the MIT License.
#include <iostream>
#include "Feeder.h"
#include "Environment.h"
#include "Script.h"
#include <fstream>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
using namespace std;

int scriptPos(int argc, char const* argv[]);
bool setFlags(int argc, char const* argv[],Environment *e);

static void sig_int(int sig)
{
	Element::m_signal = sig;
}

static void sig_hup(int sig)
{
	Element::m_signal = sig;
}

static void sig_term(int sig)
{
	Element::m_signal = sig;
}

int main(int argc, char const* argv[])
{
	if(setpgid(0,0) != 0)
		exit(1);

	if(argc <= 1)
		exit(0);

///////////////////////////////////////////
// set signals
//////////////////////////////////////////
	struct sigaction sig;
	memset(&sig,'\0',sizeof(sig));

	sig.sa_handler = sig_int;
	sigaction(SIGINT,&sig,NULL);
	sig.sa_handler = sig_hup;
	sigaction(SIGHUP,&sig,NULL);
	sig.sa_handler = sig_term;
	sigaction(SIGTERM,&sig,NULL);

///////////////////////////////////////////
// initialization of top level objects
//////////////////////////////////////////
	int script_pos = scriptPos(argc,argv);

	ifstream ifs(argv[script_pos]);
	Feeder feeder(&ifs);
	Environment env(argc,argv,script_pos);

	if(!setFlags(argc,argv,&env))
		exit(1);//flags are invalid.

	// set tmpdir
	string tmp_k = "tmpdir";
	string tmp_v = "/tmp/";
	env.setImportPath(&tmp_k,&tmp_v);
	Script s(&feeder,&env,NULL);

//////////////////////////////////////////
//execution
//////////////////////////////////////////
	s.parse();
	s.exec(NULL,NULL,NULL);
	//do not write something here because
	//a subshell cannot execute this part.
}

int scriptPos(int argc, char const* argv[])
{
	string com = string(argv[0]);
	bool shebang = com.substr(com.find_last_of('/') + 1) != "glue";

	if(shebang)
		return 0;

	int i=1;
	for(;i<argc;i++){
		if(argv[i][0] != '-')
			break;
	}
	return i;
}

void usage(void)
{
	cerr << "GlueLang (master branch)" << endl;
	cerr << "Usage: glue [OPTION] [FILE]" << endl;
	cerr << endl;
	cerr << "Copyright (C) 2015 Ryuichi Ueda" << endl;
	cerr << "GlueLang repo. <https://github.com/ryuichiueda/GlueLang>" << endl;
}

bool setFlags(int argc, char const* argv[],Environment *e)
{
	struct option long_opts[] = {
		{"help",0,NULL,'h'},
		{"usage",0,NULL,'h'},
		{"verbose",0,NULL,'v'},
		{0,0,0,0}
	};

	int opt = 0;
	int idx = 0;
	while((opt = getopt_long(argc,(char *const *)argv,"hv",long_opts,&idx)) != -1){
		switch (opt){
		case 'h':
			usage();
			return false;
		case 'v':
			e->m_v_opt = true;
			break;
		}
	}
	return true;
}
<commit_msg>Change detail<commit_after>// Copyright 2014 Ryuichi Ueda
// Released under the MIT License.
#include <iostream>
#include "Feeder.h"
#include "Environment.h"
#include "Script.h"
#include <fstream>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
using namespace std;

void usage(void);
int scriptPos(int argc, char const* argv[]);
bool setFlags(int argc, char const* argv[],Environment *e);

static void sig_int(int sig)
{
	Element::m_signal = sig;
}

static void sig_hup(int sig)
{
	Element::m_signal = sig;
}

static void sig_term(int sig)
{
	Element::m_signal = sig;
}

int main(int argc, char const* argv[])
{
	if(setpgid(0,0) != 0)
		exit(1);

	if(argc <= 1)
		usage();

///////////////////////////////////////////
// set signals
//////////////////////////////////////////
	struct sigaction sig;
	memset(&sig,'\0',sizeof(sig));

	sig.sa_handler = sig_int;
	sigaction(SIGINT,&sig,NULL);
	sig.sa_handler = sig_hup;
	sigaction(SIGHUP,&sig,NULL);
	sig.sa_handler = sig_term;
	sigaction(SIGTERM,&sig,NULL);

///////////////////////////////////////////
// initialization of top level objects
//////////////////////////////////////////
	int script_pos = scriptPos(argc,argv);

	ifstream ifs(argv[script_pos]);
	Environment env(argc,argv,script_pos);

	if(!setFlags(argc,argv,&env))
		exit(1);//flags are invalid.

	// create the feeder
	Feeder feeder(&ifs);
	// set tmpdir
	string tmp_k = "tmpdir";
	string tmp_v = "/tmp/";
	env.setImportPath(&tmp_k,&tmp_v);
	Script s(&feeder,&env,NULL);

//////////////////////////////////////////
//execution
//////////////////////////////////////////
	s.parse();
	s.exec(NULL,NULL,NULL);
	//do not write something here because
	//a subshell cannot execute this part.
}

int scriptPos(int argc, char const* argv[])
{
	string com = string(argv[0]);
	bool shebang = com.substr(com.find_last_of('/') + 1) != "glue";

	if(shebang)
		return 0;

	int i=1;
	for(;i<argc;i++){
		if(argv[i][0] != '-')
			break;
	}
	return i;
}

void version(void)
{
	cerr << "GlueLang v0.1.1 🍣 🍺\n\n"
	     << "Copyright (C) 2017 Ryuichi Ueda\n"
	     << "Released under the MIT License.\n"
	     << "https://github.com/ryuichiueda/GlueLang" << endl;
	exit(1);
}

void usage(void)
{
	cerr << "Usage: glue [OPTION] [FILE]" << endl;
	exit(1);
}

bool setFlags(int argc, char const* argv[],Environment *e)
{
	struct option long_opts[] = {
		{"help",0,NULL,'h'},
		{"usage",0,NULL,'u'},
		{"version",0,NULL,'h'},
		{"verbose",0,NULL,'v'},
		{0,0,0,0}
	};

	int opt = 0;
	int idx = 0;
	while((opt = getopt_long(argc,(char *const *)argv,"uhv",long_opts,&idx)) != -1){
		switch (opt){
		case 'u':
			usage();
		case 'h':
			version();
		case 'v':
			e->m_v_opt = true;
			break;
		}
	}
	return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.

#include <string.h>

#include "rescle.h"

bool print_error(const char* message) {
  fprintf(stderr, "Fatal error: %s\n", message);
  return 1;
}

bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) {
  *v1 = *v2 = *v3 = *v4 = 0;
  if (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4)
    return true;
  if (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3)
    return true;
  if (swscanf_s(str, L"%hu.%hu", v1, v2) == 2)
    return true;
  if (swscanf_s(str, L"%hu", v1) == 1)
    return true;

  return false;
}

int wmain(int argc, const wchar_t* argv[]) {
  bool loaded = false;
  rescle::ResourceUpdater updater;

  for (int i = 1; i < argc; ++i) {
    if (wcscmp(argv[i], L"--set-version-string") == 0 ||
        wcscmp(argv[i], L"-svs") == 0) {
      if (argc - i < 3)
        return print_error("--set-version-string requires 'Key' and 'Value'");

      const wchar_t* key = argv[++i];
      const wchar_t* value = argv[++i];
      if (!updater.SetVersionString(key, value))
        return print_error("Unable to change version string");

    } else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
               wcscmp(argv[i], L"-sfv") == 0) {
      if (argc - i < 2)
        return print_error("--set-file-version requires a version string");

      unsigned short v1, v2, v3, v4;
      if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
        return print_error("Unable to parse version string for FileVersion");

      if (!updater.SetFileVersion(v1, v2, v3, v4))
        return print_error("Unable to change file version");

      if (!updater.SetVersionString(L"FileVersion", argv[i]))
        return print_error("Unable to change FileVersion string");

    } else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
               wcscmp(argv[i], L"-spv") == 0) {
      if (argc - i < 2)
        return print_error("--set-product-version requires a version string");

      unsigned short v1, v2, v3, v4;
      if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
        return print_error("Unable to parse version string for ProductVersion");

      if (!updater.SetProductVersion(v1, v2, v3, v4))
        return print_error("Unable to change product version");

      if (!updater.SetVersionString(L"ProductVersion", argv[i]))
        return print_error("Unable to change ProductVersion string");

    } else if (wcscmp(argv[i], L"--set-icon") == 0 ||
               wcscmp(argv[i], L"-si") == 0) {
      if (argc - i < 2)
        return print_error("--set-icon requires path to the icon");

      if (!updater.SetIcon(argv[++i]))
        return print_error("Unable to set icon");
    }
    else if (wcscmp(argv[i], L"--set-requested-executation-level") == 0 ||
      wcscmp(argv[i], L"-sel") == 0) {
      if (argc - i < 2)
        return print_error("--set-requested-executation-level requires user, requireAdministrator or asInvoker");

      if (!updater.SetExecutionLevel(argv[++i]))
        return print_error("Unable to set execution level");

    } else if (wcscmp(argv[i], L"--set-resource-string") == 0 ||
      wcscmp(argv[i], L"--srs") == 0) {
      if (argc - i < 3)
        return print_error("--set-resource-string requires int 'Key' and string 'Value'");

      const wchar_t* key = argv[++i];
      unsigned int key_id = 0;
      if (swscanf_s(key, L"%d", &key_id) != 1)
        return print_error("Unable to parse id");

      const wchar_t* value = argv[++i];
      if (!updater.ChangeString(key_id, value))
        return print_error("Unable to change string");
    } else {
      if (loaded)
        return print_error("Unexpected trailing arguments");

      loaded = true;
      if (!updater.Load(argv[i]))
        return print_error("Unable to load file");

    }
  }

  if (!loaded)
    return print_error("You should specify a exe/dll file");

  if (!updater.Commit())
    return print_error("Unable to commit changes");

  return 0;
}
<commit_msg>Fix spelling of execution<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.

#include <string.h>

#include "rescle.h"

bool print_error(const char* message) {
  fprintf(stderr, "Fatal error: %s\n", message);
  return 1;
}

bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) {
  *v1 = *v2 = *v3 = *v4 = 0;
  if (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4)
    return true;
  if (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3)
    return true;
  if (swscanf_s(str, L"%hu.%hu", v1, v2) == 2)
    return true;
  if (swscanf_s(str, L"%hu", v1) == 1)
    return true;

  return false;
}

int wmain(int argc, const wchar_t* argv[]) {
  bool loaded = false;
  rescle::ResourceUpdater updater;

  for (int i = 1; i < argc; ++i) {
    if (wcscmp(argv[i], L"--set-version-string") == 0 ||
        wcscmp(argv[i], L"-svs") == 0) {
      if (argc - i < 3)
        return print_error("--set-version-string requires 'Key' and 'Value'");

      const wchar_t* key = argv[++i];
      const wchar_t* value = argv[++i];
      if (!updater.SetVersionString(key, value))
        return print_error("Unable to change version string");

    } else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
               wcscmp(argv[i], L"-sfv") == 0) {
      if (argc - i < 2)
        return print_error("--set-file-version requires a version string");

      unsigned short v1, v2, v3, v4;
      if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
        return print_error("Unable to parse version string for FileVersion");

      if (!updater.SetFileVersion(v1, v2, v3, v4))
        return print_error("Unable to change file version");

      if (!updater.SetVersionString(L"FileVersion", argv[i]))
        return print_error("Unable to change FileVersion string");

    } else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
               wcscmp(argv[i], L"-spv") == 0) {
      if (argc - i < 2)
        return print_error("--set-product-version requires a version string");

      unsigned short v1, v2, v3, v4;
      if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
        return print_error("Unable to parse version string for ProductVersion");

      if (!updater.SetProductVersion(v1, v2, v3, v4))
        return print_error("Unable to change product version");

      if (!updater.SetVersionString(L"ProductVersion", argv[i]))
        return print_error("Unable to change ProductVersion string");

    } else if (wcscmp(argv[i], L"--set-icon") == 0 ||
               wcscmp(argv[i], L"-si") == 0) {
      if (argc - i < 2)
        return print_error("--set-icon requires path to the icon");

      if (!updater.SetIcon(argv[++i]))
        return print_error("Unable to set icon");
    } else if (wcscmp(argv[i], L"--set-requested-execution-level") == 0 ||
      wcscmp(argv[i], L"-sel") == 0) {
      if (argc - i < 2)
        return print_error("--set-requested-execution-level requires user, requireAdministrator or asInvoker");

      if (!updater.SetExecutionLevel(argv[++i]))
        return print_error("Unable to set execution level");

    } else if (wcscmp(argv[i], L"--set-resource-string") == 0 ||
      wcscmp(argv[i], L"--srs") == 0) {
      if (argc - i < 3)
        return print_error("--set-resource-string requires int 'Key' and string 'Value'");

      const wchar_t* key = argv[++i];
      unsigned int key_id = 0;
      if (swscanf_s(key, L"%d", &key_id) != 1)
        return print_error("Unable to parse id");

      const wchar_t* value = argv[++i];
      if (!updater.ChangeString(key_id, value))
        return print_error("Unable to change string");
    } else {
      if (loaded)
        return print_error("Unexpected trailing arguments");

      loaded = true;
      if (!updater.Load(argv[i]))
        return print_error("Unable to load file");

    }
  }

  if (!loaded)
    return print_error("You should specify a exe/dll file");

  if (!updater.Commit())
    return print_error("Unable to commit changes");

  return 0;
}
<|endoftext|>


<commit_before>// @(#)root/graf:$Name:  $:$Id: TCutG.cxx,v 1.11 2002/03/15 22:11:47 brun Exp $
// Author: Rene Brun   16/05/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TCutG                                                                //
//                                                                      //
//  A Graphical cut.                                                    //
//  A TCutG object defines a closed polygon in a x,y plot.              //
//  It can be created via the graphics editor option "CutG"             //
//  or directly by invoking its constructor.                            //
//  To create a TCutG via the graphics editor, use the left button      //
//  to select the points building the contour of the cut. Click on      //
//  the right button to close the TCutG.                                //
//  When it is created via the graphics editor, the TCutG object        //
//  is named "CUTG". It is recommended to immediatly change the name    //
//  by using the context menu item "SetName".                           //                                                                      //
//   When the graphics editor is used, the names of the variables X,Y   //
//   are automatically taken from the current pad title.                //
//  Example:                                                            //
//  Assume a TTree object T and:                                        //
//     Root > T.Draw("abs(fMomemtum)%fEtot")                            //
//  the TCutG members fVarX, fVary will be set to:                      //
//     fVarx = fEtot                                                    //
//     fVary = abs(fMomemtum)                                           //
//                                                                      //
//  A graphical cut can be used in a TTree selection expression:        //
//    Root > T.Draw("fEtot","cutg1")                                    //
//    where "cutg1" is the name of an existing graphical cut.           //
//                                                                      //
//  Note that, as shown in the example above, a graphical cut may be    //
//  used in a selection expression when drawing TTrees expressions      //
//  of 1-d, 2-d or 3-dimensions.                                        //
//  The expressions used in TTree::Draw can reference the variables     //
//  in the fVarX, fVarY of the graphical cut plus other variables.      //
//                                                                      //
//  When the TCutG object is created, it is added to the list of special//
//  objects in the main TROOT object pointed by gROOT. To retrieve a    //
//  pointer to this object from the code or command line, do:           //
//      TCutG *mycutg;                                                  //
//      mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") //
//      mycutg->SetName("mycutg");                                      //
//                                                                      //
//  Example of use of a TCutG in TTree::Draw:                           //
//       tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1")                  //
//                                                                      //
//  A Graphical cut may be drawn via TGraph::Draw.                      //
//  It can be edited like a normal TGraph.                              //
//                                                                      //
//  A Graphical cut may be saved to a file via TCutG::Write.            //                                                                     //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include <string.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TCutG.h"
#include "TVirtualPad.h"
#include "TPaveText.h"

ClassImp(TCutG)

//______________________________________________________________________________
TCutG::TCutG() : TGraph()
{

   fObjectX  = 0;
   fObjectY  = 0;
   gROOT->GetListOfSpecials()->Add(this);
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n)
      :TGraph(n)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y)
      :TGraph(n,x,y)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y)
      :TGraph(n,x,y)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::~TCutG()
{

   delete fObjectX;
   delete fObjectY;
   gROOT->GetListOfSpecials()->Remove(this);
}

//______________________________________________________________________________
Int_t TCutG::IsInside(Double_t x, Double_t y) const
{
//*.         Function which returns 1 if point x,y lies inside the
//*.              polygon defined by the graph points
//*.                                0 otherwise
//*.
//*.     The loop is executed with the end-point coordinates of a
//*.     line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a
//*.     horizontal line.
//*.     The counter inter is incremented if the line (X1,Y1)-(X2,Y2)
//*.     intersects the horizontal line.
//*.     In this case XINT is set to the X-coordinate of the
//*.     intersection point.
//*.     If inter is an odd number, then the point x,y is within
//*.     the polygon.
//*.
//*.         This routine is based on an original algorithm
//*.         developed by R.Nierhaus.
//*.

   Double_t xint;
   Int_t i;
   Int_t inter = 0;
   for (i=0;i<fNpoints-1;i++) {
      if (fY[i] == fY[i+1]) continue;
      if (y <= fY[i] && y <= fY[i+1]) continue;
      if (fY[i] < y && fY[i+1] < y) continue;
      xint = fX[i] + (y-fY[i])*(fX[i+1]-fX[i])/(fY[i+1]-fY[i]);
      if (x < xint) inter++;
   }
   if (inter%2) return 1;
   return 0;
}

//______________________________________________________________________________
void TCutG::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save primitive as a C++ statement(s) on output stream out

   char quote = '"';
   out<<"   "<<endl;
   if (gROOT->ClassSaved(TCutG::Class())) {
       out<<"   ";
   } else {
       out<<"   TCutG *";
   }
   out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl;
   out<<"   cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl;
   out<<"   cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl;
   out<<"   cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl;

   SaveFillAttributes(out,"cutg",0,1001);
   SaveLineAttributes(out,"cutg",1,1,1);
   SaveMarkerAttributes(out,"cutg",1,1,1);

   for (Int_t i=0;i<fNpoints;i++) {
      out<<"   cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
   }
   out<<"   cutg->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
void TCutG::SetVarX(const char *varx)
{
   fVarX = varx;
   delete fObjectX;
   fObjectX = 0;
}

//______________________________________________________________________________
void TCutG::SetVarY(const char *vary)
{
   fVarY = vary;
   delete fObjectY;
   fObjectY = 0;
}

//______________________________________________________________________________
void TCutG::Streamer(TBuffer &R__b)
{
   // Stream an object of class TCutG.

   if (R__b.IsReading()) {
      TCutG::Class()->ReadBuffer(R__b, this);
      gROOT->GetListOfSpecials()->Add(this);
   } else {
      TCutG::Class()->WriteBuffer(R__b, this);
   }
}
<commit_msg>In TCutG default constructor, do not add the cut to the list of specials. When reading from a file, the cut is added in Streamer.<commit_after>// @(#)root/graf:$Name:  $:$Id: TCutG.cxx,v 1.12 2002/03/26 07:05:57 brun Exp $
// Author: Rene Brun   16/05/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TCutG                                                                //
//                                                                      //
//  A Graphical cut.                                                    //
//  A TCutG object defines a closed polygon in a x,y plot.              //
//  It can be created via the graphics editor option "CutG"             //
//  or directly by invoking its constructor.                            //
//  To create a TCutG via the graphics editor, use the left button      //
//  to select the points building the contour of the cut. Click on      //
//  the right button to close the TCutG.                                //
//  When it is created via the graphics editor, the TCutG object        //
//  is named "CUTG". It is recommended to immediatly change the name    //
//  by using the context menu item "SetName".                           //                                                                      //
//   When the graphics editor is used, the names of the variables X,Y   //
//   are automatically taken from the current pad title.                //
//  Example:                                                            //
//  Assume a TTree object T and:                                        //
//     Root > T.Draw("abs(fMomemtum)%fEtot")                            //
//  the TCutG members fVarX, fVary will be set to:                      //
//     fVarx = fEtot                                                    //
//     fVary = abs(fMomemtum)                                           //
//                                                                      //
//  A graphical cut can be used in a TTree selection expression:        //
//    Root > T.Draw("fEtot","cutg1")                                    //
//    where "cutg1" is the name of an existing graphical cut.           //
//                                                                      //
//  Note that, as shown in the example above, a graphical cut may be    //
//  used in a selection expression when drawing TTrees expressions      //
//  of 1-d, 2-d or 3-dimensions.                                        //
//  The expressions used in TTree::Draw can reference the variables     //
//  in the fVarX, fVarY of the graphical cut plus other variables.      //
//                                                                      //
//  When the TCutG object is created, it is added to the list of special//
//  objects in the main TROOT object pointed by gROOT. To retrieve a    //
//  pointer to this object from the code or command line, do:           //
//      TCutG *mycutg;                                                  //
//      mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") //
//      mycutg->SetName("mycutg");                                      //
//                                                                      //
//  Example of use of a TCutG in TTree::Draw:                           //
//       tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1")                  //
//                                                                      //
//  A Graphical cut may be drawn via TGraph::Draw.                      //
//  It can be edited like a normal TGraph.                              //
//                                                                      //
//  A Graphical cut may be saved to a file via TCutG::Write.            //                                                                     //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include <string.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TCutG.h"
#include "TVirtualPad.h"
#include "TPaveText.h"

ClassImp(TCutG)

//______________________________________________________________________________
TCutG::TCutG() : TGraph()
{

   fObjectX  = 0;
   fObjectY  = 0;
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n)
      :TGraph(n)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y)
      :TGraph(n,x,y)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y)
      :TGraph(n,x,y)
{
   fObjectX  = 0;
   fObjectY  = 0;
   SetName(name);
   delete gROOT->GetListOfSpecials()->FindObject(name);
   gROOT->GetListOfSpecials()->Add(this);

// Take name of cut variables from pad title if title contains ":"
   if (gPad) {
      TPaveText *ptitle = (TPaveText*)gPad->FindObject("title");
      if (!ptitle) return;
      TText *ttitle = ptitle->GetLineWith(":");
      if (!ttitle) ttitle = ptitle->GetLineWith("{");
      if (!ttitle) ttitle = ptitle->GetLine(0);
      if (!ttitle) return;
      const char *title = ttitle->GetTitle();
      Int_t nch = strlen(title);
      char *vars = new char[nch+1];
      strcpy(vars,title);
      char *col = strstr(vars,":");
      if (col) {
         *col = 0;
         col++;
         char *brak = strstr(col," {");
         if (brak) *brak = 0;
         fVarY = vars;
         fVarX = col;
      } else {
         char *brak = strstr(vars," {");
         if (brak) *brak = 0;
         fVarX = vars;
      }
      delete [] vars;
   }
}

//______________________________________________________________________________
TCutG::~TCutG()
{

   delete fObjectX;
   delete fObjectY;
   gROOT->GetListOfSpecials()->Remove(this);
}

//______________________________________________________________________________
Int_t TCutG::IsInside(Double_t x, Double_t y) const
{
//*.         Function which returns 1 if point x,y lies inside the
//*.              polygon defined by the graph points
//*.                                0 otherwise
//*.
//*.     The loop is executed with the end-point coordinates of a
//*.     line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a
//*.     horizontal line.
//*.     The counter inter is incremented if the line (X1,Y1)-(X2,Y2)
//*.     intersects the horizontal line.
//*.     In this case XINT is set to the X-coordinate of the
//*.     intersection point.
//*.     If inter is an odd number, then the point x,y is within
//*.     the polygon.
//*.
//*.         This routine is based on an original algorithm
//*.         developed by R.Nierhaus.
//*.

   Double_t xint;
   Int_t i;
   Int_t inter = 0;
   for (i=0;i<fNpoints-1;i++) {
      if (fY[i] == fY[i+1]) continue;
      if (y <= fY[i] && y <= fY[i+1]) continue;
      if (fY[i] < y && fY[i+1] < y) continue;
      xint = fX[i] + (y-fY[i])*(fX[i+1]-fX[i])/(fY[i+1]-fY[i]);
      if (x < xint) inter++;
   }
   if (inter%2) return 1;
   return 0;
}

//______________________________________________________________________________
void TCutG::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save primitive as a C++ statement(s) on output stream out

   char quote = '"';
   out<<"   "<<endl;
   if (gROOT->ClassSaved(TCutG::Class())) {
       out<<"   ";
   } else {
       out<<"   TCutG *";
   }
   out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl;
   out<<"   cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl;
   out<<"   cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl;
   out<<"   cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl;

   SaveFillAttributes(out,"cutg",0,1001);
   SaveLineAttributes(out,"cutg",1,1,1);
   SaveMarkerAttributes(out,"cutg",1,1,1);

   for (Int_t i=0;i<fNpoints;i++) {
      out<<"   cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
   }
   out<<"   cutg->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
void TCutG::SetVarX(const char *varx)
{
   fVarX = varx;
   delete fObjectX;
   fObjectX = 0;
}

//______________________________________________________________________________
void TCutG::SetVarY(const char *vary)
{
   fVarY = vary;
   delete fObjectY;
   fObjectY = 0;
}

//______________________________________________________________________________
void TCutG::Streamer(TBuffer &R__b)
{
   // Stream an object of class TCutG.

   if (R__b.IsReading()) {
      TCutG::Class()->ReadBuffer(R__b, this);
      gROOT->GetListOfSpecials()->Add(this);
   } else {
      TCutG::Class()->WriteBuffer(R__b, this);
   }
}
<|endoftext|>