<commit_before>#include "DisAsmVu.h"
#include "lexical_cast_ex.h"
#include "string_cast.h"
#include "../VuAnalysis.h"

#define ID_DISASM_ANALYSE		40100

CDisAsmVu::CDisAsmVu(HWND hParent, const RECT& rect, CVirtualMachine& virtualMachine, CMIPS* ctx)
: CDisAsm(hParent, rect, virtualMachine, ctx)
{
	m_instructionSize = 8;
}

CDisAsmVu::~CDisAsmVu()
{

}

long CDisAsmVu::OnCommand(unsigned short id, unsigned short msg, HWND hwndFrom)
{
	if(id == ID_DISASM_ANALYSE)
	{
		CVuAnalysis::Analyse(m_ctx, 0, 0x4000);
		Redraw();
		return TRUE;
	}
	return CDisAsm::OnCommand(id, msg, hwndFrom);
}

unsigned int CDisAsmVu::BuildContextMenu(HMENU menuHandle)
{
	unsigned int position = CDisAsm::BuildContextMenu(menuHandle);
	InsertMenu(menuHandle, position++, MF_BYPOSITION, ID_DISASM_ANALYSE, _T("Analyse Microprogram"));
	return position;
}

std::tstring CDisAsmVu::GetInstructionDetailsText(uint32 address)
{
	assert((address & 0x07) == 0);

	uint32 lowerInstruction = GetInstruction(address + 0);
	uint32 upperInstruction = GetInstruction(address + 4);

	std::tstring result;

	result += lexical_cast_hex<std::tstring>(address, 8) + _T("    ");
	result += lexical_cast_hex<std::tstring>(upperInstruction,  8) + _T(" ") + lexical_cast_hex<std::tstring>(lowerInstruction,  8) + _T("    ");

	char disasm[256];

	m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 4, upperInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 15; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 4, upperInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 31; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 0, lowerInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 16; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 0, lowerInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	return result;
}

unsigned int CDisAsmVu::GetMetadataPosition() const
{
	return m_renderMetrics.fontSizeX * 80;
}

void CDisAsmVu::DrawInstructionDetails(Framework::Win32::CDeviceContext& deviceContext, uint32 address, int y)
{
	assert((address & 0x07) == 0);

	uint32 lowerInstruction = GetInstruction(address + 0);
	uint32 upperInstruction = GetInstruction(address + 4);

	std::tstring instructionCode = lexical_cast_hex<std::tstring>(upperInstruction, 8) + _T(" ") + lexical_cast_hex<std::tstring>(lowerInstruction, 8);
	deviceContext.TextOut(m_renderMetrics.fontSizeX * 15, y, instructionCode.c_str());

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 4, upperInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 35, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 4, upperInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 42, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 0, lowerInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 66, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 0, lowerInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 73, y, string_cast<std::tstring>(disAsm).c_str());
	}
}
<commit_msg>Minor adjustments to text positions in DisAsmVu.<commit_after>#include "DisAsmVu.h"
#include "lexical_cast_ex.h"
#include "string_cast.h"
#include "../VuAnalysis.h"

#define ID_DISASM_ANALYSE		40100

CDisAsmVu::CDisAsmVu(HWND hParent, const RECT& rect, CVirtualMachine& virtualMachine, CMIPS* ctx)
: CDisAsm(hParent, rect, virtualMachine, ctx)
{
	m_instructionSize = 8;
}

CDisAsmVu::~CDisAsmVu()
{

}

long CDisAsmVu::OnCommand(unsigned short id, unsigned short msg, HWND hwndFrom)
{
	if(id == ID_DISASM_ANALYSE)
	{
		CVuAnalysis::Analyse(m_ctx, 0, 0x4000);
		Redraw();
		return TRUE;
	}
	return CDisAsm::OnCommand(id, msg, hwndFrom);
}

unsigned int CDisAsmVu::BuildContextMenu(HMENU menuHandle)
{
	unsigned int position = CDisAsm::BuildContextMenu(menuHandle);
	InsertMenu(menuHandle, position++, MF_BYPOSITION, ID_DISASM_ANALYSE, _T("Analyse Microprogram"));
	return position;
}

std::tstring CDisAsmVu::GetInstructionDetailsText(uint32 address)
{
	assert((address & 0x07) == 0);

	uint32 lowerInstruction = GetInstruction(address + 0);
	uint32 upperInstruction = GetInstruction(address + 4);

	std::tstring result;

	result += lexical_cast_hex<std::tstring>(address, 8) + _T("    ");
	result += lexical_cast_hex<std::tstring>(upperInstruction,  8) + _T(" ") + lexical_cast_hex<std::tstring>(lowerInstruction,  8) + _T("    ");

	char disasm[256];

	m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 4, upperInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 15; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 4, upperInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 31; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 0, lowerInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	for(size_t j = strlen(disasm); j < 16; j++)
	{
		result += _T(" ");
	}

	m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 0, lowerInstruction, disasm, countof(disasm));
	result += string_cast<std::tstring>(disasm);

	return result;
}

unsigned int CDisAsmVu::GetMetadataPosition() const
{
	return m_renderMetrics.fontSizeX * 80;
}

void CDisAsmVu::DrawInstructionDetails(Framework::Win32::CDeviceContext& deviceContext, uint32 address, int y)
{
	assert((address & 0x07) == 0);

	uint32 lowerInstruction = GetInstruction(address + 0);
	uint32 upperInstruction = GetInstruction(address + 4);

	std::tstring instructionCode = lexical_cast_hex<std::tstring>(upperInstruction, 8) + _T(" ") + lexical_cast_hex<std::tstring>(lowerInstruction, 8);
	deviceContext.TextOut(m_renderMetrics.fontSizeX * 15, y, instructionCode.c_str());

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 4, upperInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 35, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 4, upperInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 43, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionMnemonic(m_ctx, address + 0, lowerInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 71, y, string_cast<std::tstring>(disAsm).c_str());
	}

	{
		char disAsm[256];
		m_ctx->m_pArch->GetInstructionOperands(m_ctx, address + 0, lowerInstruction, disAsm, 256);
		deviceContext.TextOut(m_renderMetrics.fontSizeX * 79, y, string_cast<std::tstring>(disAsm).c_str());
	}
}
<|endoftext|>


<commit_before>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program 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, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Enable migration from Qt v3 to Qt v4
#define LSB_Q3FRAME
#define LSB_Q3GRIDLAYOUT

#include "ParameterDialog.h"
#include "SimpleParameter.h"
#include "SimpleParameterEdit.h"
#include "DeferredParameterEdit.h"

#include "ConfigFile.h"

#include "params/Type.h"
#include "params/Generator.h"

#include <qstring.h>
#include <q3hgroupbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qmessagebox.h>
#include <q3scrollview.h>
#include <qobject.h>
#ifdef LSB_Q3GRIDLAYOUT
#include <QGridLayout>
#else
//Added by qt3to4:
#include <Q3GridLayout>
#endif
#ifdef LSB_Q3FRAME
#include <QFrame>
#else
#include <Q3Frame>
#endif

#include <cassert>

ParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,
				 QDomNode const& _parentNode,
				 QDomNode const& _node,
				 ItemXML * _parentItem,
				 ItemXML * _item,
				 QWidget * _parent, const char * _name) :
  Super(_parentNode, _node, _parentItem, _item, _parent, _name),
  config_(ConfigFile::instance()),
  parameterType_(_parameterType),
  params_(config_->description().getFullParameterSet(parameterType_))
{
  assert(!_node.isNull());

  initDialog();

  QSize s = frame_->sizeHint();

  if (s.width() > 800 ||
      s.height() > 600) {

    delete frame_;
    Q3ScrollView * sv = new Q3ScrollView(groupBox_, "scrollview");
#ifdef LSB_Q3FRAME
    QWidget * const parent = sv->viewport();
    frame_ = new QFrame(parent);
#else
    frame_ = new Q3Frame(sv->viewport());
#endif
    sv->addChild(frame_);
    sv->setResizePolicy(Q3ScrollView::AutoOneFit);

    initDialog();

    frame_->sizeHint();
  }

  groupBox_->sizeHint(); // we seem to need this to get the right size (hutz)
  groupBox_->setTitle("Parameters");
}

void
ParameterDialog::setXML()
{
  setModified(false);
  EditVector::const_iterator first, last = editFelds_.end();
  for (first = editFelds_.begin(); first != last; ++first) {
    if ((*first)->modified()) {
      (*first)->setXML();
      setModified(true);
    }
  }
}

void
ParameterDialog::initDialog()
{
  editFelds_.clear();

#ifdef LSB_Q3GRIDLAYOUT
  QWidget * const pGridLayoutParent = frame_;
  QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);
  assert(gridLayout != 0);
  const int margin = 5;
  gridLayout->setContentsMargins(margin, margin, margin, margin);
#else
  Q3GridLayout * gridLayout =
    new Q3GridLayout(frame_, params_.size(), 3, 2, 5, "gridLayout");
