<commit_before>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program 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 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "generator.h"
#include "device.h"

#include <QtCore/QDebug>

#include <QDBusReply>
#include <QDBusMessage>
#include <QDBusConnection>

#include <kscreen/config.h>

Generator* Generator::instance = 0;

Generator* Generator::self()
{
    if (!Generator::instance) {
        Generator::instance = new Generator();
    }
    return Generator::instance;
}

Generator::Generator()
 : QObject()
 , m_device(new Device(this))
 , m_isReady(false)
 , m_forceLaptop(false)
 , m_forceLidClosed(false)
 , m_forceDocked(false)
{
    connect(m_device, SIGNAL(ready()), SIGNAL(ready()));
}

void Generator::destroy()
{
    delete Generator::instance;
}

Generator::~Generator()
{
    delete m_device;
}

KScreen::Config* Generator::idealConfig()
{
    KScreen::Config* config = KScreen::Config::current();

    disableAllDisconnectedOutputs(config->outputs());

    KScreen::OutputList connectedOutputs = config->connectedOutputs();

    if (connectedOutputs.count() == 1) {
        qDebug() << "Config for one output";
        KScreen::Output* output = connectedOutputs.take(connectedOutputs.keys().first());
        output->setCurrentMode(output->preferredMode());

        return config;
    }

    //If we are a laptop, go into laptop mode
    if (isLaptop()) {
        return laptop(config, connectedOutputs);
    }

    extendToRight(connectedOutputs);

    return config;
}

KScreen::Config* Generator::laptop(KScreen::Config* config, KScreen::OutputList& outputs)
{
    qDebug() << "Config for a laptop";

    KScreen::Output* embedded = 0;
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (isEmbedded(output->name())) {
            embedded = output;
            outputs.remove(embedded->id());
            continue;
        }
    }

    if (outputs.isEmpty() || !embedded) {
        qWarning("Neither external outputs or embedded could be found");
        return KScreen::Config::current();
    }

    if (isLidClosed() && outputs.count() == 1) {
        qDebug() << "With lid closed";
        embedded->setEnabled(false);

        KScreen::Output* external = outputs.value(outputs.keys().first());
        external->setEnabled(true);
        external->setCurrentMode(external->preferredMode());
        external->setPrimary(true);

        return config;
    }

    if (isLidClosed() && outputs.count() > 1) {
        embedded->setEnabled(false);
        embedded->setPrimary(false);

       extendToRight(outputs);

        return config;
    }

    //If lid is open, laptop screen shuold be primary
    embedded->setPos(QPoint(0,0));
    embedded->setCurrentMode(embedded->preferredMode());
    embedded->setPrimary(true);
    embedded->setEnabled(true);

    QSize globalSize = embedded->mode(embedded->preferredMode())->size();
    KScreen::Output* biggest = biggestOutput(outputs);
    outputs.remove(biggest->id());

    biggest->setPos(QPoint(globalSize.width(), 0));
    biggest->setEnabled(true);
    biggest->setCurrentMode(biggest->preferredMode());
    biggest->setPrimary(false);

    QSize size;
    globalSize += biggest->mode(biggest->currentMode())->size();
    Q_FOREACH(KScreen::Output* output, outputs) {
        output->setEnabled(true);
        output->setCurrentMode(output->preferredMode());
        output->setPos(QPoint(globalSize.width(), 0));

        size = output->mode(output->currentMode())->size();
        globalSize += size;
    }

    if (isDocked()) {
        qDebug() << "Docked";
        embedded->setPrimary(false);
        biggest->setPrimary(true);
    }

    return config;
}

void Generator::extendToRight(KScreen::OutputList& outputs)
{
    KScreen::Output* biggest = biggestOutput(outputs);
    outputs.remove(biggest->id());

    biggest->setEnabled(true);
    biggest->setPrimary(true);
    biggest->setCurrentMode(biggest->preferredMode());
    biggest->setPos(QPoint(0,0));

    QSize size;
    QSize globalSize = biggest->mode(biggest->currentMode())->size();
    Q_FOREACH(KScreen::Output* output, outputs) {
        output->setEnabled(true);
        output->setPrimary(false);
        output->setCurrentMode(output->preferredMode());
        output->setPos(QPoint(globalSize.width(), 0));

        size = output->mode(output->currentMode())->size();
        globalSize += size;
    }
}

KScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)
{
    int area, total = 0;
    KScreen::Mode* biggest = 0;
    Q_FOREACH(KScreen::Mode* mode, modes) {
        area = mode->size().width() * mode->size().height();
        if (area < total) {
            continue;
        }

        total = area;
        biggest = mode;
    }

    return biggest;
}

KScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)
{
    int area, total = 0;
    KScreen::Output* biggest = 0;
    Q_FOREACH(KScreen::Output* output, outputs) {
        KScreen::Mode* mode = output->mode(output->preferredMode());
        area = mode->size().width() * mode->size().height();
        if (area < total) {
            continue;
        }

        total = area;
        biggest = output;
    }

    return biggest;
}

void Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)
{
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (!output->isConnected()) {
            output->setEnabled(false);
        }
    }
}

bool Generator::isEmbedded(const QString& name)
{
    QStringList embedded;
    embedded << "LVDS";
    embedded << "IDP";
    embedded << "EDP";

    Q_FOREACH(const QString &pre, embedded) {
        if (name.toUpper().startsWith(pre)) {
            qDebug() << "This is embedded: " << name;
            return true;
        }
    }

    return false;
}

bool Generator::isLaptop()
{
    if (m_forceLaptop) {
        return true;
    }

    return m_device->isLaptop();
}

bool Generator::isLidClosed()
{
    if (m_forceLidClosed) {
        return true;
    }

    return m_device->isLidClosed();
}

bool Generator::isDocked()
{
    if (m_forceDocked) {
        return true;
    }

    return m_device->isDocked();
}

KScreen::Config* Generator::dockedLaptop()
{
    return new KScreen::Config();
}

KScreen::Config* Generator::desktop()
{
    return new KScreen::Config();
}

void Generator::setForceLaptop(bool force)
{
    m_forceLaptop = force;
}

void Generator::setForceLidClosed(bool force)
{
    m_forceLidClosed = force;
}

void Generator::setForceDocked(bool force)
{
    m_forceDocked = force;
}
<commit_msg>Soem indentation fixes<commit_after>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program 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 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "generator.h"
#include "device.h"

#include <QtCore/QDebug>

#include <QDBusReply>
#include <QDBusMessage>
#include <QDBusConnection>

#include <kscreen/config.h>

Generator* Generator::instance = 0;

Generator* Generator::self()
{
    if (!Generator::instance) {
        Generator::instance = new Generator();
    }
    return Generator::instance;
}

Generator::Generator()
 : QObject()
 , m_device(new Device(this))
 , m_isReady(false)
 , m_forceLaptop(false)
 , m_forceLidClosed(false)
 , m_forceDocked(false)
{
    connect(m_device, SIGNAL(ready()), SIGNAL(ready()));
}

void Generator::destroy()
{
    delete Generator::instance;
}

Generator::~Generator()
{
    delete m_device;
}

KScreen::Config* Generator::idealConfig()
{
    KScreen::Config* config = KScreen::Config::current();

    disableAllDisconnectedOutputs(config->outputs());

    KScreen::OutputList connectedOutputs = config->connectedOutputs();

    if (connectedOutputs.count() == 1) {
        qDebug() << "Config for one output";
        KScreen::Output* output = connectedOutputs.take(connectedOutputs.keys().first());
        output->setCurrentMode(output->preferredMode());

        return config;
    }

    //If we are a laptop, go into laptop mode
    if (isLaptop()) {
        return laptop(config, connectedOutputs);
    }

    extendToRight(connectedOutputs);

    return config;
}

KScreen::Config* Generator::laptop(KScreen::Config* config, KScreen::OutputList& outputs)
{
    qDebug() << "Config for a laptop";

    KScreen::Output* embedded = 0;
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (isEmbedded(output->name())) {
            embedded = output;
            outputs.remove(embedded->id());
            continue;
        }
    }

    if (outputs.isEmpty() || !embedded) {
        qWarning("Neither external outputs or embedded could be found");
        return KScreen::Config::current();
    }

    if (isLidClosed() && outputs.count() == 1) {
        qDebug() << "With lid closed";
        embedded->setEnabled(false);

        KScreen::Output* external = outputs.value(outputs.keys().first());
        external->setEnabled(true);
        external->setCurrentMode(external->preferredMode());
        external->setPrimary(true);

        return config;
    }

    if (isLidClosed() && outputs.count() > 1) {
        embedded->setEnabled(false);
        embedded->setPrimary(false);

        extendToRight(outputs);

        return config;
    }

    //If lid is open, laptop screen shuold be primary
    embedded->setPos(QPoint(0,0));
    embedded->setCurrentMode(embedded->preferredMode());
    embedded->setPrimary(true);
    embedded->setEnabled(true);

    QSize globalSize = embedded->mode(embedded->preferredMode())->size();
    KScreen::Output* biggest = biggestOutput(outputs);
    outputs.remove(biggest->id());

    biggest->setPos(QPoint(globalSize.width(), 0));
    biggest->setEnabled(true);
    biggest->setCurrentMode(biggest->preferredMode());
    biggest->setPrimary(false);

    QSize size;
    globalSize += biggest->mode(biggest->currentMode())->size();
    Q_FOREACH(KScreen::Output* output, outputs) {
        output->setEnabled(true);
        output->setCurrentMode(output->preferredMode());
        output->setPos(QPoint(globalSize.width(), 0));

        size = output->mode(output->currentMode())->size();
        globalSize += size;
    }

    if (isDocked()) {
        qDebug() << "Docked";
        embedded->setPrimary(false);
        biggest->setPrimary(true);
    }

    return config;
}