#endif

  // add parameter structs:
  unsigned long i = 0;
  Miro::CFG::ParameterVector::const_iterator first, last = params_.end();
  for (first = params_.begin(); first != last; ++first, ++i) {

    // name
    QLabel * name = new QLabel(frame_);
    QString n = first->name_;
    n[0] = n[0].upper();
    name->setText(n);
    gridLayout->addWidget(name, i, 0);

    // search existing entry

    QDomNode parameterNode;
    if (!node_.isNull()) {
      parameterNode = node_.firstChild();
      while(!parameterNode.isNull()) {
	QDomElement e = parameterNode.toElement();
	if (!e.isNull() &&
	    e.attribute("name") == n)
	  break;
	parameterNode = parameterNode.nextSibling();
      }
    }

    // if there is an existing entry
    // and we know our listview,
    // get the corresponding listview item

    ItemXML * childItem = NULL;
    if (!parameterNode.isNull() &&
	item_ != NULL) {
      if (!item_->children().isEmpty()) {
	QObjectList childList = item_->children();
        QListIterator<QObject*> it(childList);
        QObject * c;
        while (it.hasNext()) {
          c = it.next();
	  childItem = dynamic_cast<ItemXML *>(c);
	  assert(childItem != NULL);

	  if (childItem->node().toElement().attribute("name") == n) {
	    break;
	  }
	  childItem = NULL;
	}
      }
    }

    // create the dialog

    ParameterEdit * value;
    SimpleParameter::Type editType =
      SimpleParameter::typeFromName(first->type_);
    if (editType != SimpleParameter::NONE) {
      value = new SimpleParameterEdit(editType,
				      *first,
				      node_,
				      parameterNode,
				      item_,
				      childItem,
				      frame_,
				      n.latin1());

      // add measure
      QLabel * measure = new QLabel(frame_);
      if (!first->measure_.isEmpty()) {
	measure->setText(first->measure_);
	QToolTip::add(measure, (first->type_ != "angle")? first->type_ : QString("double"));
      }
      else
	measure->setText(first->type_);
      gridLayout->addWidget(measure, i, 2);
    }
    else {
      DeferredParameterEdit::EditType deferredEditType =
	DeferredParameterEdit::editType(first->type_);

      value = new DeferredParameterEdit(deferredEditType,
					*first,
					node_,
					parameterNode,
					item_,
					childItem,
					frame_,
					n.latin1());
    }

    gridLayout->addWidget(value->editWidget(), i, 1);
    editFelds_.push_back(value);

  }
}
<commit_msg>Migrate Q3ScrollView to QScrollArea<commit_after>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program 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, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Enable migration from Qt v3 to Qt v4
#define LSB_Q3FRAME
#define LSB_Q3GRIDLAYOUT
#define LSB_Q3HGROUPBOX
#define LSB_Q3SCROLLVIEW

#include "ParameterDialog.h"
#include "SimpleParameter.h"
#include "SimpleParameterEdit.h"
#include "DeferredParameterEdit.h"

#include "ConfigFile.h"

#include "params/Type.h"
#include "params/Generator.h"

#include <qstring.h>
#ifdef LSB_Q3HGROUPBOX
#include <QGroupBox>
#else
#include <q3hgroupbox.h>
#endif
#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qmessagebox.h>
#ifdef LSB_Q3SCROLLVIEW
#include <QScrollArea>
#else
#include <q3scrollview.h>
#endif
#include <qobject.h>
#ifdef LSB_Q3GRIDLAYOUT
#include <QGridLayout>
#else
//Added by qt3to4:
#include <Q3GridLayout>
#endif
#ifdef LSB_Q3FRAME
#include <QFrame>
#else
#include <Q3Frame>
#endif

#include <cassert>

ParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,
				 QDomNode const& _parentNode,
				 QDomNode const& _node,
				 ItemXML * _parentItem,
				 ItemXML * _item,
				 QWidget * _parent, const char * _name) :
  Super(_parentNode, _node, _parentItem, _item, _parent, _name),
  config_(ConfigFile::instance()),
  parameterType_(_parameterType),
  params_(config_->description().getFullParameterSet(parameterType_))
{
  assert(!_node.isNull());

  initDialog();

  QSize s = frame_->sizeHint();

  if (s.width() > 800 ||
      s.height() > 600) {

    delete frame_;
#ifdef LSB_Q3SCROLLVIEW
    QWidget * const pScrollAreaParent = groupBox_;
    QScrollArea * const sv = new QScrollArea(pScrollAreaParent);
    assert(sv != NULL);
#else
    Q3ScrollView * sv = new Q3ScrollView(groupBox_, "scrollview");
#endif
#ifdef LSB_Q3FRAME
    QWidget * const parent = sv->viewport();
    frame_ = new QFrame(parent);
#else
    frame_ = new Q3Frame(sv->viewport());
#endif
#ifdef LSB_Q3SCROLLVIEW
    sv->setWidget(frame_);
    /// @todo What is the counterpart of setting the resize policy?
#else
    sv->addChild(frame_);
    sv->setResizePolicy(Q3ScrollView::AutoOneFit);
#endif

    initDialog();

    frame_->sizeHint();
  }

  groupBox_->sizeHint(); // we seem to need this to get the right size (hutz)
  groupBox_->setTitle("Parameters");
}

void
ParameterDialog::setXML()
{
  setModified(false);
  EditVector::const_iterator first, last = editFelds_.end();
  for (first = editFelds_.begin(); first != last; ++first) {
    if ((*first)->modified()) {
      (*first)->setXML();
      setModified(true);
    }
  }
}

void
ParameterDialog::initDialog()
{
  editFelds_.clear();

#ifdef LSB_Q3GRIDLAYOUT
  QWidget * const pGridLayoutParent = frame_;
  QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);
  assert(gridLayout != 0);
  const int margin = 5;
  gridLayout->setContentsMargins(margin, margin, margin, margin);
#else
  Q3GridLayout * gridLayout =
    new Q3GridLayout(frame_, params_.size(), 3, 2, 5, "gridLayout");
#endif

  // add parameter structs:
  unsigned long i = 0;
  Miro::CFG::ParameterVector::const_iterator first, last = params_.end();
  for (first = params_.begin(); first != last; ++first, ++i) {

    // name
    QLabel * name = new QLabel(frame_);
    QString n = first->name_;
    n[0] = n[0].upper();
    name->setText(n);
    gridLayout->addWidget(name, i, 0);

    // search existing entry

    QDomNode parameterNode;
    if (!node_.isNull()) {
      parameterNode = node_.firstChild();
      while(!parameterNode.isNull()) {
	QDomElement e = parameterNode.toElement();
	if (!e.isNull() &&
	    e.attribute("name") == n)
	  break;
	parameterNode = parameterNode.nextSibling();
      }
    }

    // if there is an existing entry
    // and we know our listview,
    // get the corresponding listview item

    ItemXML * childItem = NULL;
    if (!parameterNode.isNull() &&
	item_ != NULL) {
      if (!item_->children().isEmpty()) {
	QObjectList childList = item_->children();
        QListIterator<QObject*> it(childList);
        QObject * c;
        while (it.hasNext()) {
          c = it.next();
	  childItem = dynamic_cast<ItemXML *>(c);
	  assert(childItem != NULL);

	  if (childItem->node().toElement().attribute("name") == n) {
	    break;
	  }
	  childItem = NULL;
	}
      }
    }

    // create the dialog

    ParameterEdit * value;
    SimpleParameter::Type editType =
      SimpleParameter::typeFromName(first->type_);
    if (editType != SimpleParameter::NONE) {
      value = new SimpleParameterEdit(editType,
				      *first,
				      node_,
				      parameterNode,
				      item_,
				      childItem,
				      frame_,
				      n.latin1());

      // add measure
      QLabel * measure = new QLabel(frame_);
      if (!first->measure_.isEmpty()) {
	measure->setText(first->measure_);
	QToolTip::add(measure, (first->type_ != "angle")? first->type_ : QString("double"));
      }
      else
	measure->setText(first->type_);
      gridLayout->addWidget(measure, i, 2);
    }
    else {
      DeferredParameterEdit::EditType deferredEditType =
	DeferredParameterEdit::editType(first->type_);

      value = new DeferredParameterEdit(deferredEditType,
					*first,
					node_,
					parameterNode,
					item_,
					childItem,
					frame_,
					n.latin1());
    }

    gridLayout->addWidget(value->editWidget(), i, 1);
    editFelds_.push_back(value);

  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Hero.h>

namespace Hearthstonepp
{
Hero::Hero(Card& card) : Character(card)
{
    // Do nothing
}

Hero::~Hero()
{
    delete weapon;
}

Hero::Hero(const Hero& hero) : Character(hero)
{
    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }
}

Hero::Hero(Hero&& hero) noexcept : Character(hero)
{
    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }
}

Hero& Hero::operator=(const Hero& hero)
{
    if (this == &hero)
    {
        return *this;
    }

    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }

    return *this;
}

Hero& Hero::operator=(Hero&& hero) noexcept
{
    if (this == &hero)
    {
        return *this;
    }

    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }

    return *this;
}

Hero* Hero::Clone() const
{
    return new Hero(*this);
}

size_t Hero::GetAttack() const
{
    return weapon != nullptr ? m_attack + weapon->GetAttack() : m_attack;
}
}  // namespace Hearthstonepp<commit_msg>refactor: Pass 'hero' as rvalue ref using std::move<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Hero.h>

namespace Hearthstonepp
{
Hero::Hero(Card& card) : Character(card)
{
    // Do nothing
}

Hero::~Hero()
{
    delete weapon;
}

Hero::Hero(const Hero& hero) : Character(hero)
{
    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }
}

Hero::Hero(Hero&& hero) noexcept : Character(std::move(hero))
{
    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }
}

Hero& Hero::operator=(const Hero& hero)
{
    if (this == &hero)
    {
        return *this;
    }

    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }

    return *this;
}

Hero& Hero::operator=(Hero&& hero) noexcept
{
    if (this == &hero)
    {
        return *this;
    }

    delete weapon;

    if (hero.weapon != nullptr)
    {
        weapon = hero.weapon->Clone();
    }

    return *this;
}

Hero* Hero::Clone() const
{
    return new Hero(*this);
}

size_t Hero::GetAttack() const
{
    return weapon != nullptr ? m_attack + weapon->GetAttack() : m_attack;
}
}  // namespace Hearthstonepp<|endoftext|>


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

#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>

namespace graphene { namespace elasticsearch {
   using namespace chain;

//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ELASTICSEARCH_SPACE_ID
#define ELASTICSEARCH_SPACE_ID 6
#endif

namespace detail
{
    class elasticsearch_plugin_impl;
}

class elasticsearch_plugin : public graphene::app::plugin
{
   public:
      elasticsearch_plugin();
      virtual ~elasticsearch_plugin();

      std::string plugin_name()const override;
      std::string plugin_description()const override;
      virtual void plugin_set_program_options(
         boost::program_options::options_description& cli,
         boost::program_options::options_description& cfg) override;
      virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
      virtual void plugin_startup() override;