void Generator::extendToRight(KScreen::OutputList& outputs)
{
    KScreen::Output* biggest = biggestOutput(outputs);
    outputs.remove(biggest->id());

    biggest->setEnabled(true);
    biggest->setPrimary(true);
    biggest->setCurrentMode(biggest->preferredMode());
    biggest->setPos(QPoint(0,0));

    QSize size;
    QSize globalSize = biggest->mode(biggest->currentMode())->size();
    Q_FOREACH(KScreen::Output* output, outputs) {
        output->setEnabled(true);
        output->setPrimary(false);
        output->setCurrentMode(output->preferredMode());
        output->setPos(QPoint(globalSize.width(), 0));

        size = output->mode(output->currentMode())->size();
        globalSize += size;
    }
}

KScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)
{
    int area, total = 0;
    KScreen::Mode* biggest = 0;
    Q_FOREACH(KScreen::Mode* mode, modes) {
        area = mode->size().width() * mode->size().height();
        if (area < total) {
            continue;
        }

        total = area;
        biggest = mode;
    }

    return biggest;
}

KScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)
{
    int area, total = 0;
    KScreen::Output* biggest = 0;
    Q_FOREACH(KScreen::Output* output, outputs) {
        KScreen::Mode* mode = output->mode(output->preferredMode());
        area = mode->size().width() * mode->size().height();
        if (area < total) {
            continue;
        }

        total = area;
        biggest = output;
    }

    return biggest;
}

void Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)
{
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (!output->isConnected()) {
            output->setEnabled(false);
        }
    }
}

bool Generator::isEmbedded(const QString& name)
{
    QStringList embedded;
    embedded << "LVDS";
    embedded << "IDP";
    embedded << "EDP";

    Q_FOREACH(const QString &pre, embedded) {
        if (name.toUpper().startsWith(pre)) {
            qDebug() << "This is embedded: " << name;
            return true;
        }
    }

    return false;
}

bool Generator::isLaptop()
{
    if (m_forceLaptop) {
        return true;
    }

    return m_device->isLaptop();
}

bool Generator::isLidClosed()
{
    if (m_forceLidClosed) {
        return true;
    }

    return m_device->isLidClosed();
}

bool Generator::isDocked()
{
    if (m_forceDocked) {
        return true;
    }

    return m_device->isDocked();
}

KScreen::Config* Generator::dockedLaptop()
{
    return new KScreen::Config();
}

KScreen::Config* Generator::desktop()
{
    return new KScreen::Config();
}

void Generator::setForceLaptop(bool force)
{
    m_forceLaptop = force;
}

void Generator::setForceLidClosed(bool force)
{
    m_forceLidClosed = force;
}

void Generator::setForceDocked(bool force)
{
    m_forceDocked = force;
}
<|endoftext|>


<commit_before>/// Project specific
// This class
#include <Manager/EntitySpawnManager.hpp>
// Handlers
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/EntityHandlerServer.hpp>
#include <EventHandler/EventHandler.hpp>
// Components
#include <EntityComponent/Components/EntitySpawnerComponent.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/EntityTypeComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
// Events
#include <EventHandler/Events/EntityCreatedEvent.hpp>

/// Engine
// Physics
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
// AI
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include<DoremiEngine/AI/Include/AIModule.hpp>
/// Third party
#include <DirectXMath.h>
using namespace DirectX;

// DEBUG
#include <iostream>
using namespace std;

namespace Doremi
{
    namespace Core
    {
        EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)
            : Manager(p_sharedContext, "EntitySpawnManager")
        {
        }

        EntitySpawnManager::~EntitySpawnManager() {}

        void EntitySpawnManager::Update(double p_dt)
        {
			static int DEBUGcount = 0;
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            // Loop through all entities
            const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
            for(size_t i = 0; i < length; i++)
            {
                // Check that the current entity has the relevant components
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)
                {
                    // We've found an entity spawner
                    EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);
                    // Check if its a timed spawned
                    if(spawnComp->type == SpawnerType::TimedSpawner)
                    {
                        // Update time since last spawn
                        spawnComp->timeSinceLastSpawn += p_dt;
                        // Check if it's time to spawn and if we haven't already spawned the max number
                        if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)
                        {
                            // Reset timer
                            spawnComp->timeSinceLastSpawn = 0;
                            // We should spawn something
                            CreateEntity(spawnComp->entityBlueprint, i);
                            spawnComp->currentNumSpawnedEntities++;
                        }
                        else
                        {
                            // Nothing
                        }
                    }
                    else
                    {
                        // nothing
                    }
                }
            }
        }

        void EntitySpawnManager::OnEvent(Event* p_event) {}

        void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)
        {
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            switch(p_blueprint)
            {
                case Blueprints::EnemyEntity:
                    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    // Spawn inside the spawner. This might be changed in the future
                    XMFLOAT3 spawnPosition = transComp->position;
                    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);
                    int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(newID)->p_materialID;
                    m_sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(newID, matID, spawnPosition, XMFLOAT2(0.1f, 0.5f));

                    Core::PotentialFieldComponent* potentialComponent =
                        Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(newID);
                    potentialComponent->ChargedActor =
                        m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(spawnPosition, -1.0f, 3.0f, false);

                    EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);
                    EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
                    break;
            }
        }
    }
}<commit_msg>EnemySpawner: hax to ensure no spawns before players have joined<commit_after>/// Project specific
// This class
#include <Manager/EntitySpawnManager.hpp>
// Handlers
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/EntityHandlerServer.hpp>
#include <EventHandler/EventHandler.hpp>
#include <PlayerHandler.hpp>
// Components
#include <EntityComponent/Components/EntitySpawnerComponent.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/EntityTypeComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
// Events
#include <EventHandler/Events/EntityCreatedEvent.hpp>

/// Engine
// Physics
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
// AI
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include<DoremiEngine/AI/Include/AIModule.hpp>
/// Third party
#include <DirectXMath.h>
using namespace DirectX;

// DEBUG
#include <iostream>
using namespace std;

namespace Doremi
{
    namespace Core
    {
        EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)
            : Manager(p_sharedContext, "EntitySpawnManager")
        {
        }

        EntitySpawnManager::~EntitySpawnManager() {}

        void EntitySpawnManager::Update(double p_dt)
        {
			static int DEBUGcount = 0;
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            // Loop through all entities
            const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
            for(size_t i = 0; i < length; i++)
            {
                // Check that the current entity has the relevant components
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)
                {
                    // We've found an entity spawner
                    EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);
                    // Check if its a timed spawned
                    if(spawnComp->type == SpawnerType::TimedSpawner)
                    {
                        // Update time since last spawn
                        spawnComp->timeSinceLastSpawn += p_dt;
                        // Check if it's time to spawn and if we haven't already spawned the max number
                        if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)
                        {
                            // Hax to ensure nothing spawns when no players are active, which apparently is a no-can-do
                            if(PlayerHandler::GetInstance()->GetPlayerMap().size() > 0)
                            {
                                // We should spawn something
                                CreateEntity(spawnComp->entityBlueprint, i);
                                spawnComp->currentNumSpawnedEntities++;
                            }
                            // Reset timer
                            spawnComp->timeSinceLastSpawn = 0;
                        }
                        else
                        {
                            // Nothing
                        }
                    }
                    else
                    {
                        // nothing
                    }
                }
            }
        }

        void EntitySpawnManager::OnEvent(Event* p_event) {}

        void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)
        {
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            switch(p_blueprint)
            {
                case Blueprints::EnemyEntity:
                    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    // Spawn inside the spawner. This might be changed in the future
                    XMFLOAT3 spawnPosition = transComp->position;
                    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);
                    int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(newID)->p_materialID;
                    m_sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(newID, matID, spawnPosition, XMFLOAT2(0.1f, 0.5f));

                    Core::PotentialFieldComponent* potentialComponent =
                        Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(newID);
                    potentialComponent->ChargedActor =
                        m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(spawnPosition, -1.0f, 3.0f, false);

                    EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);
                    EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
                    break;
            }
        }
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2006-2010 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 "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif

namespace {

// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
    FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
    FILE_PATH_LITERAL("gcswf32.dll");
#else  // OS_LINUX, etc.
    FILE_PATH_LITERAL("libgcflashplayer.so");
#endif

}  // namespace

namespace chrome {

// Gets the path for internal (or bundled) plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
  // If called from Chrome, get internal plugins from the versioned directory.
  if (mac_util::AmIBundled()) {
    *result = chrome::GetVersionedDirectory();
    DCHECK(!result->empty());
    return true;
  }
  // In tests, just look in the module directory (below).
#endif

  // The rest of the world expects plugins in the module directory.
  return PathService::Get(base::DIR_MODULE, result);
}

bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  FilePath plugin_path =
      CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          switches::kGearsPluginPathOverride);
  *path = plugin_path;
  return !plugin_path.empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifdef NDEBUG
      // Release builds write to the data dir
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      // Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
      if (!PathService::Get(base::DIR_EXE, result))
        return false;
      if (mac_util::AmIBundled()) {
        // If we're called from chrome, dump it beside the app (outside the
        // app bundle), if we're called from a unittest, we'll already
        // outside the bundle so use the exe dir.
        // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
        *result = result->DirName();
        *result = result->DirName();
        *result = result->DirName();
      }
      return true;
#else
      return PathService::Get(base::DIR_EXE, result);
#endif  // defined(OS_MACOSX)
#endif  // NDEBUG
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will not need to create the directory if it does not exist.
  // This flag can be set to true for the cases where we want to create it.
  bool create_dir = false;

  FilePath cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur)) {
        NOTREACHED();
        return false;
      }
      create_dir = true;
      break;
    case chrome::DIR_USER_DOCUMENTS:
      if (!GetUserDocumentsDirectory(&cur))
        return false;
      create_dir = true;
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
      if (!GetUserDownloadsDirectorySafe(&cur))
        return false;
      break;
#else
      // Fall through for all other platforms.
#endif
    case chrome::DIR_DEFAULT_DOWNLOADS:
      if (!GetUserDownloadsDirectory(&cur))
        return false;
      // Do not create the download directory here, we have done it twice now
      // and annoyed a lot of users.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DESKTOP:
      if (!GetUserDesktop(&cur))
        return false;
      break;
    case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
      cur = mac_util::MainAppBundlePath();
      cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
      break;
    case chrome::DIR_SHARED_RESOURCES:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("shared"));
      break;
    case chrome::DIR_BOOKMARK_MANAGER:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager"));
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("inspector"));
      break;
    case chrome::DIR_NET_INTERNALS:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("net_internals"));
      break;
    case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
      // We can't write into the EXE dir on Linux, so keep dictionaries
      // alongside the safe browsing database in the user data dir.
      // And we don't want to write into the bundle on the Mac, so push
      // it to the user data dir there also.
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
#else
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
#endif
      cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DATA_TEMP:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Temp"));
      create_dir = true;
      break;
    case chrome::DIR_INTERNAL_PLUGINS:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(chrome::kLocalStateFilename);
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("script.log"));
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!GetInternalPluginsDirectory(&cur))
          return false;
        cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          cur = cur.Append(FILE_PATH_LITERAL("plugins"));
          cur = cur.Append(FILE_PATH_LITERAL("gears"));
          cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
        }
#else
        // No gears.dll on non-Windows systems.
        return false;
#endif
      }
      break;
    case chrome::FILE_FLASH_PLUGIN:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      cur = cur.Append(kInternalFlashPluginFileName);
      if (!file_util::PathExists(cur))
        return false;
      break;
    case chrome::FILE_PDF_PLUGIN:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
#if defined(OS_WIN)
      cur = cur.Append(FILE_PATH_LITERAL("pdf.dll"));
#elif defined(OS_MACOSX)
      NOTIMPLEMENTED();
      return false;
#else  // Linux and Chrome OS
      cur = cur.Append(FILE_PATH_LITERAL("libpdf.so"));
#endif
      if (!file_util::PathExists(cur))
        return false;
      break;
#if defined(OS_CHROMEOS)
    case chrome::FILE_CHROMEOS_API:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
      cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
      break;
#endif
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      cur = cur.Append(FILE_PATH_LITERAL("data"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("tools"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    default:
      return false;
  }

  if (create_dir && !file_util::PathExists(cur) &&
      !file_util::CreateDirectory(cur))
    return false;

  *result = cur;
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome
<commit_msg>[Mac] stop the output that is slowing down all the tests that seem to walk this code path.<commit_after>// Copyright (c) 2006-2010 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 "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif

namespace {

// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
    FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
    FILE_PATH_LITERAL("gcswf32.dll");
#else  // OS_LINUX, etc.
    FILE_PATH_LITERAL("libgcflashplayer.so");
#endif

}  // namespace

namespace chrome {

// Gets the path for internal (or bundled) plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
  // If called from Chrome, get internal plugins from the versioned directory.
  if (mac_util::AmIBundled()) {
    *result = chrome::GetVersionedDirectory();
    DCHECK(!result->empty());
    return true;
  }
  // In tests, just look in the module directory (below).
#endif

  // The rest of the world expects plugins in the module directory.
  return PathService::Get(base::DIR_MODULE, result);
}

bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  FilePath plugin_path =
      CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          switches::kGearsPluginPathOverride);
  *path = plugin_path;
  return !plugin_path.empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifdef NDEBUG
      // Release builds write to the data dir
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      // Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
      if (!PathService::Get(base::DIR_EXE, result))
        return false;
      if (mac_util::AmIBundled()) {
        // If we're called from chrome, dump it beside the app (outside the
        // app bundle), if we're called from a unittest, we'll already
        // outside the bundle so use the exe dir.
        // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
        *result = result->DirName();
        *result = result->DirName();
        *result = result->DirName();
      }
      return true;
#else
      return PathService::Get(base::DIR_EXE, result);
#endif  // defined(OS_MACOSX)
#endif  // NDEBUG
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will not need to create the directory if it does not exist.
  // This flag can be set to true for the cases where we want to create it.
  bool create_dir = false;

  FilePath cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur)) {
        NOTREACHED();
        return false;
      }
      create_dir = true;
      break;
    case chrome::DIR_USER_DOCUMENTS:
      if (!GetUserDocumentsDirectory(&cur))
        return false;
      create_dir = true;
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
      if (!GetUserDownloadsDirectorySafe(&cur))
        return false;
      break;
#else
      // Fall through for all other platforms.
#endif
    case chrome::DIR_DEFAULT_DOWNLOADS:
      if (!GetUserDownloadsDirectory(&cur))
        return false;
      // Do not create the download directory here, we have done it twice now
      // and annoyed a lot of users.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DESKTOP:
      if (!GetUserDesktop(&cur))
        return false;
      break;
    case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
      cur = mac_util::MainAppBundlePath();
      cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
      break;
    case chrome::DIR_SHARED_RESOURCES:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("shared"));
      break;
    case chrome::DIR_BOOKMARK_MANAGER:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager"));
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("inspector"));
      break;
    case chrome::DIR_NET_INTERNALS:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("net_internals"));
      break;
    case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
      // We can't write into the EXE dir on Linux, so keep dictionaries
      // alongside the safe browsing database in the user data dir.
      // And we don't want to write into the bundle on the Mac, so push
      // it to the user data dir there also.
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
#else
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
#endif
      cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DATA_TEMP:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Temp"));
      create_dir = true;
      break;
    case chrome::DIR_INTERNAL_PLUGINS:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(chrome::kLocalStateFilename);
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("script.log"));
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!GetInternalPluginsDirectory(&cur))
          return false;
        cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          cur = cur.Append(FILE_PATH_LITERAL("plugins"));
          cur = cur.Append(FILE_PATH_LITERAL("gears"));
          cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
        }
#else
        // No gears.dll on non-Windows systems.
        return false;
#endif
      }
      break;
    case chrome::FILE_FLASH_PLUGIN:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      cur = cur.Append(kInternalFlashPluginFileName);
      if (!file_util::PathExists(cur))
        return false;
      break;
    case chrome::FILE_PDF_PLUGIN:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
#if defined(OS_WIN)
      cur = cur.Append(FILE_PATH_LITERAL("pdf.dll"));
#elif defined(OS_MACOSX)
      // http://crbug.com/44900
      return false;
#else  // Linux and Chrome OS
      cur = cur.Append(FILE_PATH_LITERAL("libpdf.so"));
#endif
      if (!file_util::PathExists(cur))
        return false;
      break;
#if defined(OS_CHROMEOS)
    case chrome::FILE_CHROMEOS_API:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
      cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
      break;