      friend class detail::elasticsearch_plugin_impl;
      std::unique_ptr<detail::elasticsearch_plugin_impl> my;
};

struct operation_visitor
{
   typedef void result_type;

   share_type fee_amount;
   asset_id_type fee_asset;

   asset_id_type transfer_asset_id;
   share_type transfer_amount;
   account_id_type transfer_from;
   account_id_type transfer_to;

   void operator()( const graphene::chain::transfer_operation& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;

      transfer_asset_id = o.amount.asset_id;
      transfer_amount = o.amount.amount;
      transfer_from = o.from;
      transfer_to = o.to;
   }

   object_id_type      fill_order_id;
   account_id_type     fill_account_id;
   asset_id_type       fill_pays_asset_id;
   share_type          fill_pays_amount;
   asset_id_type       fill_receives_asset_id;
   share_type          fill_receives_amount;
   double              fill_fill_price;
   bool                fill_is_maker;

   void operator()( const graphene::chain::fill_order_operation& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;

      fill_order_id = o.order_id;
      fill_account_id = o.account_id;
      fill_pays_asset_id = o.pays.asset_id;
      fill_pays_amount = o.pays.amount;
      fill_receives_asset_id = o.receives.asset_id;
      fill_receives_amount = o.receives.amount;
      fill_fill_price = o.fill_price.to_real();
      fill_is_maker = o.is_maker;
   }

   template<typename T>
   void operator()( const T& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;
   }
};

struct operation_history_struct {
   int trx_in_block;
   int op_in_trx;
   std::string operation_result;
   int virtual_op;
   std::string op;
   variant op_object;
};

struct block_struct {
   int block_num;
   fc::time_point_sec block_time;
   std::string trx_id;
};

struct fee_struct {
   asset_id_type asset;
   std::string asset_name;
   share_type amount;
   double amount_units;
};

struct transfer_struct {
   asset_id_type asset;
   std::string asset_name;
   share_type amount;
   double amount_units;
   account_id_type from;
   account_id_type to;
};

struct fill_struct {
   object_id_type order_id;
   account_id_type account_id;
   asset_id_type pays_asset_id;
   std::string pays_asset_name;
   share_type pays_amount;
   double pays_amount_units;
   asset_id_type receives_asset_id;
   std::string receives_asset_name;
   share_type receives_amount;
   double receives_amount_units;
   double fill_price;
   double fill_price_units;
   bool is_maker;
};

struct visitor_struct {
   fee_struct fee_data;
   transfer_struct transfer_data;
   fill_struct fill_data;
};

struct bulk_struct {
   account_transaction_history_object account_history;
   operation_history_struct operation_history;
   int operation_type;
   int operation_id_num;
   block_struct block_data;
   optional<visitor_struct> additional_data;
};

struct adaptor_struct {
   variant adapt(const variant_object& op)
   {
      fc::mutable_variant_object o(op);
      vector<string> keys_to_rename;
      for (auto i = o.begin(); i != o.end(); ++i)
      {
         auto& element = (*i).value();
         if (element.is_object())
         {
            const string& name = (*i).key();
            auto& vo = element.get_object();
            if (vo.contains(name.c_str()))
               keys_to_rename.emplace_back(name);
            element = adapt(vo);
         }
         else if (element.is_array())
            adapt(element.get_array());
      }
      for (const auto& i : keys_to_rename)
      {
         string new_name = i + "_";
         o[new_name] = variant(o[i]);
         o.erase(i);
      }

      if (o.find("memo") != o.end())
      {
         auto& memo = o["memo"];
         if (memo.is_string())
         {
            o["memo_"] = o["memo"];
            o.erase("memo");
         }
         else if (memo.is_object())
         {
            fc::mutable_variant_object tmp(memo.get_object());
            if (tmp.find("nonce") != tmp.end())
            {
               tmp["nonce"] = tmp["nonce"].as_string();
               o["memo"] = tmp;
            }
         }
      }
      if (o.find("new_parameters") != o.end())
      {
         auto& tmp = o["new_parameters"];
         if (tmp.is_object())
         {
            fc::mutable_variant_object tmp2(tmp.get_object());
            if (tmp2.find("current_fees") != tmp2.end())
            {
               tmp2.erase("current_fees");
               o["new_parameters"] = tmp2;
            }
         }
      }
      if (o.find("owner") != o.end() && o["owner"].is_string())
      {
         o["owner_"] = o["owner"].as_string();
         o.erase("owner");
      }
      if (o.find("proposed_ops") != o.end())
      {
         o["proposed_ops"] = fc::json::to_string(o["proposed_ops"]);
      }
      if (o.find("initializer") != o.end())
      {
         o["initializer"] = fc::json::to_string(o["initializer"]);
      }
      if (o.find("policy") != o.end())
      {
         o["policy"] = fc::json::to_string(o["policy"]);
      }

      variant v;
      fc::to_variant(o, v, FC_PACK_MAX_DEPTH);
      return v;
   }

   void adapt(fc::variants& v)
   {
      for (auto& array_element : v)
      {
         if (array_element.is_object())
            array_element = adapt(array_element.get_object());
         else if (array_element.is_array())
            adapt(array_element.get_array());
         else
            array_element = array_element.as_string();
      }
   }
};

} } //graphene::elasticsearch

FC_REFLECT( graphene::elasticsearch::operation_history_struct, (trx_in_block)(op_in_trx)(operation_result)(virtual_op)(op)(op_object) )
FC_REFLECT( graphene::elasticsearch::block_struct, (block_num)(block_time)(trx_id) )
FC_REFLECT( graphene::elasticsearch::fee_struct, (asset)(asset_name)(amount)(amount_units) )
FC_REFLECT( graphene::elasticsearch::transfer_struct, (asset)(asset_name)(amount)(amount_units)(from)(to) )
FC_REFLECT( graphene::elasticsearch::fill_struct, (order_id)(account_id)(pays_asset_id)(pays_asset_name)(pays_amount)(pays_amount_units)
                                                  (receives_asset_id)(receives_asset_name)(receives_amount)(receives_amount_units)(fill_price)
                                                  (fill_price_units)(is_maker))