#endif
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      cur = cur.Append(FILE_PATH_LITERAL("data"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("tools"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    default:
      return false;
  }

  if (create_dir && !file_util::PathExists(cur) &&
      !file_util::CreateDirectory(cur))
    return false;

  *result = cur;
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DeformableRegistration1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkRawImageIO.h"

//#include "itkImageFileWriter.h"
//#include "itkRawImageWriter.h"

#include "itkRescaleIntensityImageFilter.h"
#include "itkHistogramMatchingImageFilter.h"

#include "itkFEM.h"
#include "itkFEMRegistrationFilter.h"

// Below, we have typedefs that instantiate all necessary classes.
// Here, we instantiate the image type, load type and
// explicitly template the load implementation type.

#define TWOD
//#define THREED

#ifdef TWOD
typedef itk::Image< unsigned char, 2 >                     fileImageType;
typedef itk::Image< float, 2 >                     ImageType;

// We now declare an element type and load implementation pointer for the visitor class.
typedef itk::fem::Element2DC0LinearTriangularMembrane   ElementType2;
typedef itk::fem::Element2DC0LinearQuadrilateralMembrane   ElementType;
#endif

#ifdef THREED
typedef itk::Image< unsigned char, 3 >                     fileImageType;
typedef itk::Image< float, 3 >                     ImageType;
typedef itk::fem::Element3DC0LinearHexahedronMembrane   ElementType;
typedef itk::fem::Element3DC0LinearTetrahedronMembrane   ElementType2;
#endif

typedef itk::fem::ImageMetricLoad<ImageType,ImageType>     ImageLoadType;
template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>;
typedef ElementType::LoadImplementationFunctionPointer     LoadImpFP;
typedef ElementType::LoadType                              ElementLoadType;
typedef ElementType2::LoadImplementationFunctionPointer     LoadImpFP2;
typedef ElementType2::LoadType                              ElementLoadType2;
typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP>
                                                          DispatcherType;
typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2>
                                                          DispatcherType2;

typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType;

int main(int argc, char *argv[])
{
  char *paramname;
  if ( argc < 2 )
  {
    std::cout << "Parameter file name missing" << std::endl;
    std::cout << "Usage: " << argv[0] << " param.file" << std::endl;
    return -1;
  }
  else { paramname=argv[1]; }

  // Register the correct load implementation with the element typed visitor dispatcher.
  {
    ElementType::LoadImplementationFunctionPointer fp =
      &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType::RegisterVisitor((ImageLoadType*)0,fp);
  }
  {
    ElementType2::LoadImplementationFunctionPointer fp =
      &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp);
  }

  // Declare the FEM registration class
  RegistrationType::Pointer X= RegistrationType::New();

  // Attempt to read the parameter file, and exit if an error occurs
  X->SetConfigFileName(paramname);
  if ( !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; }

  // Read the image files
  typedef itk::ImageFileReader< fileImageType >      FileSourceType;
  typedef fileImageType::PixelType PixType;
  const unsigned int ImageDimension=fileImageType::ImageDimension;
  typedef itk::RawImageIO< PixType,ImageDimension>   RawReaderType;

  FileSourceType::Pointer reffilter = FileSourceType::New();
  reffilter->SetFileName( (X->GetReferenceFile()).c_str() );
  FileSourceType::Pointer tarfilter = FileSourceType::New();
  tarfilter->SetFileName( (X->GetTargetFile()).c_str() );

  RawReaderType::Pointer rawReader  = RawReaderType::New();
  rawReader->SetFileDimensionality( ImageDimension );

  ImageType::SizeType ImageSize=X->GetImageSize();
  for (unsigned int ii=0; ii<ImageDimension; ii++)
  {
    unsigned int temp = (unsigned int) ImageSize[ii];
    rawReader->SetDimensions( ii, temp );
  }
  reffilter->SetImageIO( rawReader );
  tarfilter->SetImageIO( rawReader );

  try
  {
    reffilter->Update();
  }
  catch( itk::ExceptionObject & e )
  {
    std::cerr << "Exception caught during reference file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
  }
  try
  {
    tarfilter->Update();
  }
  catch( itk::ExceptionObject & e )
  {
    std::cerr << "Exception caught during target file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
  }

  // Rescale the image intensities so that they fall between 0 and 255
  typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType;
  FilterType::Pointer refrescalefilter = FilterType::New();
  FilterType::Pointer tarrescalefilter = FilterType::New();

  refrescalefilter->SetInput(reffilter->GetOutput());
  tarrescalefilter->SetInput(tarfilter->GetOutput());

  const double desiredMinimum =  0.0;
  const double desiredMaximum =  255.0;

  refrescalefilter->SetOutputMinimum( desiredMinimum );
  refrescalefilter->SetOutputMaximum( desiredMaximum );
  refrescalefilter->UpdateLargestPossibleRegion();
  tarrescalefilter->SetOutputMinimum( desiredMinimum );
  tarrescalefilter->SetOutputMaximum( desiredMaximum );
  tarrescalefilter->UpdateLargestPossibleRegion();

  // Histogram match the images
  typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType;
  HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New();

  IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100);
  IntensityEqualizeFilter->SetNumberOfMatchPoints( 15);
  IntensityEqualizeFilter->ThresholdAtMeanIntensityOn();
  IntensityEqualizeFilter->Update();

  X->SetReferenceImage(refrescalefilter->GetOutput());
  X->SetTargetImage(IntensityEqualizeFilter->GetOutput());

  // Choose the material properties
  itk::fem::MaterialLinearElasticity::Pointer m;
  m = itk::fem::MaterialLinearElasticity::New();
  m->GN = 0;                  // Global number of the material ///
  m->E = X->GetElasticity();  // Young's modulus -- used in the membrane ///
  m->A = 1.0;                 // Cross-sectional area ///
  m->h = 1.0;                 // Thickness ///
  m->I = 1.0;                 // Moment of inertia ///
  m->nu = 0.;                 // Poisson's ratio -- DONT CHOOSE 1.0!!///
  m->RhoC = 1.0;              // Density

  // Create the element type
  ElementType::Pointer e1=ElementType::New();
  e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m );
  X->SetElement(e1);
  X->SetMaterial(m);

  // Register the images
  X->RunRegistration();

  // Output the image resulting from the registration
  X->WriteWarpedImage((X->GetResultsFileName()).c_str());

  // Output the displacement fields associated with the result
  if (X->GetWriteDisplacements()) {
    X->WriteDisplacementField(0);
    X->WriteDisplacementField(1);
#ifdef THREE
    X->WriteDisplacementField(2);
#endif
  }

  // Clean up and exit
  delete m;
  delete e1;
  delete X;

  return 0;
}

<commit_msg>DOC: Example Latex tags added.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DeformableRegistration1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRawImageIO.h"

//#include "itkImageFileWriter.h"
//#include "itkRawImageWriter.h"

#include "itkRescaleIntensityImageFilter.h"
#include "itkHistogramMatchingImageFilter.h"

//  Software Guide : BeginLatex
//
// The first step in implementing a FEM-Based registration method is to include
// the following header files.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkFEM.h"
#include "itkFEMRegistrationFilter.h"
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Below, we have typedefs that instantiate all necessary classes.
//  Here, we instantiate the image type, load type and
//  explicitly template the load implementation type.
//
//  Software Guide : EndLatex

#define TWOD
//#define THREED

#ifdef TWOD
typedef itk::Image< unsigned char, 2 >                     fileImageType;
typedef itk::Image< float, 2 >                     ImageType;

// We now declare an element type and load implementation pointer for the visitor class.
typedef itk::fem::Element2DC0LinearTriangularMembrane   ElementType2;
typedef itk::fem::Element2DC0LinearQuadrilateralMembrane   ElementType;
#endif

#ifdef THREED
typedef itk::Image< unsigned char, 3 >                     fileImageType;
typedef itk::Image< float, 3 >                     ImageType;
typedef itk::fem::Element3DC0LinearHexahedronMembrane   ElementType;
typedef itk::fem::Element3DC0LinearTetrahedronMembrane   ElementType2;
#endif

typedef itk::fem::ImageMetricLoad<ImageType,ImageType>     ImageLoadType;
template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>;
typedef ElementType::LoadImplementationFunctionPointer     LoadImpFP;
typedef ElementType::LoadType                              ElementLoadType;
typedef ElementType2::LoadImplementationFunctionPointer     LoadImpFP2;
typedef ElementType2::LoadType                              ElementLoadType2;
typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP>
                                                          DispatcherType;
typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2>
                                                          DispatcherType2;

typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType;