FC_REFLECT( graphene::elasticsearch::visitor_struct, (fee_data)(transfer_data)(fill_data) )
FC_REFLECT( graphene::elasticsearch::bulk_struct, (account_history)(operation_history)(operation_type)(operation_id_num)(block_data)(additional_data) )
<commit_msg>add predicates to adaptor<commit_after>/*
 * Copyright (c) 2017 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#pragma once

#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>

namespace graphene { namespace elasticsearch {
   using namespace chain;

//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ELASTICSEARCH_SPACE_ID
#define ELASTICSEARCH_SPACE_ID 6
#endif

namespace detail
{
    class elasticsearch_plugin_impl;
}

class elasticsearch_plugin : public graphene::app::plugin
{
   public:
      elasticsearch_plugin();
      virtual ~elasticsearch_plugin();

      std::string plugin_name()const override;
      std::string plugin_description()const override;
      virtual void plugin_set_program_options(
         boost::program_options::options_description& cli,
         boost::program_options::options_description& cfg) override;
      virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
      virtual void plugin_startup() override;

      friend class detail::elasticsearch_plugin_impl;
      std::unique_ptr<detail::elasticsearch_plugin_impl> my;
};

struct operation_visitor
{
   typedef void result_type;

   share_type fee_amount;
   asset_id_type fee_asset;

   asset_id_type transfer_asset_id;
   share_type transfer_amount;
   account_id_type transfer_from;
   account_id_type transfer_to;

   void operator()( const graphene::chain::transfer_operation& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;

      transfer_asset_id = o.amount.asset_id;
      transfer_amount = o.amount.amount;
      transfer_from = o.from;
      transfer_to = o.to;
   }

   object_id_type      fill_order_id;
   account_id_type     fill_account_id;
   asset_id_type       fill_pays_asset_id;
   share_type          fill_pays_amount;
   asset_id_type       fill_receives_asset_id;
   share_type          fill_receives_amount;
   double              fill_fill_price;
   bool                fill_is_maker;

   void operator()( const graphene::chain::fill_order_operation& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;

      fill_order_id = o.order_id;
      fill_account_id = o.account_id;
      fill_pays_asset_id = o.pays.asset_id;
      fill_pays_amount = o.pays.amount;
      fill_receives_asset_id = o.receives.asset_id;
      fill_receives_amount = o.receives.amount;
      fill_fill_price = o.fill_price.to_real();
      fill_is_maker = o.is_maker;
   }

   template<typename T>
   void operator()( const T& o )
   {
      fee_asset = o.fee.asset_id;
      fee_amount = o.fee.amount;
   }
};

struct operation_history_struct {
   int trx_in_block;
   int op_in_trx;
   std::string operation_result;
   int virtual_op;
   std::string op;
   variant op_object;
};

struct block_struct {
   int block_num;
   fc::time_point_sec block_time;
   std::string trx_id;
};

struct fee_struct {
   asset_id_type asset;
   std::string asset_name;
   share_type amount;
   double amount_units;
};

struct transfer_struct {
   asset_id_type asset;
   std::string asset_name;
   share_type amount;
   double amount_units;
   account_id_type from;
   account_id_type to;
};

struct fill_struct {
   object_id_type order_id;
   account_id_type account_id;
   asset_id_type pays_asset_id;
   std::string pays_asset_name;
   share_type pays_amount;
   double pays_amount_units;
   asset_id_type receives_asset_id;
   std::string receives_asset_name;
   share_type receives_amount;
   double receives_amount_units;
   double fill_price;
   double fill_price_units;
   bool is_maker;
};

struct visitor_struct {
   fee_struct fee_data;
   transfer_struct transfer_data;
   fill_struct fill_data;
};

struct bulk_struct {
   account_transaction_history_object account_history;
   operation_history_struct operation_history;
   int operation_type;
   int operation_id_num;
   block_struct block_data;
   optional<visitor_struct> additional_data;
};

struct adaptor_struct {
   variant adapt(const variant_object& op)
   {
      fc::mutable_variant_object o(op);
      vector<string> keys_to_rename;
      for (auto i = o.begin(); i != o.end(); ++i)
      {
         auto& element = (*i).value();
         if (element.is_object())
         {
            const string& name = (*i).key();
            auto& vo = element.get_object();
            if (vo.contains(name.c_str()))
               keys_to_rename.emplace_back(name);
            element = adapt(vo);
         }
         else if (element.is_array())
            adapt(element.get_array());
      }
      for (const auto& i : keys_to_rename)
      {
         string new_name = i + "_";
         o[new_name] = variant(o[i]);
         o.erase(i);
      }

      if (o.find("memo") != o.end())
      {
         auto& memo = o["memo"];
         if (memo.is_string())
         {
            o["memo_"] = o["memo"];
            o.erase("memo");
         }
         else if (memo.is_object())
         {
            fc::mutable_variant_object tmp(memo.get_object());
            if (tmp.find("nonce") != tmp.end())
            {
               tmp["nonce"] = tmp["nonce"].as_string();
               o["memo"] = tmp;
            }
         }
      }
      if (o.find("new_parameters") != o.end())
      {
         auto& tmp = o["new_parameters"];
         if (tmp.is_object())
         {
            fc::mutable_variant_object tmp2(tmp.get_object());
            if (tmp2.find("current_fees") != tmp2.end())
            {
               tmp2.erase("current_fees");
               o["new_parameters"] = tmp2;
            }
         }
      }
      if (o.find("owner") != o.end() && o["owner"].is_string())
      {
         o["owner_"] = o["owner"].as_string();
         o.erase("owner");
      }
      if (o.find("proposed_ops") != o.end())
      {
         o["proposed_ops"] = fc::json::to_string(o["proposed_ops"]);
      }
      if (o.find("initializer") != o.end())
      {
         o["initializer"] = fc::json::to_string(o["initializer"]);
      }
      if (o.find("policy") != o.end())
      {
         o["policy"] = fc::json::to_string(o["policy"]);
      }
      if (o.find("predicates") != o.end())
      {
         o["predicates"] = fc::json::to_string(o["predicates"]);
      }

      variant v;
      fc::to_variant(o, v, FC_PACK_MAX_DEPTH);
      return v;
   }

   void adapt(fc::variants& v)
   {
      for (auto& array_element : v)
      {
         if (array_element.is_object())
            array_element = adapt(array_element.get_object());
         else if (array_element.is_array())
            adapt(array_element.get_array());
         else
            array_element = array_element.as_string();
      }
   }
};

} } //graphene::elasticsearch

FC_REFLECT( graphene::elasticsearch::operation_history_struct, (trx_in_block)(op_in_trx)(operation_result)(virtual_op)(op)(op_object) )
FC_REFLECT( graphene::elasticsearch::block_struct, (block_num)(block_time)(trx_id) )
FC_REFLECT( graphene::elasticsearch::fee_struct, (asset)(asset_name)(amount)(amount_units) )
FC_REFLECT( graphene::elasticsearch::transfer_struct, (asset)(asset_name)(amount)(amount_units)(from)(to) )
FC_REFLECT( graphene::elasticsearch::fill_struct, (order_id)(account_id)(pays_asset_id)(pays_asset_name)(pays_amount)(pays_amount_units)
                                                  (receives_asset_id)(receives_asset_name)(receives_amount)(receives_amount_units)(fill_price)
                                                  (fill_price_units)(is_maker))
FC_REFLECT( graphene::elasticsearch::visitor_struct, (fee_data)(transfer_data)(fill_data) )
FC_REFLECT( graphene::elasticsearch::bulk_struct, (account_history)(operation_history)(operation_type)(operation_id_num)(block_data)(additional_data) )
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <sstream>

#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "filelib.h"
#include "weights.h"
#include "line_optimizer.h"
#include "hg.h"
#include "hg_io.h"

using namespace std;
namespace po = boost::program_options;

typedef SparseVector<double> Dir;

typedef RandomNumberGenerator<boost::mt19937> RNG;
RNG rng;

struct oracle_directions {
  string forest_repository;
  unsigned dev_set_size;
  vector<Dir> dirs; //best_to_hope_dirs
  vector<int> fids;
  string forest_file(unsigned i) const {
    ostringstream o;
    o << forest_repository << '/' << i << ".json.gz";
    return o.str();
  }

  oracle_directions(string forest_repository,unsigned dev_set_size,vector<int> const& fids=vector<int>()): forest_repository(forest_repository),dev_set_size(dev_set_size),fids(fids) {
    dirs.resize(dev_set_size);
  }
  Dir const& operator[](unsigned i) {
    Dir &dir=dirs[i];
    if (dir.empty()) {
      ReadFile rf(forest_file(i));
      Hypergraph hg;
      HypergraphIO::ReadFromJSON(rf.stream(), &hg);
      cerr<<"oracle: forest["<<i<<"] loaded: "<<hg.stats()<<endl;
      //TODO: get hope/oracle from vlad.  random for now.
      LineOptimizer::RandomUnitVector(fids,&dir,&rng);
    }
    return dir;
  }

};

void compress_similar(vector<Dir> &dirs,double min_dist,ostream *log=&cerr,bool avg=true) {
  if (min_dist<=0) return;
  double max_s=1.-min_dist;
  unsigned N=dirs.size();
  for (int i=0;i<N;++i) {
    for (int j=i+1;j<N;++j) {
      double s=dirs[i].tanimoto_coef(dirs[j]);
      if (s>max_s) {
        if (log) *log << "Collapsing similar directions (T="<<s<<" > "<<max_s<<").  dirs["<<i<<"]="<<dirs[i]<<" dirs["<<j<<"]";
        if (avg) {
          dirs[i]+=dirs[j];
          dirs[i]/=2.;
          if (log) *log<<" averaged="<<dirs[i];
        }
        if (log) *log<<endl;
        swap(dirs[j],dirs[--N]);
      }
    }
  }
  dirs.resize(N);
}

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("dev_set_size,s",po::value<unsigned int>(),"[REQD] Development set size (# of parallel sentences)")
        ("forest_repository,r",po::value<string>(),"[REQD] Path to forest repository")
        ("weights,w",po::value<string>(),"[REQD] Current feature weights file")
        ("optimize_feature,o",po::value<vector<string> >(), "Feature to optimize (if none specified, all weights listed in the weights file will be optimized)")
        ("random_directions,d",po::value<unsigned int>()->default_value(20),"Number of random directions to run the line optimizer in")
    ("no_primary,n","don't use the primary (orthogonal each feature alone) directions")
    ("oracle_directions,O",po::value<unsigned>()->default_value(0),"read the forests and choose this many directions based on heading toward a hope max (bleu+modelscore) translation.")
    ("oracle_batch,b",po::value<unsigned>()->default_value(10),"to produce each oracle direction, sum the 'gradient' over this many sentences")
    ("max_similarity,m",po::value<double>()->default_value(0),"remove directions that are too similar (Tanimoto coeff. less than (1-this)).  0 means don't filter, 1 means only 1 direction allowed?")
        ("help,h", "Help");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);
  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  bool flag = false;
  if (conf->count("dev_set_size") == 0) {
    cerr << "Please specify the size of the development set using -d N\n";
    flag = true;
  }
  if (conf->count("weights") == 0) {
    cerr << "Please specify the starting-point weights using -w <weightfile.txt>\n";
    flag = true;
  }
  if (conf->count("forest_repository") == 0) {
    cerr << "Please specify the forest repository location using -r <DIR>\n";
    flag = true;
  }
  if (flag || conf->count("help")) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

int main(int argc, char** argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  Weights weights;
  vector<string> features;
  weights.InitFromFile(conf["weights"].as<string>(), &features);
  vector<int> fids(features.size());
  for (int i = 0; i < features.size(); ++i)
    fids[i] = FD::Convert(features[i]);

  oracle_directions od(conf["forest_repository"].as<string>()
                       , conf["dev_set_size"].as<unsigned int>()
                       , fids
    );
;
  assert(DirectoryExists(od.forest_repository));
  SparseVector<double> origin;
  weights.InitSparseVector(&origin);
  if (conf.count("optimize_feature") > 0)
    features=conf["optimize_feature"].as<vector<string> >();
  vector<SparseVector<double> > axes;
  LineOptimizer::CreateOptimizationDirections(
     fids,
     conf["random_directions"].as<unsigned int>(),
     &rng,
     &axes,
     !conf.count("no_primary")
    );
  compress_similar(axes,conf["max_similarity"].as<double>());
  for (int i = 0; i < od.dev_set_size; ++i)
    for (int j = 0; j < axes.size(); ++j)
      cout << od.forest_file(i) <<" " << i << ' ' << origin << ' ' << axes[j] << endl;
  return 0;
}
<commit_msg>vest oracle directions<commit_after>#include <iostream>
#include <vector>
#include <sstream>

#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "sampler.h"
#include "filelib.h"
#include "weights.h"
#include "line_optimizer.h"
#include "hg.h"
#include "hg_io.h"

using namespace std;
namespace po = boost::program_options;

typedef SparseVector<double> Dir;

MT19937 rng;

struct oracle_directions {
  string forest_repository;
  unsigned dev_set_size;
  vector<Dir> dirs; //best_to_hope_dirs
  vector<int> fids;
  string forest_file(unsigned i) const {
    ostringstream o;
    o << forest_repository << '/' << i << ".json.gz";
    return o.str();
  }

  oracle_directions(string forest_repository,unsigned dev_set_size,vector<int> const& fids=vector<int>()): forest_repository(forest_repository),dev_set_size(dev_set_size),fids(fids) {
    dirs.resize(dev_set_size);
  }
  Dir const& operator[](unsigned i) {
    Dir &dir=dirs[i];
    if (dir.empty()) {
      ReadFile rf(forest_file(i));
      Hypergraph hg;
      HypergraphIO::ReadFromJSON(rf.stream(), &hg);
      cerr<<"oracle: forest["<<i<<"] loaded: "<<hg.stats()<<endl;
      //TODO: get hope/oracle from vlad.  random for now.
      LineOptimizer::RandomUnitVector(fids,&dir,&rng);
    }
    return dir;
  }
  // if start_random is true, immediately sample w/ replacement from src sentences; otherwise, consume them sequentially until exhausted, then random.  oracle vectors are summed
  void add_directions(vector<Dir> &dirs,unsigned n,unsigned batchsz=20,bool start_random=false) {
    MT19937::IntRNG rsg=rng.inclusive(0,dev_set_size-1);
    unsigned b=0;
    for(unsigned i=0;i<n;++i) {
      dirs.push_back(Dir());
      Dir &d=dirs.back();
      for (unsigned j=0;j<batchsz;++j,++b)
        d+=(*this)[(start_random || b>=dev_set_size)?rsg():b];
      d/=(double)batchsz;
    }
  }

};

void compress_similar(vector<Dir> &dirs,double min_dist,ostream *log=&cerr,bool avg=true) {
  if (min_dist<=0) return;
  double max_s=1.-min_dist;
  unsigned N=dirs.size();
  for (int i=0;i<N;++i) {
    for (int j=i+1;j<N;++j) {
      double s=dirs[i].tanimoto_coef(dirs[j]);
      if (s>max_s) {
        if (log) *log << "Collapsing similar directions (T="<<s<<" > "<<max_s<<").  dirs["<<i<<"]="<<dirs[i]<<" dirs["<<j<<"]";
        if (avg) {
          dirs[i]+=dirs[j];
          dirs[i]/=2.;
          if (log) *log<<" averaged="<<dirs[i];
        }
        if (log) *log<<endl;
        swap(dirs[j],dirs[--N]);
      }
    }
  }
  dirs.resize(N);
}

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("dev_set_size,s",po::value<unsigned int>(),"[REQD] Development set size (# of parallel sentences)")
        ("forest_repository,r",po::value<string>(),"[REQD] Path to forest repository")
        ("weights,w",po::value<string>(),"[REQD] Current feature weights file")
        ("optimize_feature,o",po::value<vector<string> >(), "Feature to optimize (if none specified, all weights listed in the weights file will be optimized)")
        ("random_directions,d",po::value<unsigned int>()->default_value(20),"Number of random directions to run the line optimizer in")
    ("no_primary,n","don't use the primary (orthogonal each feature alone) directions")
    ("oracle_directions,O",po::value<unsigned>()->default_value(0),"read the forests and choose this many directions based on heading toward a hope max (bleu+modelscore) translation.")
    ("oracle_batch,b",po::value<unsigned>()->default_value(10),"to produce each oracle direction, sum the 'gradient' over this many sentences")
    ("max_similarity,m",po::value<double>()->default_value(0),"remove directions that are too similar (Tanimoto coeff. less than (1-this)).  0 means don't filter, 1 means only 1 direction allowed?")
        ("help,h", "Help");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);
  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  bool flag = false;
  if (conf->count("dev_set_size") == 0) {
    cerr << "Please specify the size of the development set using -d N\n";
    flag = true;
  }
  if (conf->count("weights") == 0) {
    cerr << "Please specify the starting-point weights using -w <weightfile.txt>\n";
    flag = true;
  }
  if (conf->count("forest_repository") == 0) {
    cerr << "Please specify the forest repository location using -r <DIR>\n";
    flag = true;
  }
  if (flag || conf->count("help")) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

int main(int argc, char** argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  Weights weights;
  vector<string> features;
  weights.InitFromFile(conf["weights"].as<string>(), &features);
  vector<int> fids(features.size());
  for (int i = 0; i < features.size(); ++i)
    fids[i] = FD::Convert(features[i]);

  oracle_directions od(conf["forest_repository"].as<string>()
                       , conf["dev_set_size"].as<unsigned int>()
                       , fids
    );
;
  assert(DirectoryExists(od.forest_repository));
  SparseVector<double> origin;
  weights.InitSparseVector(&origin);
  if (conf.count("optimize_feature") > 0)
    features=conf["optimize_feature"].as<vector<string> >();
  vector<SparseVector<double> > axes;
  LineOptimizer::CreateOptimizationDirections(
     fids,
     conf["random_directions"].as<unsigned int>(),
     &rng,
     &axes,
     !conf.count("no_primary")
    );
  od.add_directions(axes,conf["oracle_directions"].as<unsigned>(),conf["oracle_batch"].as<unsigned>());
  compress_similar(axes,conf["max_similarity"].as<double>());
  for (int i = 0; i < od.dev_set_size; ++i)
    for (int j = 0; j < axes.size(); ++j)
      cout << od.forest_file(i) <<" " << i << ' ' << origin << ' ' << axes[j] << endl;
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/textfield/textfield.h"

#if defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#endif

#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif

#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"

#if defined(OS_WIN)
// TODO(beng): this should be removed when the OS_WIN hack from
// ViewHierarchyChanged is removed.
#include "views/controls/textfield/native_textfield_win.h"
#endif

namespace views {

// static
const char Textfield::kViewClassName[] = "views/Textfield";

/////////////////////////////////////////////////////////////////////////////
// Textfield

Textfield::Textfield()
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(STYLE_DEFAULT),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::Textfield(StyleFlags style)
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(style),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::~Textfield() {
}

void Textfield::SetController(Controller* controller) {
  controller_ = controller;
}

Textfield::Controller* Textfield::GetController() const {
  return controller_;
}

void Textfield::SetReadOnly(bool read_only) {
  read_only_ = read_only;
  if (native_wrapper_) {
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateBackgroundColor();
  }
}

bool Textfield::IsPassword() const {
  return style_ & STYLE_PASSWORD;
}

bool Textfield::IsMultiLine() const {
  return !!(style_ & STYLE_MULTILINE);
}

void Textfield::SetText(const string16& text) {
  text_ = text;
  if (native_wrapper_)
    native_wrapper_->UpdateText();
}

void Textfield::AppendText(const string16& text) {
  text_ += text;
  if (native_wrapper_)
    native_wrapper_->AppendText(text);
}

void Textfield::SelectAll() {
  if (native_wrapper_)
    native_wrapper_->SelectAll();
}

string16 Textfield::GetSelectedText() const {
  if (native_wrapper_)
    return native_wrapper_->GetSelectedText();
  return string16();
}

void Textfield::ClearSelection() const {
  if (native_wrapper_)
    native_wrapper_->ClearSelection();
}

void Textfield::SetBackgroundColor(SkColor color) {
  background_color_ = color;
  use_default_background_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::UseDefaultBackgroundColor() {
  use_default_background_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::SetFont(const gfx::Font& font) {
  font_ = font;
  if (native_wrapper_)
    native_wrapper_->UpdateFont();
}

void Textfield::SetHorizontalMargins(int left, int right) {
  if (native_wrapper_)
    native_wrapper_->SetHorizontalMargins(left, right);
}

void Textfield::SetHeightInLines(int num_lines) {
  DCHECK(IsMultiLine());
  num_lines_ = num_lines;
}

void Textfield::RemoveBorder() {
  if (!draw_border_)
    return;

  draw_border_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBorder();
}

void Textfield::CalculateInsets(gfx::Insets* insets) {
  DCHECK(insets);

  if (!draw_border_)
    return;

  // NOTE: One would think GetThemeMargins would return the insets we should
  // use, but it doesn't. The margins returned by GetThemeMargins are always
  // 0.

  // This appears to be the insets used by Windows.
  insets->Set(3, 3, 3, 3);
}

void Textfield::SyncText() {
  if (native_wrapper_)
    text_ = native_wrapper_->GetText();
}

////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:

void Textfield::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
    native_wrapper_->GetView()->Layout();
  }
}

gfx::Size Textfield::GetPreferredSize() {
  gfx::Insets insets;
  CalculateInsets(&insets);
  return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
                       insets.width(),
                   num_lines_ * font_.height() + insets.height());
}

bool Textfield::IsFocusable() const {
  return IsEnabled() && !read_only_;
}

void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
  SelectAll();
}

bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
  // TODO(hamaji): Figure out which keyboard combinations we need to add here,
  //               similar to LocationBarView::SkipDefaultKeyEventProcessing.
  const int c = e.GetCharacter();
  if (c == VK_BACK)
    return true;  // We'll handle BackSpace ourselves.

  // We don't translate accelerators for ALT + NumPad digit, they are used for
  // entering special characters.  We do translate alt-home.
  if (e.IsAltDown() && (c != VK_HOME) &&
      win_util::IsNumPadDigit(c, e.IsExtendedKey()))
    return true;
#endif
  return false;
}

void Textfield::SetEnabled(bool enabled) {
  View::SetEnabled(enabled);
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void Textfield::Focus() {
  if (native_wrapper_) {
    // Forward the focus to the wrapper if it exists.
    native_wrapper_->SetFocus();
  } else {
    // If there is no wrapper, cause the RootView to be focused so that we still
    // get keyboard messages.
    View::Focus();
  }
}

void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
    initialized_ = true;

    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
    AddChildView(native_wrapper_->GetView());
    // TODO(beng): Move this initialization to NativeTextfieldWin once it
    //             subclasses NativeControlWin.
    native_wrapper_->UpdateText();
    native_wrapper_->UpdateBackgroundColor();
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateFont();
    native_wrapper_->UpdateEnabled();
    native_wrapper_->UpdateBorder();

#if defined(OS_WIN)
    // TODO(beng): remove this once NativeTextfieldWin subclasses
    // NativeControlWin. This is currently called to perform post-AddChildView
    // initialization for the wrapper. The GTK version subclasses things
    // correctly and doesn't need this.
    //
    // Remove the include for native_textfield_win.h above when you fix this.
    static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();
#endif
  }
}

std::string Textfield::GetClassName() const {
  return kViewClassName;
}

NativeTextfieldWrapper* Textfield::CreateWrapper() {
  NativeTextfieldWrapper* native_wrapper =
      NativeTextfieldWrapper::CreateWrapper(this);

  native_wrapper->UpdateText();
  native_wrapper->UpdateBackgroundColor();
  native_wrapper->UpdateReadOnly();
  native_wrapper->UpdateFont();
  native_wrapper->UpdateEnabled();
  native_wrapper->UpdateBorder();

  return native_wrapper;
}

base::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {
#if defined(OS_WIN)
  return static_cast<base::KeyboardCode>(key_);
#else
  return static_cast<base::KeyboardCode>(event_.keyval);
#endif
}

#if defined(OS_WIN)
bool Textfield::Keystroke::IsControlHeld() const {
  return GetKeyState(VK_CONTROL) >= 0;
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return GetKeyState(VK_SHIFT) >= 0;
}
#else
bool Textfield::Keystroke::IsControlHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_CONTROL_MASK;
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_SHIFT_MASK;
}
#endif

}  // namespace views
<commit_msg>Home/End were being forwarded to the page from the find box.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/textfield/textfield.h"

#if defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#endif

#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#include "base/win_util.h"
#endif

#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"

#if defined(OS_WIN)
// TODO(beng): this should be removed when the OS_WIN hack from
// ViewHierarchyChanged is removed.
#include "views/controls/textfield/native_textfield_win.h"
#endif

namespace views {

// static
const char Textfield::kViewClassName[] = "views/Textfield";

/////////////////////////////////////////////////////////////////////////////
// Textfield

Textfield::Textfield()
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(STYLE_DEFAULT),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::Textfield(StyleFlags style)
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(style),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::~Textfield() {
}

void Textfield::SetController(Controller* controller) {
  controller_ = controller;
}

Textfield::Controller* Textfield::GetController() const {
  return controller_;
}

void Textfield::SetReadOnly(bool read_only) {
  read_only_ = read_only;
  if (native_wrapper_) {
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateBackgroundColor();
  }
}

bool Textfield::IsPassword() const {
  return style_ & STYLE_PASSWORD;
}

bool Textfield::IsMultiLine() const {
  return !!(style_ & STYLE_MULTILINE);
}

void Textfield::SetText(const string16& text) {
  text_ = text;
  if (native_wrapper_)
    native_wrapper_->UpdateText();
}

void Textfield::AppendText(const string16& text) {
  text_ += text;
  if (native_wrapper_)
    native_wrapper_->AppendText(text);
}

void Textfield::SelectAll() {
  if (native_wrapper_)
    native_wrapper_->SelectAll();
}

string16 Textfield::GetSelectedText() const {
  if (native_wrapper_)
    return native_wrapper_->GetSelectedText();
  return string16();
}

void Textfield::ClearSelection() const {
  if (native_wrapper_)
    native_wrapper_->ClearSelection();
}

void Textfield::SetBackgroundColor(SkColor color) {
  background_color_ = color;
  use_default_background_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::UseDefaultBackgroundColor() {
  use_default_background_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::SetFont(const gfx::Font& font) {
  font_ = font;
  if (native_wrapper_)
    native_wrapper_->UpdateFont();
}

void Textfield::SetHorizontalMargins(int left, int right) {
  if (native_wrapper_)
    native_wrapper_->SetHorizontalMargins(left, right);
}

void Textfield::SetHeightInLines(int num_lines) {
  DCHECK(IsMultiLine());
  num_lines_ = num_lines;
}

void Textfield::RemoveBorder() {
  if (!draw_border_)
    return;

  draw_border_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBorder();
}

void Textfield::CalculateInsets(gfx::Insets* insets) {
  DCHECK(insets);

  if (!draw_border_)
    return;

  // NOTE: One would think GetThemeMargins would return the insets we should
  // use, but it doesn't. The margins returned by GetThemeMargins are always
  // 0.

  // This appears to be the insets used by Windows.
  insets->Set(3, 3, 3, 3);
}

void Textfield::SyncText() {
  if (native_wrapper_)
    text_ = native_wrapper_->GetText();
}

////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:

void Textfield::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
    native_wrapper_->GetView()->Layout();
  }
}

gfx::Size Textfield::GetPreferredSize() {
  gfx::Insets insets;
  CalculateInsets(&insets);
  return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
                       insets.width(),
                   num_lines_ * font_.height() + insets.height());
}

bool Textfield::IsFocusable() const {
  return IsEnabled() && !read_only_;
}

void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
  SelectAll();
}

bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
  // TODO(hamaji): Figure out which keyboard combinations we need to add here,
  //               similar to LocationBarView::SkipDefaultKeyEventProcessing.
  const int c = e.GetCharacter();
  if (c == VK_BACK)
    return true;  // We'll handle BackSpace ourselves.

  // We don't translate accelerators for ALT + NumPad digit, they are used for
  // entering special characters.  We do translate alt-home.
  if (e.IsAltDown() && (c != VK_HOME) &&
      win_util::IsNumPadDigit(c, e.IsExtendedKey()))
    return true;
#endif
  return false;
}

void Textfield::SetEnabled(bool enabled) {
  View::SetEnabled(enabled);
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void Textfield::Focus() {
  if (native_wrapper_) {
    // Forward the focus to the wrapper if it exists.
    native_wrapper_->SetFocus();
  } else {
    // If there is no wrapper, cause the RootView to be focused so that we still
    // get keyboard messages.
    View::Focus();
  }
}

void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
    initialized_ = true;

    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
    AddChildView(native_wrapper_->GetView());
    // TODO(beng): Move this initialization to NativeTextfieldWin once it
    //             subclasses NativeControlWin.
    native_wrapper_->UpdateText();
    native_wrapper_->UpdateBackgroundColor();
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateFont();
    native_wrapper_->UpdateEnabled();
    native_wrapper_->UpdateBorder();

#if defined(OS_WIN)
    // TODO(beng): remove this once NativeTextfieldWin subclasses
    // NativeControlWin. This is currently called to perform post-AddChildView
    // initialization for the wrapper. The GTK version subclasses things
    // correctly and doesn't need this.
    //
    // Remove the include for native_textfield_win.h above when you fix this.
    static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();
#endif
  }
}

std::string Textfield::GetClassName() const {
  return kViewClassName;
}

NativeTextfieldWrapper* Textfield::CreateWrapper() {
  NativeTextfieldWrapper* native_wrapper =
      NativeTextfieldWrapper::CreateWrapper(this);

  native_wrapper->UpdateText();
  native_wrapper->UpdateBackgroundColor();
  native_wrapper->UpdateReadOnly();
  native_wrapper->UpdateFont();
  native_wrapper->UpdateEnabled();
  native_wrapper->UpdateBorder();

  return native_wrapper;
}

base::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {
#if defined(OS_WIN)
  return static_cast<base::KeyboardCode>(key_);
#else
  return static_cast<base::KeyboardCode>(event_.keyval);
#endif
}

#if defined(OS_WIN)
bool Textfield::Keystroke::IsControlHeld() const {
  return win_util::IsCtrlPressed();
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return win_util::IsShiftPressed();
}
#else
bool Textfield::Keystroke::IsControlHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_CONTROL_MASK;
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_SHIFT_MASK;
}
#endif

}  // namespace views
<|endoftext|>


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

//-------------------------------------------------------
//          Implementation of the TPC tracker helper clasess
//  AliTPCtrackerRow
//  AliTPCtrackerSector
//
//   Origin: Marian Ivanov   Marian.Ivanov@cern.ch
//
//  AliTPCtrakerMI -  parallel tracker helper clases
//

/* $Id: AliTPCtrackerSector.cxx 25837 2008-05-16 16:39:00Z marian $ */

#include "Riostream.h"
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliComplexCluster.h"
#include "AliTPCcluster.h"
#include "AliTPCclusterMI.h"
#include "AliTPCClustersRow.h"
#include "AliTPCParam.h"
#include "AliTPCReconstructor.h"
#include "AliTPCreco.h"
//
#include "AliTPCtrackerSector.h"
#include "TStopwatch.h"
#include "TTreeStream.h"

//

ClassImp(AliTPCtrackerRow)
ClassImp(AliTPCtrackerSector)

AliTPCtrackerRow::AliTPCtrackerRow():
  fDeadZone(0.),
  fClusters1(0),
  fN1(0),
  fClusters2(0),
  fN2(0),
  fFastCluster(),
  fN(0),
  fClusters(),
  fIndex(),
  fX(0.)
{
  //
  // default constructor
  //
}

AliTPCtrackerRow::~AliTPCtrackerRow(){
  //
  delete fClusters1;
  delete fClusters2;
}

//_________________________________________________________________________
void
AliTPCtrackerRow::InsertCluster(const AliTPCclusterMI* c, UInt_t index) {
  //-----------------------------------------------------------------------
  // Insert a cluster into this pad row in accordence with its y-coordinate
  //-----------------------------------------------------------------------
  if (!c) {
    AliError("Inserting Zerro cluster pointer");
    return;
  }
  if (fN==kMaxClusterPerRow) {
    //AliInfo("AliTPCtrackerRow::InsertCluster(): Too many clusters");
    return;
  }
  if (fN>=fN1+fN2) {
    //AliInfo("AliTPCtrackerRow::InsertCluster(): Too many clusters !");
  }

  if (fN==0) {fIndex[0]=index; fClusters[fN++]=c; return;}
  Int_t i=Find(c->GetZ());
  if (i>=0 && i<=kMaxClusterPerRow-2) {
    memmove(fClusters+i+1 ,fClusters+i,(fN-i)*sizeof(AliTPCclusterMI*));
    memmove(fIndex   +i+1 ,fIndex   +i,(fN-i)*sizeof(UInt_t));
  }
  fIndex[i]=index; fClusters[i]=c; fN++;
}