int main(int argc, char *argv[])
{
  char *paramname;
  if ( argc < 2 )
  {
    std::cout << "Parameter file name missing" << std::endl;
    std::cout << "Usage: " << argv[0] << " param.file" << std::endl;
    return -1;
  }
  else { paramname=argv[1]; }

  // Register the correct load implementation with the element typed visitor dispatcher.
  {
    ElementType::LoadImplementationFunctionPointer fp =
      &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType::RegisterVisitor((ImageLoadType*)0,fp);
  }
  {
    ElementType2::LoadImplementationFunctionPointer fp =
      &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp);
  }

  // Declare the FEM registration class
  RegistrationType::Pointer X= RegistrationType::New();

  // Attempt to read the parameter file, and exit if an error occurs
  X->SetConfigFileName(paramname);
  if ( !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; }

  // Read the image files
  typedef itk::ImageFileReader< fileImageType >      FileSourceType;
  typedef fileImageType::PixelType PixType;
  const unsigned int ImageDimension=fileImageType::ImageDimension;
  typedef itk::RawImageIO< PixType,ImageDimension>   RawReaderType;

  FileSourceType::Pointer reffilter = FileSourceType::New();
  reffilter->SetFileName( (X->GetReferenceFile()).c_str() );
  FileSourceType::Pointer tarfilter = FileSourceType::New();
  tarfilter->SetFileName( (X->GetTargetFile()).c_str() );

  RawReaderType::Pointer rawReader  = RawReaderType::New();
  rawReader->SetFileDimensionality( ImageDimension );

  ImageType::SizeType ImageSize=X->GetImageSize();
  for (unsigned int ii=0; ii<ImageDimension; ii++)
  {
    unsigned int temp = (unsigned int) ImageSize[ii];
    rawReader->SetDimensions( ii, temp );
  }
  reffilter->SetImageIO( rawReader );
  tarfilter->SetImageIO( rawReader );

  try
  {
    reffilter->Update();
  }
  catch( itk::ExceptionObject & e )
  {
    std::cerr << "Exception caught during reference file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
  }
  try
  {
    tarfilter->Update();
  }
  catch( itk::ExceptionObject & e )
  {
    std::cerr << "Exception caught during target file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
  }

  // Rescale the image intensities so that they fall between 0 and 255
  typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType;
  FilterType::Pointer refrescalefilter = FilterType::New();
  FilterType::Pointer tarrescalefilter = FilterType::New();

  refrescalefilter->SetInput(reffilter->GetOutput());
  tarrescalefilter->SetInput(tarfilter->GetOutput());

  const double desiredMinimum =  0.0;
  const double desiredMaximum =  255.0;

  refrescalefilter->SetOutputMinimum( desiredMinimum );
  refrescalefilter->SetOutputMaximum( desiredMaximum );
  refrescalefilter->UpdateLargestPossibleRegion();
  tarrescalefilter->SetOutputMinimum( desiredMinimum );
  tarrescalefilter->SetOutputMaximum( desiredMaximum );
  tarrescalefilter->UpdateLargestPossibleRegion();

  // Histogram match the images
  typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType;
  HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New();

  IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100);
  IntensityEqualizeFilter->SetNumberOfMatchPoints( 15);
  IntensityEqualizeFilter->ThresholdAtMeanIntensityOn();
  IntensityEqualizeFilter->Update();

  X->SetReferenceImage(refrescalefilter->GetOutput());
  X->SetTargetImage(IntensityEqualizeFilter->GetOutput());

  // Choose the material properties
  itk::fem::MaterialLinearElasticity::Pointer m;
  m = itk::fem::MaterialLinearElasticity::New();
  m->GN = 0;                  // Global number of the material ///
  m->E = X->GetElasticity();  // Young's modulus -- used in the membrane ///
  m->A = 1.0;                 // Cross-sectional area ///
  m->h = 1.0;                 // Thickness ///
  m->I = 1.0;                 // Moment of inertia ///
  m->nu = 0.;                 // Poisson's ratio -- DONT CHOOSE 1.0!!///
  m->RhoC = 1.0;              // Density

  // Create the element type
  ElementType::Pointer e1=ElementType::New();
  e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m );
  X->SetElement(e1);
  X->SetMaterial(m);

  // Register the images
  X->RunRegistration();

  // Output the image resulting from the registration
  X->WriteWarpedImage((X->GetResultsFileName()).c_str());

  // Output the displacement fields associated with the result
  if (X->GetWriteDisplacements()) {
    X->WriteDisplacementField(0);
    X->WriteDisplacementField(1);
#ifdef THREE
    X->WriteDisplacementField(2);
#endif
  }

  // Clean up and exit
  delete m;
  delete e1;
  delete X;

  return 0;
}

<|endoftext|>


<commit_before>//===--- DexIndex.cpp - Dex Symbol Index Implementation ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "DexIndex.h"
#include "../../FuzzyMatch.h"
#include "../../Logger.h"
#include <algorithm>
#include <queue>

namespace clang {
namespace clangd {
namespace dex {

namespace {

// Returns the tokens which are given symbol's characteristics. Currently, the
// generated tokens only contain fuzzy matching trigrams and symbol's scope,
// but in the future this will also return path proximity tokens and other
// types of tokens such as symbol type (if applicable).
// Returns the tokens which are given symbols's characteristics. For example,
// trigrams and scopes.
// FIXME(kbobyrev): Support more token types:
// * Path proximity
// * Types
std::vector<Token> generateSearchTokens(const Symbol &Sym) {
  std::vector<Token> Result = generateIdentifierTrigrams(Sym.Name);
  Result.push_back(Token(Token::Kind::Scope, Sym.Scope));
  return Result;
}

} // namespace

void DexIndex::build(std::shared_ptr<std::vector<const Symbol *>> Syms) {
  llvm::DenseMap<SymbolID, const Symbol *> TempLookupTable;
  llvm::DenseMap<const Symbol *, float> TempSymbolQuality;
  for (const Symbol *Sym : *Syms) {
    TempLookupTable[Sym->ID] = Sym;
    TempSymbolQuality[Sym] = quality(*Sym);
  }

  // Symbols are sorted by symbol qualities so that items in the posting lists
  // are stored in the descending order of symbol quality.
  std::sort(begin(*Syms), end(*Syms),
            [&](const Symbol *LHS, const Symbol *RHS) {
              return TempSymbolQuality[LHS] > TempSymbolQuality[RHS];
            });
  llvm::DenseMap<Token, PostingList> TempInvertedIndex;
  // Populate TempInvertedIndex with posting lists for index symbols.
  for (DocID SymbolRank = 0; SymbolRank < Syms->size(); ++SymbolRank) {
    const auto *Sym = (*Syms)[SymbolRank];
    for (const auto &Token : generateSearchTokens(*Sym))
      TempInvertedIndex[Token].push_back(SymbolRank);
  }

  {
    std::lock_guard<std::mutex> Lock(Mutex);

    // Replace outdated index with the new one.
    LookupTable = std::move(TempLookupTable);
    Symbols = std::move(Syms);
    InvertedIndex = std::move(TempInvertedIndex);
    SymbolQuality = std::move(TempSymbolQuality);
  }
}

std::unique_ptr<SymbolIndex> DexIndex::build(SymbolSlab Slab) {
  auto Idx = llvm::make_unique<MemIndex>();
  Idx->build(getSymbolsFromSlab(std::move(Slab)));
  return std::move(Idx);
}

/// Constructs iterators over tokens extracted from the query and exhausts it
/// while applying Callback to each symbol in the order of decreasing quality
/// of the matched symbols.
bool DexIndex::fuzzyFind(
    const FuzzyFindRequest &Req,
    llvm::function_ref<void(const Symbol &)> Callback) const {
  assert(!StringRef(Req.Query).contains("::") &&
         "There must be no :: in query.");
  FuzzyMatcher Filter(Req.Query);
  bool More = false;

  std::vector<std::unique_ptr<Iterator>> TopLevelChildren;
  const auto TrigramTokens = generateIdentifierTrigrams(Req.Query);

  {
    std::lock_guard<std::mutex> Lock(Mutex);

    // Generate query trigrams and construct AND iterator over all query
    // trigrams.
    std::vector<std::unique_ptr<Iterator>> TrigramIterators;
    for (const auto &Trigram : TrigramTokens) {
      const auto It = InvertedIndex.find(Trigram);
      if (It != InvertedIndex.end())
        TrigramIterators.push_back(create(It->second));
    }
    if (!TrigramIterators.empty())
      TopLevelChildren.push_back(createAnd(move(TrigramIterators)));

    // Generate scope tokens for search query.
    std::vector<std::unique_ptr<Iterator>> ScopeIterators;
    for (const auto &Scope : Req.Scopes) {
      const auto It = InvertedIndex.find(Token(Token::Kind::Scope, Scope));
      if (It != InvertedIndex.end())
        ScopeIterators.push_back(create(It->second));
    }
    // Add OR iterator for scopes if there are any Scope Iterators.
    if (!ScopeIterators.empty())
      TopLevelChildren.push_back(createOr(move(ScopeIterators)));

    // Use TRUE iterator if both trigrams and scopes from the query are not
    // present in the symbol index.
    auto QueryIterator = TopLevelChildren.empty()
                             ? createTrue(Symbols->size())
                             : createAnd(move(TopLevelChildren));
    // Retrieve more items than it was requested: some of  the items with high
    // final score might not be retrieved otherwise.
    // FIXME(kbobyrev): Pre-scoring retrieval threshold should be adjusted as
    // using 100x of the requested number might not be good in practice, e.g.
    // when the requested number of items is small.
    const unsigned ItemsToRetrieve = 100 * Req.MaxCandidateCount;
    std::vector<DocID> SymbolDocIDs = consume(*QueryIterator, ItemsToRetrieve);

    // Retrieve top Req.MaxCandidateCount items.
    std::priority_queue<std::pair<float, const Symbol *>> Top;
    for (const auto &SymbolDocID : SymbolDocIDs) {
      const auto *Sym = (*Symbols)[SymbolDocID];
      const llvm::Optional<float> Score = Filter.match(Sym->Name);
      if (!Score)
        continue;
      // Multiply score by a negative factor so that Top stores items with the
      // highest actual score.
      Top.emplace(-(*Score) * SymbolQuality.find(Sym)->second, Sym);
      if (Top.size() > Req.MaxCandidateCount) {
        More = true;
        Top.pop();
      }
    }

    // Apply callback to the top Req.MaxCandidateCount items.
    for (; !Top.empty(); Top.pop())
      Callback(*Top.top().second);
  }

  return More;
}

void DexIndex::lookup(const LookupRequest &Req,
                      llvm::function_ref<void(const Symbol &)> Callback) const {
  std::lock_guard<std::mutex> Lock(Mutex);
  for (const auto &ID : Req.IDs) {
    auto I = LookupTable.find(ID);
    if (I != LookupTable.end())
      Callback(*I->second);
  }
}

void DexIndex::findOccurrences(
    const OccurrencesRequest &Req,
    llvm::function_ref<void(const SymbolOccurrence &)> Callback) const {
  log("findOccurrences is not implemented.");
}

} // namespace dex
} // namespace clangd
} // namespace clang
<commit_msg>[clangd] Cleanup after D50897<commit_after>//===--- DexIndex.cpp - Dex Symbol Index Implementation ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "DexIndex.h"
#include "../../FuzzyMatch.h"
#include "../../Logger.h"
#include <algorithm>
#include <queue>