void AliTPCtrackerRow::ResetClusters() {
   //
   // reset clusters
   // MvL: Need to call destructors for AliTPCclusterMI, to delete fInfo
  if (fClusters1) fClusters1->Clear("C");
  if (fClusters2) fClusters2->Clear("C");

   fN  = 0;
   fN1 = 0;
   fN2 = 0;
   //delete[] fClusterArray;

   //fClusterArray=0;
}

//___________________________________________________________________
Int_t AliTPCtrackerRow::Find(Double_t z) const {
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster
  //-----------------------------------------------------------------------
  if (fN==0) return 0;
  if (z <= fClusters[0]->GetZ()) return 0;
  if (z > fClusters[fN-1]->GetZ()) return fN;
  Int_t b=0, e=fN-1, m=(b+e)/2;
  for (; b<e; m=(b+e)/2) {
    if (z > fClusters[m]->GetZ()) b=m+1;
    else e=m;
  }
  return m;
}

//___________________________________________________________________
AliTPCclusterMI * AliTPCtrackerRow::FindNearest(Double_t y, Double_t z, Double_t roady, Double_t roadz) const {
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster in z y
  //-----------------------------------------------------------------------
  Float_t maxdistance = roady*roady + roadz*roadz;

  AliTPCclusterMI *cl =0;
  for (Int_t i=Find(z-roadz); i<fN; i++) {
      AliTPCclusterMI *c=(AliTPCclusterMI*)(fClusters[i]);
      if (c->GetZ() > z+roadz) break;
      if ( (c->GetY()-y) >  roady ) continue;
      Float_t distance = (c->GetZ()-z)*(c->GetZ()-z)+(c->GetY()-y)*(c->GetY()-y);
      if (maxdistance>distance) {
	maxdistance = distance;
	cl=c;
      }
  }
  return cl;
}