namespace clang {
namespace clangd {
namespace dex {

namespace {

// Returns the tokens which are given symbol's characteristics. Currently, the
// generated tokens only contain fuzzy matching trigrams and symbol's scope,
// but in the future this will also return path proximity tokens and other
// types of tokens such as symbol type (if applicable).
// Returns the tokens which are given symbols's characteristics. For example,
// trigrams and scopes.
// FIXME(kbobyrev): Support more token types:
// * Path proximity
// * Types
std::vector<Token> generateSearchTokens(const Symbol &Sym) {
  std::vector<Token> Result = generateIdentifierTrigrams(Sym.Name);
  Result.push_back(Token(Token::Kind::Scope, Sym.Scope));
  return Result;
}

} // namespace

void DexIndex::build(std::shared_ptr<std::vector<const Symbol *>> Syms) {
  llvm::DenseMap<SymbolID, const Symbol *> TempLookupTable;
  llvm::DenseMap<const Symbol *, float> TempSymbolQuality;
  for (const Symbol *Sym : *Syms) {
    TempLookupTable[Sym->ID] = Sym;
    TempSymbolQuality[Sym] = quality(*Sym);
  }

  // Symbols are sorted by symbol qualities so that items in the posting lists
  // are stored in the descending order of symbol quality.
  std::sort(begin(*Syms), end(*Syms),
            [&](const Symbol *LHS, const Symbol *RHS) {
              return TempSymbolQuality[LHS] > TempSymbolQuality[RHS];
            });
  llvm::DenseMap<Token, PostingList> TempInvertedIndex;
  // Populate TempInvertedIndex with posting lists for index symbols.
  for (DocID SymbolRank = 0; SymbolRank < Syms->size(); ++SymbolRank) {
    const auto *Sym = (*Syms)[SymbolRank];
    for (const auto &Token : generateSearchTokens(*Sym))
      TempInvertedIndex[Token].push_back(SymbolRank);
  }

  {
    std::lock_guard<std::mutex> Lock(Mutex);

    // Replace outdated index with the new one.
    LookupTable = std::move(TempLookupTable);
    Symbols = std::move(Syms);
    InvertedIndex = std::move(TempInvertedIndex);
    SymbolQuality = std::move(TempSymbolQuality);
  }
}

std::unique_ptr<SymbolIndex> DexIndex::build(SymbolSlab Slab) {
  auto Idx = llvm::make_unique<DexIndex>();
  Idx->build(getSymbolsFromSlab(std::move(Slab)));
  return std::move(Idx);
}

/// Constructs iterators over tokens extracted from the query and exhausts it
/// while applying Callback to each symbol in the order of decreasing quality
/// of the matched symbols.
bool DexIndex::fuzzyFind(
    const FuzzyFindRequest &Req,
    llvm::function_ref<void(const Symbol &)> Callback) const {
  assert(!StringRef(Req.Query).contains("::") &&
         "There must be no :: in query.");
  FuzzyMatcher Filter(Req.Query);
  bool More = false;

  std::vector<std::unique_ptr<Iterator>> TopLevelChildren;
  const auto TrigramTokens = generateIdentifierTrigrams(Req.Query);

  {
    std::lock_guard<std::mutex> Lock(Mutex);

    // Generate query trigrams and construct AND iterator over all query
    // trigrams.
    std::vector<std::unique_ptr<Iterator>> TrigramIterators;
    for (const auto &Trigram : TrigramTokens) {
      const auto It = InvertedIndex.find(Trigram);
      if (It != InvertedIndex.end())
        TrigramIterators.push_back(create(It->second));
    }
    if (!TrigramIterators.empty())
      TopLevelChildren.push_back(createAnd(move(TrigramIterators)));

    // Generate scope tokens for search query.
    std::vector<std::unique_ptr<Iterator>> ScopeIterators;
    for (const auto &Scope : Req.Scopes) {
      const auto It = InvertedIndex.find(Token(Token::Kind::Scope, Scope));
      if (It != InvertedIndex.end())
        ScopeIterators.push_back(create(It->second));
    }
    // Add OR iterator for scopes if there are any Scope Iterators.
    if (!ScopeIterators.empty())
      TopLevelChildren.push_back(createOr(move(ScopeIterators)));

    // Use TRUE iterator if both trigrams and scopes from the query are not
    // present in the symbol index.
    auto QueryIterator = TopLevelChildren.empty()
                             ? createTrue(Symbols->size())
                             : createAnd(move(TopLevelChildren));
    // Retrieve more items than it was requested: some of  the items with high
    // final score might not be retrieved otherwise.
    // FIXME(kbobyrev): Pre-scoring retrieval threshold should be adjusted as
    // using 100x of the requested number might not be good in practice, e.g.
    // when the requested number of items is small.
    const unsigned ItemsToRetrieve = 100 * Req.MaxCandidateCount;
    std::vector<DocID> SymbolDocIDs = consume(*QueryIterator, ItemsToRetrieve);

    // Retrieve top Req.MaxCandidateCount items.
    std::priority_queue<std::pair<float, const Symbol *>> Top;
    for (const auto &SymbolDocID : SymbolDocIDs) {
      const auto *Sym = (*Symbols)[SymbolDocID];
      const llvm::Optional<float> Score = Filter.match(Sym->Name);
      if (!Score)
        continue;
      // Multiply score by a negative factor so that Top stores items with the
      // highest actual score.
      Top.emplace(-(*Score) * SymbolQuality.find(Sym)->second, Sym);
      if (Top.size() > Req.MaxCandidateCount) {
        More = true;
        Top.pop();
      }
    }

    // Apply callback to the top Req.MaxCandidateCount items.
    for (; !Top.empty(); Top.pop())
      Callback(*Top.top().second);
  }

  return More;
}

void DexIndex::lookup(const LookupRequest &Req,
                      llvm::function_ref<void(const Symbol &)> Callback) const {
  std::lock_guard<std::mutex> Lock(Mutex);
  for (const auto &ID : Req.IDs) {
    auto I = LookupTable.find(ID);
    if (I != LookupTable.end())
      Callback(*I->second);
  }
}

void DexIndex::findOccurrences(
    const OccurrencesRequest &Req,
    llvm::function_ref<void(const SymbolOccurrence &)> Callback) const {
  log("findOccurrences is not implemented.");
}

} // namespace dex
} // namespace clangd
} // namespace clang
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief A Scheduler interface
 *
 * @details
 *
 * @authors Théo de la Hogue
 *
 * @copyright © 2013, Théo de la Hogue @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "Scheduler.h"

#define thisTTClass		Scheduler

/****************************************************************************************************/

Scheduler::Scheduler(TTValue& arguments) :
TTObjectBase(arguments),
mDuration(0.),
mOffset(0.),
mSpeed(1.),
mRunning(NO),
mPaused(NO),
mProgression(0.),
mRealTime(0.),
mCallback(NULL),
mBaton(NULL)
{
    mCallback = SchedulerProgressionCallback((TTPtr)arguments[0]);
    mBaton = arguments[1];

	addAttribute(Name, kTypeSymbol);
	addAttributeProperty(Name, readOnly, YES);

	addAttribute(Version, kTypeSymbol);
	addAttributeProperty(Version, readOnly, YES);

	addAttribute(Author, kTypeSymbol);
	addAttributeProperty(Author, readOnly, YES);

    addAttributeWithSetter(Duration, kTypeFloat64);
    addAttributeWithSetter(Offset, kTypeFloat64);
    addAttributeWithSetter(Speed, kTypeFloat64);

	addAttribute(Stretchable, kTypeBoolean);
	addAttributeProperty(Stretchable, readOnly, YES);

	addAttribute(Running, kTypeBoolean);
    addAttributeProperty(Running, readOnly, YES);

    addAttribute(Paused, kTypeBoolean);
    addAttributeProperty(Paused, readOnly, YES);

    addAttribute(Progression, kTypeFloat64);
    addAttributeProperty(Progression, readOnly, YES);

    addAttribute(RealTime, kTypeFloat64);
    addAttributeProperty(RealTime, readOnly, YES);

	addMessage(Go);
	addMessage(Stop);
    addMessage(Pause);
    addMessage(Resume);
	addMessage(Tick);

    // Cache some attributes for high speed notification feedbacks
    this->findAttribute(TTSymbol("duration"), &durationAttribute);
    this->findAttribute(TTSymbol("offset"), &offsetAttribute);
    this->findAttribute(TTSymbol("speed"), &speedAttribute);

    this->findAttribute(TTSymbol("running"), &runningAttribute);
    this->findAttribute(TTSymbol("progression"), &progressionAttribute);
    this->findAttribute(TTSymbol("realTime"), &realTimeAttribute);
}

Scheduler::~Scheduler()
{
    ;
}

TTErr Scheduler::getParameterNames(TTValue& value)
{
	TTValue		attributeNames;
	TTSymbol	attributeName;

	// filter all default attributes (Name, Version, Author, Stretchable, Running, ...)
	this->getAttributeNames(attributeNames);

	value.clear();
	for (TTUInt8 i = 0; i < attributeNames.size(); i++) {
		attributeName = attributeNames[0];

		if (attributeName == TTSymbol("name")           ||
			attributeName == TTSymbol("version")        ||
			attributeName == TTSymbol("author")         ||
			attributeName == TTSymbol("stretchable")    ||
            attributeName == TTSymbol("duration")       ||
            attributeName == TTSymbol("offset")         ||
            attributeName == TTSymbol("speed")          ||
            attributeName == TTSymbol("running")        ||
            attributeName == TTSymbol("progression")    ||
            attributeName == TTSymbol("realTime"))
			continue;

		value.append(attributeName);
	}

	return kTTErrNone;
}