AliTPCclusterMI * AliTPCtrackerRow::FindNearest2(Double_t y, Double_t z, Double_t roady, Double_t roadz,UInt_t & index) const
{
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster in z y
  //-----------------------------------------------------------------------
  Float_t maxdistance = roady*roady + roadz*roadz;
  AliTPCclusterMI *cl =0;

  //PH Check boundaries. 510 is the size of fFastCluster
  Int_t iz1 = Int_t(z-roadz+254.5);
  if (iz1<0 || iz1>=510) return cl;
  iz1 = TMath::Max(GetFastCluster(iz1)-1,0);
  Int_t iz2 = Int_t(z+roadz+255.5);
  if (iz2<0 || iz2>=510) return cl;
  iz2 = TMath::Min(GetFastCluster(iz2)+1,fN);
  Bool_t skipUsed = !(AliTPCReconstructor::GetRecoParam()->GetClusterSharing());
  //FindNearest3(y,z,roady,roadz,index);
  //  for (Int_t i=Find(z-roadz); i<fN; i++) {
  for (Int_t i=iz1; i<iz2; i++) {
      AliTPCclusterMI *c=(AliTPCclusterMI*)(fClusters[i]);
      if (c->GetZ() > z+roadz) break;
      if ( c->GetY()-y >  roady ) continue;
      if ( y-c->GetY() >  roady ) continue;
      if (skipUsed && c->IsUsed(11)) continue;
      Float_t distance = (c->GetZ()-z)*(c->GetZ()-z)+(c->GetY()-y)*(c->GetY()-y);
      if (maxdistance>distance) {
	maxdistance = distance;
	cl=c;
	index =i;
	//roady = TMath::Sqrt(maxdistance);
      }
  }
  return cl;
}

void AliTPCtrackerRow::SetFastCluster(Int_t i, Short_t cl){
  //
  // Set cluster info for fast navigation
  //
  if (i>=510|| i<0){
  }else{
    fFastCluster[i]=cl;
  }
}

Int_t  AliTPCtrackerSector::GetRowNumber(Double_t x) const
{
  //return pad row number for this x
  Double_t r;
  if (fN < 64){
    r=fRow[fN-1].GetX();
    if (x > r) return fN;
    r=fRow[0].GetX();
    if (x < r) return -1;
    return Int_t((x-r)/fPadPitchLength + 0.5);}
  else{
    r=fRow[fN-1].GetX();
    if (x > r) return fN;
    r=fRow[0].GetX();
    if (x < r) return -1;
    Double_t r1=fRow[64].GetX();
    if(x<r1){
      return Int_t((x-r)/f1PadPitchLength + 0.5);}
    else{
      return (Int_t((x-r1)/f2PadPitchLength + 0.5)+64);}
  }
}

void AliTPCtrackerRow::SetCluster1(Int_t i, const AliTPCclusterMI &cl)
{
  // attach cluster
  if (!fClusters1) fClusters1 = new TClonesArray("AliTPCclusterMI",1000);
  if (i<=fClusters1->GetLast() && fClusters1->UncheckedAt(i)) fClusters1->RemoveAt(i);
  new( (*fClusters1)[fClusters1->GetEntriesFast()] ) AliTPCclusterMI(cl);
  //
}

void AliTPCtrackerRow::SetCluster2(Int_t i, const AliTPCclusterMI &cl)
{
  // attach cluster
  if (!fClusters2) fClusters2 = new TClonesArray("AliTPCclusterMI",1000);
  if (i<=fClusters2->GetLast() && fClusters2->UncheckedAt(i)) fClusters2->RemoveAt(i);
  new( (*fClusters2)[fClusters2->GetEntriesFast()] ) AliTPCclusterMI(cl);
  //
}

//_________________________________________________________________________
void AliTPCtrackerSector::Setup(const AliTPCParam *par, Int_t f) {
  //-----------------------------------------------------------------------
  // Setup inner sector
  //-----------------------------------------------------------------------
  if (f==0) {
     fAlpha=par->GetInnerAngle();
     fAlphaShift=par->GetInnerAngleShift();
     fPadPitchWidth=par->GetInnerPadPitchWidth();
     fPadPitchLength=par->GetInnerPadPitchLength();
     fN=par->GetNRowLow();
     if(fRow)delete [] fRow;fRow = 0;
     fRow=new AliTPCtrackerRow[fN];
     for (Int_t i=0; i<fN; i++) {
       fRow[i].SetX(par->GetPadRowRadiiLow(i));
       fRow[i].SetDeadZone(1.5);  //1.5 cm of dead zone
     }
  } else {
     fAlpha=par->GetOuterAngle();
     fAlphaShift=par->GetOuterAngleShift();
     fPadPitchWidth  = par->GetOuterPadPitchWidth();
     fPadPitchLength = par->GetOuter1PadPitchLength();
     f1PadPitchLength = par->GetOuter1PadPitchLength();
     f2PadPitchLength = par->GetOuter2PadPitchLength();
     fN=par->GetNRowUp();
     if(fRow)delete [] fRow;fRow = 0;
     fRow=new AliTPCtrackerRow[fN];
     for (Int_t i=0; i<fN; i++) {
       fRow[i].SetX(par->GetPadRowRadiiUp(i));
       fRow[i].SetDeadZone(1.5);  // 1.5 cm of dead zone
     }
  }
}

//_________________________________________________________________________
void AliTPCtrackerSector::InsertCluster(AliTPCclusterMI *cl, Int_t size, const AliTPCParam *par) {
  //-----------------------------------------------------------------------
  // Insert cluster to the sector
  //-----------------------------------------------------------------------

  if(!cl) return;

  const Int_t fkNIS = par->GetNInnerSector()/2;
  const Int_t fkNOS = par->GetNOuterSector()/2;
  Int_t row = cl->GetRow();
  Int_t sec = cl->GetDetector();

  // add cluster to the corresponding pad row
  AliTPCtrackerRow *tpcrow = 0x0;

  Int_t left=0;
  if (sec<fkNIS*2){
    left = sec/fkNIS;
  }
  else{
    left = (sec-fkNIS*2)/fkNOS;
  }
  //
  if (left ==0){
    tpcrow = fRow+row;
    if(!tpcrow->GetClusters1()) {
       tpcrow->SetN1(0);
    }
    if(size < kMaxClusterPerRow) {
      tpcrow->SetCluster1(tpcrow->GetN1(), *cl);
      //printf("inner: size %d, tpcrow->GetN1() %d  sec %d row %d tpcrow %p cl %p\n", size, tpcrow->GetN1(), sec, row, tpcrow, cl);

      tpcrow->IncrementN1();
    }
  }
  if (left ==1){
    tpcrow = fRow+row;
    if(!tpcrow->GetClusters2()) {
      tpcrow->SetN2(0);
    }
    if(size < kMaxClusterPerRow)  {
      tpcrow->SetCluster2(tpcrow->GetN2(), *cl);
      //printf("outer: size %d, tpcrow->GetN2() %d  sec %d row %d tpcrow %p cl %p\n", size, tpcrow->GetN2(), sec, row, tpcrow, cl);

      tpcrow->IncrementN2();
    }
  }
}

<commit_msg> Fixes a small problem with finding clusters close to the Z ends <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.                  *
 **************************************************************************/

//-------------------------------------------------------
//          Implementation of the TPC tracker helper clasess
//  AliTPCtrackerRow
//  AliTPCtrackerSector
//
//   Origin: Marian Ivanov   Marian.Ivanov@cern.ch
//
//  AliTPCtrakerMI -  parallel tracker helper clases
//

/* $Id: AliTPCtrackerSector.cxx 25837 2008-05-16 16:39:00Z marian $ */

#include "Riostream.h"
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliComplexCluster.h"
#include "AliTPCcluster.h"
#include "AliTPCclusterMI.h"
#include "AliTPCClustersRow.h"
#include "AliTPCParam.h"
#include "AliTPCReconstructor.h"
#include "AliTPCreco.h"
//
#include "AliTPCtrackerSector.h"
#include "TStopwatch.h"
#include "TTreeStream.h"

//

ClassImp(AliTPCtrackerRow)
ClassImp(AliTPCtrackerSector)

AliTPCtrackerRow::AliTPCtrackerRow():
  fDeadZone(0.),
  fClusters1(0),
  fN1(0),
  fClusters2(0),
  fN2(0),
  fFastCluster(),
  fN(0),
  fClusters(),
  fIndex(),
  fX(0.)
{
  //
  // default constructor
  //
}

AliTPCtrackerRow::~AliTPCtrackerRow(){
  //
  delete fClusters1;
  delete fClusters2;
}

//_________________________________________________________________________
void
AliTPCtrackerRow::InsertCluster(const AliTPCclusterMI* c, UInt_t index) {
  //-----------------------------------------------------------------------
  // Insert a cluster into this pad row in accordence with its y-coordinate
  //-----------------------------------------------------------------------
  if (!c) {
    AliError("Inserting Zerro cluster pointer");
    return;
  }
  if (fN==kMaxClusterPerRow) {
    //AliInfo("AliTPCtrackerRow::InsertCluster(): Too many clusters");
    return;
  }
  if (fN>=fN1+fN2) {
    //AliInfo("AliTPCtrackerRow::InsertCluster(): Too many clusters !");
  }

  if (fN==0) {fIndex[0]=index; fClusters[fN++]=c; return;}
  Int_t i=Find(c->GetZ());
  if (i>=0 && i<=kMaxClusterPerRow-2) {
    memmove(fClusters+i+1 ,fClusters+i,(fN-i)*sizeof(AliTPCclusterMI*));
    memmove(fIndex   +i+1 ,fIndex   +i,(fN-i)*sizeof(UInt_t));
  }
  fIndex[i]=index; fClusters[i]=c; fN++;
}

void AliTPCtrackerRow::ResetClusters() {
   //
   // reset clusters
   // MvL: Need to call destructors for AliTPCclusterMI, to delete fInfo
  if (fClusters1) fClusters1->Clear("C");
  if (fClusters2) fClusters2->Clear("C");

   fN  = 0;
   fN1 = 0;
   fN2 = 0;
   //delete[] fClusterArray;

   //fClusterArray=0;
}

//___________________________________________________________________
Int_t AliTPCtrackerRow::Find(Double_t z) const {
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster
  //-----------------------------------------------------------------------
  if (fN==0) return 0;
  if (z <= fClusters[0]->GetZ()) return 0;
  if (z > fClusters[fN-1]->GetZ()) return fN;
  Int_t b=0, e=fN-1, m=(b+e)/2;
  for (; b<e; m=(b+e)/2) {
    if (z > fClusters[m]->GetZ()) b=m+1;
    else e=m;
  }
  return m;
}

//___________________________________________________________________
AliTPCclusterMI * AliTPCtrackerRow::FindNearest(Double_t y, Double_t z, Double_t roady, Double_t roadz) const {
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster in z y
  //-----------------------------------------------------------------------
  Float_t maxdistance = roady*roady + roadz*roadz;

  AliTPCclusterMI *cl =0;
  for (Int_t i=Find(z-roadz); i<fN; i++) {
      AliTPCclusterMI *c=(AliTPCclusterMI*)(fClusters[i]);
      if (c->GetZ() > z+roadz) break;
      if ( (c->GetY()-y) >  roady ) continue;
      Float_t distance = (c->GetZ()-z)*(c->GetZ()-z)+(c->GetY()-y)*(c->GetY()-y);
      if (maxdistance>distance) {
	maxdistance = distance;
	cl=c;
      }
  }
  return cl;
}

AliTPCclusterMI * AliTPCtrackerRow::FindNearest2(Double_t y, Double_t z, Double_t roady, Double_t roadz,UInt_t & index) const
{
  //-----------------------------------------------------------------------
  // Return the index of the nearest cluster in z y
  //-----------------------------------------------------------------------
  Float_t maxdistance = roady*roady + roadz*roadz;
  AliTPCclusterMI *cl =0;

  //PH Check boundaries. 510 is the size of fFastCluster
  Int_t iz1 = Int_t(z-roadz+254.5);
  if ( iz1>=510) return cl;
  if (iz1<0 ) iz1 = 0;
  iz1 = TMath::Max(GetFastCluster(iz1)-1,0);
  Int_t iz2 = Int_t(z+roadz+255.5);
  if (iz2<0 ) return cl;
  if ( iz2>=510) iz2 = 509;
  iz2 = TMath::Min(GetFastCluster(iz2)+1,fN);
  Bool_t skipUsed = !(AliTPCReconstructor::GetRecoParam()->GetClusterSharing());
  //FindNearest3(y,z,roady,roadz,index);
  //  for (Int_t i=Find(z-roadz); i<fN; i++) {
  for (Int_t i=iz1; i<iz2; i++) {
      AliTPCclusterMI *c=(AliTPCclusterMI*)(fClusters[i]);
      if (c->GetZ() > z+roadz) break;
      if ( c->GetY()-y >  roady ) continue;
      if ( y-c->GetY() >  roady ) continue;
      if (skipUsed && c->IsUsed(11)) continue;
      Float_t distance = (c->GetZ()-z)*(c->GetZ()-z)+(c->GetY()-y)*(c->GetY()-y);
      if (maxdistance>distance) {
	maxdistance = distance;
	cl=c;
	index =i;
	//roady = TMath::Sqrt(maxdistance);
      }
  }
  return cl;
}

void AliTPCtrackerRow::SetFastCluster(Int_t i, Short_t cl){
  //
  // Set cluster info for fast navigation
  //
  if (i>=510|| i<0){
  }else{
    fFastCluster[i]=cl;
  }
}

Int_t  AliTPCtrackerSector::GetRowNumber(Double_t x) const
{
  //return pad row number for this x
  Double_t r;
  if (fN < 64){
    r=fRow[fN-1].GetX();
    if (x > r) return fN;
    r=fRow[0].GetX();
    if (x < r) return -1;
    return Int_t((x-r)/fPadPitchLength + 0.5);}
  else{
    r=fRow[fN-1].GetX();
    if (x > r) return fN;
    r=fRow[0].GetX();
    if (x < r) return -1;
    Double_t r1=fRow[64].GetX();
    if(x<r1){
      return Int_t((x-r)/f1PadPitchLength + 0.5);}
    else{
      return (Int_t((x-r1)/f2PadPitchLength + 0.5)+64);}
  }
}

void AliTPCtrackerRow::SetCluster1(Int_t i, const AliTPCclusterMI &cl)
{
  // attach cluster
  if (!fClusters1) fClusters1 = new TClonesArray("AliTPCclusterMI",1000);
  if (i<=fClusters1->GetLast() && fClusters1->UncheckedAt(i)) fClusters1->RemoveAt(i);
  new( (*fClusters1)[fClusters1->GetEntriesFast()] ) AliTPCclusterMI(cl);
  //
}

void AliTPCtrackerRow::SetCluster2(Int_t i, const AliTPCclusterMI &cl)
{
  // attach cluster
  if (!fClusters2) fClusters2 = new TClonesArray("AliTPCclusterMI",1000);
  if (i<=fClusters2->GetLast() && fClusters2->UncheckedAt(i)) fClusters2->RemoveAt(i);
  new( (*fClusters2)[fClusters2->GetEntriesFast()] ) AliTPCclusterMI(cl);
  //
}

//_________________________________________________________________________
void AliTPCtrackerSector::Setup(const AliTPCParam *par, Int_t f) {
  //-----------------------------------------------------------------------
  // Setup inner sector
  //-----------------------------------------------------------------------
  if (f==0) {
     fAlpha=par->GetInnerAngle();
     fAlphaShift=par->GetInnerAngleShift();
     fPadPitchWidth=par->GetInnerPadPitchWidth();
     fPadPitchLength=par->GetInnerPadPitchLength();
     fN=par->GetNRowLow();
     if(fRow)delete [] fRow;fRow = 0;
     fRow=new AliTPCtrackerRow[fN];
     for (Int_t i=0; i<fN; i++) {
       fRow[i].SetX(par->GetPadRowRadiiLow(i));
       fRow[i].SetDeadZone(1.5);  //1.5 cm of dead zone
     }
  } else {
     fAlpha=par->GetOuterAngle();
     fAlphaShift=par->GetOuterAngleShift();
     fPadPitchWidth  = par->GetOuterPadPitchWidth();
     fPadPitchLength = par->GetOuter1PadPitchLength();
     f1PadPitchLength = par->GetOuter1PadPitchLength();
     f2PadPitchLength = par->GetOuter2PadPitchLength();
     fN=par->GetNRowUp();
     if(fRow)delete [] fRow;fRow = 0;
     fRow=new AliTPCtrackerRow[fN];
     for (Int_t i=0; i<fN; i++) {
       fRow[i].SetX(par->GetPadRowRadiiUp(i));
       fRow[i].SetDeadZone(1.5);  // 1.5 cm of dead zone
     }
  }
}

//_________________________________________________________________________
void AliTPCtrackerSector::InsertCluster(AliTPCclusterMI *cl, Int_t size, const AliTPCParam *par) {
  //-----------------------------------------------------------------------
  // Insert cluster to the sector
  //-----------------------------------------------------------------------

  if(!cl) return;

  const Int_t fkNIS = par->GetNInnerSector()/2;
  const Int_t fkNOS = par->GetNOuterSector()/2;
  Int_t row = cl->GetRow();
  Int_t sec = cl->GetDetector();

  // add cluster to the corresponding pad row
  AliTPCtrackerRow *tpcrow = 0x0;

  Int_t left=0;
  if (sec<fkNIS*2){
    left = sec/fkNIS;
  }
  else{
    left = (sec-fkNIS*2)/fkNOS;
  }
  //
  if (left ==0){
    tpcrow = fRow+row;
    if(!tpcrow->GetClusters1()) {
       tpcrow->SetN1(0);
    }
    if(size < kMaxClusterPerRow) {
      tpcrow->SetCluster1(tpcrow->GetN1(), *cl);
      //printf("inner: size %d, tpcrow->GetN1() %d  sec %d row %d tpcrow %p cl %p\n", size, tpcrow->GetN1(), sec, row, tpcrow, cl);

      tpcrow->IncrementN1();
    }
  }
  if (left ==1){
    tpcrow = fRow+row;
    if(!tpcrow->GetClusters2()) {
      tpcrow->SetN2(0);
    }
    if(size < kMaxClusterPerRow)  {
      tpcrow->SetCluster2(tpcrow->GetN2(), *cl);
      //printf("outer: size %d, tpcrow->GetN2() %d  sec %d row %d tpcrow %p cl %p\n", size, tpcrow->GetN2(), sec, row, tpcrow, cl);

      tpcrow->IncrementN2();
    }
  }
}

<|endoftext|>