TTErr Scheduler::setDuration(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            Stop();

            mDuration = value[0];

            durationAttribute->sendNotification(kTTSym_notify, mDuration);           // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

TTErr Scheduler::setOffset(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            mOffset = value[0];

            offsetAttribute->sendNotification(kTTSym_notify, mOffset);             // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

TTErr Scheduler::setSpeed(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            mSpeed = value[0];

            speedAttribute->sendNotification(kTTSym_notify, mSpeed);             // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

/***************************************************************************

	SchedulerLib

 ***************************************************************************/

TTErr SchedulerLib::createScheduler(const TTSymbol SchedulerName, SchedulerPtr *returnedScheduler, SchedulerProgressionCallback aCallback, TTPtr aBaton)
{
	TTValue args;

    // prepare arguments
	args.append((TTPtr)aCallback);
    args.append(aBaton);

	// These should be alphabetized
	if (SchedulerName == TTSymbol("Max"))
		return TTObjectBaseInstantiate(TTSymbol("Max"), (TTObjectBasePtr*)returnedScheduler, args);
    else if (SchedulerName == TTSymbol("System"))
		return TTObjectBaseInstantiate(TTSymbol("System"), (TTObjectBasePtr*)returnedScheduler, args);

	TTLogError("Jamoma SchedulerLib : Invalid Scheduler ( %s ) specified", SchedulerName.c_str());
	return kTTErrValueNotFound;
}

void SchedulerLib::getSchedulerNames(TTValue& SchedulerNames)
{
	SchedulerNames.clear();
	SchedulerNames.append(TTSymbol("Max"));
	SchedulerNames.append(TTSymbol("System"));
}

<commit_msg>Removing the Stop from the setDuration accessor<commit_after>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief A Scheduler interface
 *
 * @details
 *
 * @authors Théo de la Hogue
 *
 * @copyright © 2013, Théo de la Hogue @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "Scheduler.h"

#define thisTTClass		Scheduler

/****************************************************************************************************/

Scheduler::Scheduler(TTValue& arguments) :
TTObjectBase(arguments),
mDuration(0.),
mOffset(0.),
mSpeed(1.),
mRunning(NO),
mPaused(NO),
mProgression(0.),
mRealTime(0.),
mCallback(NULL),
mBaton(NULL)
{
    mCallback = SchedulerProgressionCallback((TTPtr)arguments[0]);
    mBaton = arguments[1];

	addAttribute(Name, kTypeSymbol);
	addAttributeProperty(Name, readOnly, YES);

	addAttribute(Version, kTypeSymbol);
	addAttributeProperty(Version, readOnly, YES);

	addAttribute(Author, kTypeSymbol);
	addAttributeProperty(Author, readOnly, YES);

    addAttributeWithSetter(Duration, kTypeFloat64);
    addAttributeWithSetter(Offset, kTypeFloat64);
    addAttributeWithSetter(Speed, kTypeFloat64);

	addAttribute(Stretchable, kTypeBoolean);
	addAttributeProperty(Stretchable, readOnly, YES);

	addAttribute(Running, kTypeBoolean);
    addAttributeProperty(Running, readOnly, YES);

    addAttribute(Paused, kTypeBoolean);
    addAttributeProperty(Paused, readOnly, YES);

    addAttribute(Progression, kTypeFloat64);
    addAttributeProperty(Progression, readOnly, YES);

    addAttribute(RealTime, kTypeFloat64);
    addAttributeProperty(RealTime, readOnly, YES);

	addMessage(Go);
	addMessage(Stop);
    addMessage(Pause);
    addMessage(Resume);
	addMessage(Tick);

    // Cache some attributes for high speed notification feedbacks
    this->findAttribute(TTSymbol("duration"), &durationAttribute);
    this->findAttribute(TTSymbol("offset"), &offsetAttribute);
    this->findAttribute(TTSymbol("speed"), &speedAttribute);

    this->findAttribute(TTSymbol("running"), &runningAttribute);
    this->findAttribute(TTSymbol("progression"), &progressionAttribute);
    this->findAttribute(TTSymbol("realTime"), &realTimeAttribute);
}

Scheduler::~Scheduler()
{
    ;
}

TTErr Scheduler::getParameterNames(TTValue& value)
{
	TTValue		attributeNames;
	TTSymbol	attributeName;

	// filter all default attributes (Name, Version, Author, Stretchable, Running, ...)
	this->getAttributeNames(attributeNames);

	value.clear();
	for (TTUInt8 i = 0; i < attributeNames.size(); i++) {
		attributeName = attributeNames[0];

		if (attributeName == TTSymbol("name")           ||
			attributeName == TTSymbol("version")        ||
			attributeName == TTSymbol("author")         ||
			attributeName == TTSymbol("stretchable")    ||
            attributeName == TTSymbol("duration")       ||
            attributeName == TTSymbol("offset")         ||
            attributeName == TTSymbol("speed")          ||
            attributeName == TTSymbol("running")        ||
            attributeName == TTSymbol("progression")    ||
            attributeName == TTSymbol("realTime"))
			continue;

		value.append(attributeName);
	}

	return kTTErrNone;
}

TTErr Scheduler::setDuration(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            mDuration = value[0];

            durationAttribute->sendNotification(kTTSym_notify, mDuration);           // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

TTErr Scheduler::setOffset(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            mOffset = value[0];

            offsetAttribute->sendNotification(kTTSym_notify, mOffset);             // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

TTErr Scheduler::setSpeed(const TTValue& value)
{
    if (value.size() == 1) {

        if (value[0].type() == kTypeFloat64) {

            mSpeed = value[0];

            speedAttribute->sendNotification(kTTSym_notify, mSpeed);             // we use kTTSym_notify because we know that observers are TTCallback

            return kTTErrNone;
        }
    }

    return kTTErrGeneric;
}

/***************************************************************************

	SchedulerLib

 ***************************************************************************/

TTErr SchedulerLib::createScheduler(const TTSymbol SchedulerName, SchedulerPtr *returnedScheduler, SchedulerProgressionCallback aCallback, TTPtr aBaton)
{
	TTValue args;

    // prepare arguments
	args.append((TTPtr)aCallback);
    args.append(aBaton);

	// These should be alphabetized
	if (SchedulerName == TTSymbol("Max"))
		return TTObjectBaseInstantiate(TTSymbol("Max"), (TTObjectBasePtr*)returnedScheduler, args);
    else if (SchedulerName == TTSymbol("System"))
		return TTObjectBaseInstantiate(TTSymbol("System"), (TTObjectBasePtr*)returnedScheduler, args);

	TTLogError("Jamoma SchedulerLib : Invalid Scheduler ( %s ) specified", SchedulerName.c_str());
	return kTTErrValueNotFound;
}

void SchedulerLib::getSchedulerNames(TTValue& SchedulerNames)
{
	SchedulerNames.clear();
	SchedulerNames.append(TTSymbol("Max"));
	SchedulerNames.append(TTSymbol("System"));
}

<|endoftext|>


<commit_before><commit_msg>Fix Vulkan memory leak<commit_after><|endoftext|>


<commit_before><commit_msg>Require semicolons after declarations<commit_after><|endoftext|>


<commit_before>// rm -f galice.root ;  aliroot -l -q -b $ALICE_SOURCE/HLT/global/physics/macros/testConfigOnlineCalib.C $ALICE_ROOT/HLT/exa/recraw-local.C'("raw.root","local:///opt/HLT-DEV/HCDB", 23, 23, "HLT", "chains=RootWriter ignore-hltout")'

void testConfigOnlineCalib()
{
	AliHLTSystem* pHLT = AliHLTPluginBase::GetInstance();

	if (1)
	{
		AliHLTConfiguration calib1("myCalibration1", "HLTAnalysisManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3 -MinTracks=5 -QueueDepth=0 AddTaskMacro=$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C(\"TPCCalib:CalibTimeDrift\")");
//		AliHLTConfiguration calib2("myCalibration2", "TPCCalibManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3");
		AliHLTConfiguration calibmerge("myCalibrationMerger" , "RootObjectMerger" , "myCalibration1" , "-QueueDepth 0 -cumulative");
		AliHLTConfiguration preproc("myTPCOfflinePreprocessor" , "TPCOfflinePreprocessorWrapper" , "myCalibrationMerger" , "-QueueDepth 0");

		AliHLTConfiguration eventTrigger("myCustomTrigger", "Zero", "TPC-DP", "");

		AliHLTConfiguration zmqsink("myZMQsink", "ZMQsink", "myTPCOfflinePreprocessor", "out=PUB@tcp://*:60203");
		AliHLTConfiguration zmqsource("myZMQsource", "ZMQsource", "myCustomTrigger", "in=SUB+tcp://localhost:60203");

		AliHLTConfiguration mapPrepare1("myMapPrepare1", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 0 -MaxSector 35 -NoInitialObject");
		AliHLTConfiguration mapPrepare2("myMapPrepare2", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 36 -MaxSector 71 -NoInitialObject");
		AliHLTConfiguration mapPreparemerge("myMapPrepare", "RootObjectMerger", "myMapPrepare1 myMapPrepare2", "-QueueDepth 0");

		TString clusterTransformation = "TPC-ClusterTransformation";
		AliHLTConfiguration overrideClusterTransformation(clusterTransformation.Data(), "TPCClusterTransformation", "TPC-HWCFDecoder myMapPrepare", "-update-object-on-the-fly -offline-mode");

		AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalibrationMerger myTPCOfflinePreprocessor myZMQsink GLOBAL-esd-converter", "-directory testDir -datafile test.root");
	}
	else if (0)
	{
		AliHLTConfiguration calib("myCalib", "TPCCalibManagerComponent", "GLOBAL-esd-converter", "");
		AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalib", "-directory testDir -datafile test-calib.root");
	}
	else
	{
		AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "GLOBAL-esd-converter", "-directory testDir -datafile test-esdevent.root");
	}
}
<commit_msg>Cleanup test online calib macro<commit_after>// rm -f galice.root ;  aliroot -l -q -b $ALICE_SOURCE/HLT/global/physics/macros/testConfigOnlineCalib.C $ALICE_ROOT/HLT/exa/recraw-local.C'("raw.root","local:///opt/HLT-DEV/HCDB", 23, 23, "HLT", "chains=RootWriter ignore-hltout")'

void testConfigOnlineCalib()
{
	AliHLTPluginBase::InitInstance();

	AliHLTConfiguration calib1("myCalibration", "HLTAnalysisManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3 -MinTracks=5 -QueueDepth=0 AddTaskMacro=$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C(\"TPCCalib:CalibTimeDrift\")");
/*	AliHLTConfiguration calibmerge("myCalibrationMerger" , "RootObjectMerger" , "myCalibration" , "-QueueDepth 0 -cumulative");
	AliHLTConfiguration preproc("myTPCOfflinePreprocessor" , "TPCOfflinePreprocessorWrapper" , "myCalibrationMerger" , "-QueueDepth 0");

	AliHLTConfiguration eventTrigger("myCustomTrigger", "Zero", "TPC-DP", "");

	AliHLTConfiguration zmqsink("myZMQsink", "ZMQsink", "myTPCOfflinePreprocessor", "out=PUB@tcp://*:60203");
	AliHLTConfiguration zmqsource("myZMQsource", "ZMQsource", "myCustomTrigger", "in=SUB+tcp://localhost:60203");

	AliHLTConfiguration mapPrepare1("myMapPrepare1", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 0 -MaxSector 35 -NoInitialObject");
	AliHLTConfiguration mapPrepare2("myMapPrepare2", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 36 -MaxSector 71 -NoInitialObject");
	AliHLTConfiguration mapPreparemerge("myMapPrepare", "RootObjectMerger", "myMapPrepare1 myMapPrepare2", "-QueueDepth 0");*/

	TString clusterTransformation = "TPC-ClusterTransformation";
	AliHLTConfiguration overrideClusterTransformation(clusterTransformation.Data(), "TPCClusterTransformation", "TPC-HWCFDecoder", "-update-object-on-the-fly");
	/*AliHLTConfiguration overrideClusterTransformation(clusterTransformation.Data(), "TPCClusterTransformation", "TPC-HWCFDecoder myMapPrepare", "-update-object-on-the-fly");*/

	AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalibration GLOBAL-esd-converter", "-directory testDir -datafile test.root");
	/*AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalibrationMerger myTPCOfflinePreprocessor myZMQsink GLOBAL-esd-converter", "-directory testDir -datafile test.root");*/
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <functional>

#include "board/full_board.h"
#include "game/game_info.h"
#include "game/sgf_game.h"
#include "def.h"
#include "util/cxxopts.hpp"
#include "util/SGFParser.h"
#include "deep_learning/sample.h"
#include "deep_learning/engine.h"
#include "deep_learning/cnn/graph_builder.h"
#include "N3LDG.h"

using namespace foolgo;
using namespace std;
using namespace cxxopts;

int main(int argc, char *argv[]) {
  uint32_t seed = GetTimeSeed();
  cout << "seed:" << seed << endl;
  ZobHasher<19>::Init(seed);
  Options options("FoolGo", "A montecarlo Go A.I.");
  options.add_options()
    ("s,sgf", "sgf file name", cxxopts::value<string>());
  auto args = options.parse(argc, argv);
  string sgf_file_name = args["sgf"].as<string>();

  SGFParser parser;
  vector<string> strs = parser.chop_all(sgf_file_name);
  cout << strs.size() << endl;
  vector<GameInfo> game_infos = parser.get_game_infos(sgf_file_name);
  vector<Sample<19>> samples;

  int iter = 0;
  for (const GameInfo &game_info : game_infos) {
    auto sgf_game = SgfGame<19>::BuildSgfGame(game_info, &samples);
    sgf_game->Run();
    if (++iter % 100 == 0) {
      cout << "iter:" << iter << "sample count:" << samples.size() << endl;
      break;
    }
  }

  return 0;
}
<commit_msg>some change<commit_after>#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <functional>

#include "board/full_board.h"
#include "game/game_info.h"
#include "game/sgf_game.h"
#include "def.h"
#include "util/cxxopts.hpp"
#include "util/SGFParser.h"
#include "util/rand.h"
#include "deep_learning/sample.h"
#include "deep_learning/engine.h"
#include "deep_learning/cnn/graph_builder.h"
#include "N3LDG.h"

using namespace foolgo;
using namespace std;
using namespace cxxopts;

int main(int argc, char *argv[]) {
  uint32_t seed = GetTimeSeed();
  cout << "seed:" << seed << endl;
  ZobHasher<19>::Init(seed);
  Options options("FoolGo", "A montecarlo Go A.I.");
  options.add_options()
    ("s,sgf", "sgf file name", cxxopts::value<string>());
  auto args = options.parse(argc, argv);
  string sgf_file_name = args["sgf"].as<string>();

  SGFParser parser;
  vector<string> strs = parser.chop_all(sgf_file_name);
  cout << strs.size() << endl;
  vector<GameInfo> game_infos = parser.get_game_infos(sgf_file_name);

  int iter = 0;
  cout << "game count:" << game_infos.size() << endl;
  vector<Sample<19>> samples;

  for (int i=0; i < 1000; ++i) {
    int rand_game_i = Rand(game_infos.size() - 1, seed);
    const GameInfo &game_info = game_infos.at(rand_game_i);
    vector<Sample<19>> single_game_samples;
    auto game = SgfGame<19>::BuildSgfGame(game_info, &single_game_samples);
    game->Run();
    int rand_sample_i = Rand(game_info.moves.size() - 1, seed);
    samples.push_back(single_game_samples.at(rand_sample_i));
  }

  cout << "samples count:" << samples.size() << endl;

  Engine engine;

  return 0;
}
<|endoftext|>