text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingController.h"
#include "NavRoutingViewOpenMessage.h"
#include "SearchResultModel.h"
#include "NavRoutingStartLocationSetMessage.h"
#include "NavRoutingStartLocationClearedMessage.h"
#include "NavRoutingEndLocationSetMessage.h"
#include "NavRoutingEndLocationClearedMessage.h"
#include "NavRoutingRouteChangedMessage.h"
#include "NavRoutingRouteClearedMessage.h"
#include "NavRoutingCurrentDirectionSetMessage.h"
#include "NavRoutingCurrentDirectionUpdatedMessage.h"
#include "NavRoutingSelectedDirectionSetMessage.h"
#include "NavRoutingRemainingRouteDurationSetMessage.h"
#include "NavRoutingModeSetMessage.h"
#include "INavTurnByTurnModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IAlertBoxFactory.h"
#include "IWorldPinsService.h"
#include "NavRouteInteriorModelHelper.h"
#include "NavRoutingShowRerouteDialogMessage.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
NavRoutingController::NavRoutingController(INavRoutingModel& routingModel,
TurnByTurn::INavTurnByTurnModel& turnByTurnModel,
INavRoutingLocationFinder& locationFinder,
ExampleAppMessaging::TMessageBus& messageBus,
WorldPins::SdkModel::IWorldPinsService& worldPinsService)
: m_routingModel(routingModel)
, m_turnByTurnModel(turnByTurnModel)
, m_locationFinder(locationFinder)
, m_messageBus(messageBus)
, m_worldPinsService(worldPinsService)
, m_isRerouting(false)
, m_waitingForRerouteResponse(false)
, m_startLocationSetCallback(this, &NavRoutingController::OnStartLocationSet)
, m_startLocationClearedCallback(this, &NavRoutingController::OnStartLocationCleared)
, m_endLocationSetCallback(this, &NavRoutingController::OnEndLocationSet)
, m_endLocationClearedCallback(this, &NavRoutingController::OnEndLocationCleared)
, m_routeSetCallback(this, &NavRoutingController::OnRouteSet)
, m_routeClearedCallback(this, &NavRoutingController::OnRouteCleared)
, m_routeUpdatedCallback(this, &NavRoutingController::OnRouteUpdated)
, m_currentDirectionSetCallback(this, &NavRoutingController::OnCurrentDirectionSet)
, m_currentDirectionUpdatedCallback(this, &NavRoutingController::OnCurrentDirectionUpdated)
, m_selectedDirectionSetCallback(this, &NavRoutingController::OnSelectedDirectionSet)
, m_remainingRouteDurationSetCallback(this, &NavRoutingController::OnRemainingRouteDurationSet)
, m_navRoutingModeSetCallback(this, &NavRoutingController::OnNavRoutingModeSet)
, m_viewClosedMessageHandler(this, &NavRoutingController::OnNavWidgetViewClosed)
, m_startEndLocationSwappedMessageHandler(this, &NavRoutingController::OnStartEndLocationSwapped)
, m_startLocationClearClickedMessageHandler(this, &NavRoutingController::OnStartLocationClearClicked)
, m_endLocationClearClickedMessageHandler(this, &NavRoutingController::OnEndLocationClearClicked)
, m_startEndRoutingButtonClickedMessageHandler(this, &NavRoutingController::OnStartEndRoutingButtonClicked)
, m_selectedDirectionChangedMessageHandler(this, &NavRoutingController::OnSelectedDirectionChanged)
, m_rerouteDialogClosedMessageMessageHandler(this, &NavRoutingController::OnRerouteDialogClosed)
, m_navigateToMessageHandler(this, &NavRoutingController::OnNavigationMessage)
, m_shouldRerouteCallback(this, &NavRoutingController::OnShouldReroute)
{
m_routingModel.InsertStartLocationSetCallback(m_startLocationSetCallback);
m_routingModel.InsertStartLocationClearedCallback(m_startLocationClearedCallback);
m_routingModel.InsertEndLocationSetCallback(m_endLocationSetCallback);
m_routingModel.InsertEndLocationClearedCallback(m_endLocationClearedCallback);
m_routingModel.InsertRouteSetCallback(m_routeSetCallback);
m_routingModel.InsertRouteClearedCallback(m_routeClearedCallback);
m_routingModel.InsertRouteUpdatedCallback(m_routeUpdatedCallback);
m_routingModel.InsertSelectedDirectionSetCallback(m_selectedDirectionSetCallback);
m_routingModel.InsertCurrentDirectionSetCallback(m_currentDirectionSetCallback);
m_routingModel.InsertCurrentDirectionUpdatedCallback(m_currentDirectionUpdatedCallback);
m_routingModel.InsertRemainingRouteDurationSetCallback(m_remainingRouteDurationSetCallback);
m_routingModel.InsertNavModeSetCallback(m_navRoutingModeSetCallback);
m_messageBus.SubscribeNative(m_viewClosedMessageHandler);
m_messageBus.SubscribeNative(m_startEndLocationSwappedMessageHandler);
m_messageBus.SubscribeNative(m_startLocationClearClickedMessageHandler);
m_messageBus.SubscribeNative(m_endLocationClearClickedMessageHandler);
m_messageBus.SubscribeNative(m_startEndRoutingButtonClickedMessageHandler);
m_messageBus.SubscribeNative(m_selectedDirectionChangedMessageHandler);
m_messageBus.SubscribeNative(m_rerouteDialogClosedMessageMessageHandler);
m_messageBus.SubscribeNative(m_navigateToMessageHandler);
m_turnByTurnModel.InsertShouldRerouteCallback(m_shouldRerouteCallback);
}
NavRoutingController::~NavRoutingController()
{
m_turnByTurnModel.RemoveShouldRerouteCallback(m_shouldRerouteCallback);
m_messageBus.UnsubscribeNative(m_navigateToMessageHandler);
m_messageBus.UnsubscribeNative(m_rerouteDialogClosedMessageMessageHandler);
m_messageBus.UnsubscribeNative(m_selectedDirectionChangedMessageHandler);
m_messageBus.UnsubscribeNative(m_startEndRoutingButtonClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_endLocationClearClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_startLocationClearClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_startEndLocationSwappedMessageHandler);
m_messageBus.UnsubscribeNative(m_viewClosedMessageHandler);
m_routingModel.RemoveNavModeSetCallback(m_navRoutingModeSetCallback);
m_routingModel.RemoveRemainingRouteDurationSetCallback(m_remainingRouteDurationSetCallback);
m_routingModel.RemoveCurrentDirectionUpdatedCallback(m_currentDirectionUpdatedCallback);
m_routingModel.RemoveCurrentDirectionSetCallback(m_currentDirectionSetCallback);
m_routingModel.RemoveSelectedDirectionSetCallback(m_selectedDirectionSetCallback);
m_routingModel.RemoveRouteUpdatedCallback(m_routeUpdatedCallback);
m_routingModel.RemoveRouteClearedCallback(m_routeClearedCallback);
m_routingModel.RemoveRouteSetCallback(m_routeSetCallback);
m_routingModel.RemoveEndLocationClearedCallback(m_endLocationClearedCallback);
m_routingModel.RemoveEndLocationSetCallback(m_endLocationSetCallback);
m_routingModel.RemoveStartLocationClearedCallback(m_startLocationClearedCallback);
m_routingModel.RemoveStartLocationSetCallback(m_startLocationSetCallback);
}
void NavRoutingController::OnStartLocationSet(const NavRoutingLocationModel& startLocation)
{
m_messageBus.Publish(NavRoutingStartLocationSetMessage(startLocation));
}
void NavRoutingController::OnStartLocationCleared()
{
m_messageBus.Publish(NavRoutingStartLocationClearedMessage());
}
void NavRoutingController::OnEndLocationSet(const NavRoutingLocationModel& endLocation)
{
m_messageBus.Publish(NavRoutingEndLocationSetMessage(endLocation));
}
void NavRoutingController::OnEndLocationCleared()
{
m_messageBus.Publish(NavRoutingEndLocationClearedMessage());
}
void NavRoutingController::OnRouteSet(const NavRoutingRouteModel& routeModel)
{
m_messageBus.Publish(NavRoutingRouteChangedMessage(routeModel, true));
if (m_isRerouting)
{
m_turnByTurnModel.Start(routeModel.GetSourceRouteData());
m_isRerouting = false;
}
else
{
m_routingModel.SetNavMode(Ready);
}
m_routingModel.SetRemainingRouteDuration(routeModel.GetDuration());
m_worldPinsService.DeselectPin();
}
void NavRoutingController::OnRouteCleared()
{
m_messageBus.Publish(NavRoutingRouteClearedMessage());
m_routingModel.SetNavMode(NotReady);
m_routingModel.SetRemainingRouteDuration(0);
}
void NavRoutingController::OnRouteUpdated(const NavRoutingRouteModel& routeModel)
{
m_messageBus.Publish(NavRoutingRouteChangedMessage(routeModel, false));
}
void NavRoutingController::OnCurrentDirectionSet(const int& directionIndex)
{
m_messageBus.Publish(NavRoutingCurrentDirectionSetMessage(directionIndex));
}
void NavRoutingController::OnCurrentDirectionUpdated(const NavRoutingDirectionModel& directionModel)
{
m_messageBus.Publish(NavRoutingCurrentDirectionUpdatedMessage(directionModel));
}
void NavRoutingController::OnSelectedDirectionSet(const int& directionIndex)
{
m_messageBus.Publish(NavRoutingSelectedDirectionSetMessage(directionIndex));
}
void NavRoutingController::OnRemainingRouteDurationSet(const double& seconds)
{
m_messageBus.Publish(NavRoutingRemainingRouteDurationSetMessage(seconds));
}
void NavRoutingController::OnNavRoutingModeSet(const NavRoutingMode& mode)
{
m_messageBus.Publish(NavRoutingModeSetMessage(mode));
}
void NavRoutingController::OnNavWidgetViewClosed(const NavRoutingViewClosedMessage& message)
{
m_routingModel.ClearRoute();
}
void NavRoutingController::OnStartEndLocationSwapped(const NavRoutingViewStartEndLocationSwappedMessage& message)
{
NavRoutingLocationModel startLocation, endLocation;
m_routingModel.TryGetStartLocation(startLocation);
m_routingModel.TryGetEndLocation(endLocation);
NavRoutingLocationModel tempLocation = startLocation;
startLocation = endLocation;
endLocation = tempLocation;
m_routingModel.SetStartLocation(startLocation);
m_routingModel.SetEndLocation(endLocation);
m_routingModel.ClearRoute();
}
void NavRoutingController::OnStartLocationClearClicked(const NavRoutingStartLocationClearClickedMessage& message)
{
m_routingModel.ClearStartLocation();
}
void NavRoutingController::OnEndLocationClearClicked(const NavRoutingEndLocationClearClickedMessage& message)
{
m_routingModel.ClearEndLocation();
}
void NavRoutingController::OnStartEndRoutingButtonClicked(const NavRoutingStartEndRoutingButtonClickedMessage& message)
{
switch (m_routingModel.GetNavMode())
{
case NavRoutingMode::Active:
m_turnByTurnModel.Stop();
break;
case NavRoutingMode::Ready:
{
NavRoutingRouteModel routeModel;
if(m_routingModel.TryGetRoute(routeModel))
{
m_turnByTurnModel.Start(routeModel.GetSourceRouteData());
}
else
{
m_routingModel.SetNavMode(NavRoutingMode::NotReady);
}
break;
}
default:
m_routingModel.SetNavMode(NavRoutingMode::NotReady);
break;
}
}
void NavRoutingController::OnSelectedDirectionChanged(const NavRoutingSelectedDirectionChangedMessage& message)
{
m_routingModel.SetSelectedDirection(message.GetDirectionIndex());
}
void NavRoutingController::OnRerouteDialogClosed(const NavRoutingRerouteDialogClosedMessage& message)
{
if (message.GetShouldReroute())
{
NavRoutingLocationModel startLocation;
if (m_locationFinder.TryGetCurrentLocation(startLocation))
{
m_routingModel.SetStartLocation(startLocation);
m_isRerouting = true;
}
}
m_turnByTurnModel.Stop();
m_waitingForRerouteResponse = false;
}
void NavRoutingController::OnNavigationMessage(const NavigateToMessage& message)
{
NavRoutingLocationModel startLocation, endLocation;
if (!m_locationFinder.TryGetCurrentLocation(startLocation))
{
return;
}
if(!m_locationFinder.TryGetLocationFromNavigationMessage(message, endLocation))
{
return;
}
m_routingModel.SetStartLocation(startLocation);
m_routingModel.SetEndLocation(endLocation);
OpenViewWithModel(m_routingModel);
}
void NavRoutingController::OpenViewWithModel(INavRoutingModel& routingModel)
{
m_messageBus.Publish(NavRoutingViewOpenMessage(routingModel));
}
void NavRoutingController::OnShouldReroute()
{
if (m_waitingForRerouteResponse)
{
return;
}
std::string message = "You seem to be heading away from your destination. Do you want to end navigation?";
m_messageBus.Publish(NavRoutingShowRerouteDialogMessage(message));
m_waitingForRerouteResponse = true;
}
}
}
}
<commit_msg>Fixed issue where using nav swap location button attempts to find routes between blank locations. Buddy: Andrew<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingController.h"
#include "NavRoutingViewOpenMessage.h"
#include "SearchResultModel.h"
#include "NavRoutingStartLocationSetMessage.h"
#include "NavRoutingStartLocationClearedMessage.h"
#include "NavRoutingEndLocationSetMessage.h"
#include "NavRoutingEndLocationClearedMessage.h"
#include "NavRoutingRouteChangedMessage.h"
#include "NavRoutingRouteClearedMessage.h"
#include "NavRoutingCurrentDirectionSetMessage.h"
#include "NavRoutingCurrentDirectionUpdatedMessage.h"
#include "NavRoutingSelectedDirectionSetMessage.h"
#include "NavRoutingRemainingRouteDurationSetMessage.h"
#include "NavRoutingModeSetMessage.h"
#include "INavTurnByTurnModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IAlertBoxFactory.h"
#include "IWorldPinsService.h"
#include "NavRouteInteriorModelHelper.h"
#include "NavRoutingShowRerouteDialogMessage.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
NavRoutingController::NavRoutingController(INavRoutingModel& routingModel,
TurnByTurn::INavTurnByTurnModel& turnByTurnModel,
INavRoutingLocationFinder& locationFinder,
ExampleAppMessaging::TMessageBus& messageBus,
WorldPins::SdkModel::IWorldPinsService& worldPinsService)
: m_routingModel(routingModel)
, m_turnByTurnModel(turnByTurnModel)
, m_locationFinder(locationFinder)
, m_messageBus(messageBus)
, m_worldPinsService(worldPinsService)
, m_isRerouting(false)
, m_waitingForRerouteResponse(false)
, m_startLocationSetCallback(this, &NavRoutingController::OnStartLocationSet)
, m_startLocationClearedCallback(this, &NavRoutingController::OnStartLocationCleared)
, m_endLocationSetCallback(this, &NavRoutingController::OnEndLocationSet)
, m_endLocationClearedCallback(this, &NavRoutingController::OnEndLocationCleared)
, m_routeSetCallback(this, &NavRoutingController::OnRouteSet)
, m_routeClearedCallback(this, &NavRoutingController::OnRouteCleared)
, m_routeUpdatedCallback(this, &NavRoutingController::OnRouteUpdated)
, m_currentDirectionSetCallback(this, &NavRoutingController::OnCurrentDirectionSet)
, m_currentDirectionUpdatedCallback(this, &NavRoutingController::OnCurrentDirectionUpdated)
, m_selectedDirectionSetCallback(this, &NavRoutingController::OnSelectedDirectionSet)
, m_remainingRouteDurationSetCallback(this, &NavRoutingController::OnRemainingRouteDurationSet)
, m_navRoutingModeSetCallback(this, &NavRoutingController::OnNavRoutingModeSet)
, m_viewClosedMessageHandler(this, &NavRoutingController::OnNavWidgetViewClosed)
, m_startEndLocationSwappedMessageHandler(this, &NavRoutingController::OnStartEndLocationSwapped)
, m_startLocationClearClickedMessageHandler(this, &NavRoutingController::OnStartLocationClearClicked)
, m_endLocationClearClickedMessageHandler(this, &NavRoutingController::OnEndLocationClearClicked)
, m_startEndRoutingButtonClickedMessageHandler(this, &NavRoutingController::OnStartEndRoutingButtonClicked)
, m_selectedDirectionChangedMessageHandler(this, &NavRoutingController::OnSelectedDirectionChanged)
, m_rerouteDialogClosedMessageMessageHandler(this, &NavRoutingController::OnRerouteDialogClosed)
, m_navigateToMessageHandler(this, &NavRoutingController::OnNavigationMessage)
, m_shouldRerouteCallback(this, &NavRoutingController::OnShouldReroute)
{
m_routingModel.InsertStartLocationSetCallback(m_startLocationSetCallback);
m_routingModel.InsertStartLocationClearedCallback(m_startLocationClearedCallback);
m_routingModel.InsertEndLocationSetCallback(m_endLocationSetCallback);
m_routingModel.InsertEndLocationClearedCallback(m_endLocationClearedCallback);
m_routingModel.InsertRouteSetCallback(m_routeSetCallback);
m_routingModel.InsertRouteClearedCallback(m_routeClearedCallback);
m_routingModel.InsertRouteUpdatedCallback(m_routeUpdatedCallback);
m_routingModel.InsertSelectedDirectionSetCallback(m_selectedDirectionSetCallback);
m_routingModel.InsertCurrentDirectionSetCallback(m_currentDirectionSetCallback);
m_routingModel.InsertCurrentDirectionUpdatedCallback(m_currentDirectionUpdatedCallback);
m_routingModel.InsertRemainingRouteDurationSetCallback(m_remainingRouteDurationSetCallback);
m_routingModel.InsertNavModeSetCallback(m_navRoutingModeSetCallback);
m_messageBus.SubscribeNative(m_viewClosedMessageHandler);
m_messageBus.SubscribeNative(m_startEndLocationSwappedMessageHandler);
m_messageBus.SubscribeNative(m_startLocationClearClickedMessageHandler);
m_messageBus.SubscribeNative(m_endLocationClearClickedMessageHandler);
m_messageBus.SubscribeNative(m_startEndRoutingButtonClickedMessageHandler);
m_messageBus.SubscribeNative(m_selectedDirectionChangedMessageHandler);
m_messageBus.SubscribeNative(m_rerouteDialogClosedMessageMessageHandler);
m_messageBus.SubscribeNative(m_navigateToMessageHandler);
m_turnByTurnModel.InsertShouldRerouteCallback(m_shouldRerouteCallback);
}
NavRoutingController::~NavRoutingController()
{
m_turnByTurnModel.RemoveShouldRerouteCallback(m_shouldRerouteCallback);
m_messageBus.UnsubscribeNative(m_navigateToMessageHandler);
m_messageBus.UnsubscribeNative(m_rerouteDialogClosedMessageMessageHandler);
m_messageBus.UnsubscribeNative(m_selectedDirectionChangedMessageHandler);
m_messageBus.UnsubscribeNative(m_startEndRoutingButtonClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_endLocationClearClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_startLocationClearClickedMessageHandler);
m_messageBus.UnsubscribeNative(m_startEndLocationSwappedMessageHandler);
m_messageBus.UnsubscribeNative(m_viewClosedMessageHandler);
m_routingModel.RemoveNavModeSetCallback(m_navRoutingModeSetCallback);
m_routingModel.RemoveRemainingRouteDurationSetCallback(m_remainingRouteDurationSetCallback);
m_routingModel.RemoveCurrentDirectionUpdatedCallback(m_currentDirectionUpdatedCallback);
m_routingModel.RemoveCurrentDirectionSetCallback(m_currentDirectionSetCallback);
m_routingModel.RemoveSelectedDirectionSetCallback(m_selectedDirectionSetCallback);
m_routingModel.RemoveRouteUpdatedCallback(m_routeUpdatedCallback);
m_routingModel.RemoveRouteClearedCallback(m_routeClearedCallback);
m_routingModel.RemoveRouteSetCallback(m_routeSetCallback);
m_routingModel.RemoveEndLocationClearedCallback(m_endLocationClearedCallback);
m_routingModel.RemoveEndLocationSetCallback(m_endLocationSetCallback);
m_routingModel.RemoveStartLocationClearedCallback(m_startLocationClearedCallback);
m_routingModel.RemoveStartLocationSetCallback(m_startLocationSetCallback);
}
void NavRoutingController::OnStartLocationSet(const NavRoutingLocationModel& startLocation)
{
m_messageBus.Publish(NavRoutingStartLocationSetMessage(startLocation));
}
void NavRoutingController::OnStartLocationCleared()
{
m_messageBus.Publish(NavRoutingStartLocationClearedMessage());
}
void NavRoutingController::OnEndLocationSet(const NavRoutingLocationModel& endLocation)
{
m_messageBus.Publish(NavRoutingEndLocationSetMessage(endLocation));
}
void NavRoutingController::OnEndLocationCleared()
{
m_messageBus.Publish(NavRoutingEndLocationClearedMessage());
}
void NavRoutingController::OnRouteSet(const NavRoutingRouteModel& routeModel)
{
m_messageBus.Publish(NavRoutingRouteChangedMessage(routeModel, true));
if (m_isRerouting)
{
m_turnByTurnModel.Start(routeModel.GetSourceRouteData());
m_isRerouting = false;
}
else
{
m_routingModel.SetNavMode(Ready);
}
m_routingModel.SetRemainingRouteDuration(routeModel.GetDuration());
m_worldPinsService.DeselectPin();
}
void NavRoutingController::OnRouteCleared()
{
m_messageBus.Publish(NavRoutingRouteClearedMessage());
m_routingModel.SetNavMode(NotReady);
m_routingModel.SetRemainingRouteDuration(0);
}
void NavRoutingController::OnRouteUpdated(const NavRoutingRouteModel& routeModel)
{
m_messageBus.Publish(NavRoutingRouteChangedMessage(routeModel, false));
}
void NavRoutingController::OnCurrentDirectionSet(const int& directionIndex)
{
m_messageBus.Publish(NavRoutingCurrentDirectionSetMessage(directionIndex));
}
void NavRoutingController::OnCurrentDirectionUpdated(const NavRoutingDirectionModel& directionModel)
{
m_messageBus.Publish(NavRoutingCurrentDirectionUpdatedMessage(directionModel));
}
void NavRoutingController::OnSelectedDirectionSet(const int& directionIndex)
{
m_messageBus.Publish(NavRoutingSelectedDirectionSetMessage(directionIndex));
}
void NavRoutingController::OnRemainingRouteDurationSet(const double& seconds)
{
m_messageBus.Publish(NavRoutingRemainingRouteDurationSetMessage(seconds));
}
void NavRoutingController::OnNavRoutingModeSet(const NavRoutingMode& mode)
{
m_messageBus.Publish(NavRoutingModeSetMessage(mode));
}
void NavRoutingController::OnNavWidgetViewClosed(const NavRoutingViewClosedMessage& message)
{
m_routingModel.ClearRoute();
}
void NavRoutingController::OnStartEndLocationSwapped(const NavRoutingViewStartEndLocationSwappedMessage& message)
{
NavRoutingLocationModel startLocation, endLocation;
bool hasStartLocation = m_routingModel.TryGetStartLocation(startLocation);
bool hasEndLocation = m_routingModel.TryGetEndLocation(endLocation);
NavRoutingLocationModel tempLocation = startLocation;
startLocation = endLocation;
endLocation = tempLocation;
m_routingModel.ClearRoute();
if(hasEndLocation)
{
m_routingModel.SetStartLocation(startLocation);
}
else
{
m_routingModel.ClearStartLocation();
}
if(hasStartLocation)
{
m_routingModel.SetEndLocation(endLocation);
}
else
{
m_routingModel.ClearEndLocation();
}
}
void NavRoutingController::OnStartLocationClearClicked(const NavRoutingStartLocationClearClickedMessage& message)
{
m_routingModel.ClearStartLocation();
}
void NavRoutingController::OnEndLocationClearClicked(const NavRoutingEndLocationClearClickedMessage& message)
{
m_routingModel.ClearEndLocation();
}
void NavRoutingController::OnStartEndRoutingButtonClicked(const NavRoutingStartEndRoutingButtonClickedMessage& message)
{
switch (m_routingModel.GetNavMode())
{
case NavRoutingMode::Active:
m_turnByTurnModel.Stop();
break;
case NavRoutingMode::Ready:
{
NavRoutingRouteModel routeModel;
if(m_routingModel.TryGetRoute(routeModel))
{
m_turnByTurnModel.Start(routeModel.GetSourceRouteData());
}
else
{
m_routingModel.SetNavMode(NavRoutingMode::NotReady);
}
break;
}
default:
m_routingModel.SetNavMode(NavRoutingMode::NotReady);
break;
}
}
void NavRoutingController::OnSelectedDirectionChanged(const NavRoutingSelectedDirectionChangedMessage& message)
{
m_routingModel.SetSelectedDirection(message.GetDirectionIndex());
}
void NavRoutingController::OnRerouteDialogClosed(const NavRoutingRerouteDialogClosedMessage& message)
{
if (message.GetShouldReroute())
{
NavRoutingLocationModel startLocation;
if (m_locationFinder.TryGetCurrentLocation(startLocation))
{
m_routingModel.SetStartLocation(startLocation);
m_isRerouting = true;
}
}
m_turnByTurnModel.Stop();
m_waitingForRerouteResponse = false;
}
void NavRoutingController::OnNavigationMessage(const NavigateToMessage& message)
{
NavRoutingLocationModel startLocation, endLocation;
if (!m_locationFinder.TryGetCurrentLocation(startLocation))
{
return;
}
if(!m_locationFinder.TryGetLocationFromNavigationMessage(message, endLocation))
{
return;
}
m_routingModel.SetStartLocation(startLocation);
m_routingModel.SetEndLocation(endLocation);
OpenViewWithModel(m_routingModel);
}
void NavRoutingController::OpenViewWithModel(INavRoutingModel& routingModel)
{
m_messageBus.Publish(NavRoutingViewOpenMessage(routingModel));
}
void NavRoutingController::OnShouldReroute()
{
if (m_waitingForRerouteResponse)
{
return;
}
std::string message = "You seem to be heading away from your destination. Do you want to end navigation?";
m_messageBus.Publish(NavRoutingShowRerouteDialogMessage(message));
m_waitingForRerouteResponse = true;
}
}
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REALM_OS_SYNC_CONFIG_HPP
#define REALM_OS_SYNC_CONFIG_HPP
#include "sync_user.hpp"
#include <realm/util/assert.hpp>
#include <realm/sync/client.hpp>
#include <realm/sync/protocol.hpp>
#include <functional>
#include <memory>
#include <string>
#include <system_error>
#include <unordered_map>
#include <realm/sync/history.hpp>
namespace realm {
class SyncUser;
class SyncSession;
using ChangesetTransformer = sync::ClientHistory::ChangesetCooker;
enum class SyncSessionStopPolicy;
struct SyncConfig;
using SyncBindSessionHandler = void(const std::string&, // path on disk of the Realm file.
const SyncConfig&, // the sync configuration object.
std::shared_ptr<SyncSession> // the session which should be bound.
);
struct SyncError;
using SyncSessionErrorHandler = void(std::shared_ptr<SyncSession>, SyncError);
struct SyncError {
using ProtocolError = realm::sync::ProtocolError;
std::error_code error_code;
std::string message;
bool is_fatal;
std::unordered_map<std::string, std::string> user_info;
static constexpr const char c_original_file_path_key[] = "ORIGINAL_FILE_PATH";
static constexpr const char c_recovery_file_path_key[] = "RECOVERY_FILE_PATH";
/// The error is a client error, which applies to the client and all its sessions.
bool is_client_error() const
{
return error_code.category() == realm::sync::client_error_category();
}
/// The error is a protocol error, which may either be connection-level or session-level.
bool is_connection_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return !realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error is a connection-level protocol error.
bool is_session_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error indicates a client reset situation.
bool is_client_reset_requested() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
// Documented here: https://realm.io/docs/realm-object-server/#client-recovery-from-a-backup
return (error_code == ProtocolError::bad_server_file_ident
|| error_code == ProtocolError::bad_client_file_ident
|| error_code == ProtocolError::bad_server_version
|| error_code == ProtocolError::diverging_histories);
}
};
struct SyncConfig {
std::shared_ptr<SyncUser> user;
// The URL of the Realm, or of the reference Realm if partial sync is being used.
// The URL that will be used when connecting to the object server is that returned by `realm_url()`,
// and will differ from `reference_realm_url` if partial sync is being used.
// Set this field, but read from `realm_url()`.
std::string reference_realm_url;
SyncSessionStopPolicy stop_policy;
std::function<SyncBindSessionHandler> bind_session_handler;
std::function<SyncSessionErrorHandler> error_handler;
std::shared_ptr<ChangesetTransformer> transformer;
util::Optional<std::array<char, 64>> realm_encryption_key;
bool client_validate_ssl = true;
util::Optional<std::string> ssl_trust_certificate_path;
std::function<sync::Session::SSLVerifyCallback> ssl_verify_callback;
bool validate_sync_history = true;
bool is_partial = false;
util::Optional<std::string> custom_partial_sync_identifier;
// The URL that will be used when connecting to the object server.
// This will differ from `reference_realm_url` when partial sync is being used.
std::string realm_url() const;
#if __GNUC__ < 5
// GCC 4.9 does not support C++14 braced-init
SyncConfig(std::shared_ptr<SyncUser> user, std::string reference_realm_url,
SyncSessionStopPolicy stop_policy,
std::function<SyncBindSessionHandler> bind_session_handler,
std::function<SyncSessionErrorHandler> error_handler = nullptr,
std::shared_ptr<ChangesetTransformer> transformer = nullptr,
util::Optional<std::array<char, 64>> realm_encryption_key = util::none,
bool client_validate_ssl = true,
util::Optional<std::string> ssl_trust_certificate_path = util::none,
std::function<realm::sync::Session::SSLVerifyCallback> ssl_verify_callback = nullptr,
bool is_partial = false,
util::Optional<std::string> custom_partial_sync_identifier = util::none
)
: user(std::move(user))
, reference_realm_url(std::move(reference_realm_url))
, stop_policy(stop_policy)
, bind_session_handler(std::move(bind_session_handler))
, error_handler(std::move(error_handler))
, transformer(std::move(transformer))
, realm_encryption_key(std::move(realm_encryption_key))
, client_validate_ssl(client_validate_ssl)
, ssl_trust_certificate_path(std::move(ssl_trust_certificate_path))
, ssl_verify_callback(std::move(ssl_verify_callback))
, is_partial(is_partial)
, custom_partial_sync_identifier(std::move(custom_partial_sync_identifier))
{
}
SyncConfig() {}
#endif
};
} // namespace realm
#endif // REALM_OS_SYNC_CONFIG_HPP
<commit_msg>Fix the order that `SyncConfig`'s members are declared in so that they match the order of the constructor arguments.<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REALM_OS_SYNC_CONFIG_HPP
#define REALM_OS_SYNC_CONFIG_HPP
#include "sync_user.hpp"
#include <realm/util/assert.hpp>
#include <realm/sync/client.hpp>
#include <realm/sync/protocol.hpp>
#include <functional>
#include <memory>
#include <string>
#include <system_error>
#include <unordered_map>
#include <realm/sync/history.hpp>
namespace realm {
class SyncUser;
class SyncSession;
using ChangesetTransformer = sync::ClientHistory::ChangesetCooker;
enum class SyncSessionStopPolicy;
struct SyncConfig;
using SyncBindSessionHandler = void(const std::string&, // path on disk of the Realm file.
const SyncConfig&, // the sync configuration object.
std::shared_ptr<SyncSession> // the session which should be bound.
);
struct SyncError;
using SyncSessionErrorHandler = void(std::shared_ptr<SyncSession>, SyncError);
struct SyncError {
using ProtocolError = realm::sync::ProtocolError;
std::error_code error_code;
std::string message;
bool is_fatal;
std::unordered_map<std::string, std::string> user_info;
static constexpr const char c_original_file_path_key[] = "ORIGINAL_FILE_PATH";
static constexpr const char c_recovery_file_path_key[] = "RECOVERY_FILE_PATH";
/// The error is a client error, which applies to the client and all its sessions.
bool is_client_error() const
{
return error_code.category() == realm::sync::client_error_category();
}
/// The error is a protocol error, which may either be connection-level or session-level.
bool is_connection_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return !realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error is a connection-level protocol error.
bool is_session_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error indicates a client reset situation.
bool is_client_reset_requested() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
// Documented here: https://realm.io/docs/realm-object-server/#client-recovery-from-a-backup
return (error_code == ProtocolError::bad_server_file_ident
|| error_code == ProtocolError::bad_client_file_ident
|| error_code == ProtocolError::bad_server_version
|| error_code == ProtocolError::diverging_histories);
}
};
struct SyncConfig {
std::shared_ptr<SyncUser> user;
// The URL of the Realm, or of the reference Realm if partial sync is being used.
// The URL that will be used when connecting to the object server is that returned by `realm_url()`,
// and will differ from `reference_realm_url` if partial sync is being used.
// Set this field, but read from `realm_url()`.
std::string reference_realm_url;
SyncSessionStopPolicy stop_policy;
std::function<SyncBindSessionHandler> bind_session_handler;
std::function<SyncSessionErrorHandler> error_handler;
std::shared_ptr<ChangesetTransformer> transformer;
util::Optional<std::array<char, 64>> realm_encryption_key;
bool client_validate_ssl = true;
util::Optional<std::string> ssl_trust_certificate_path;
std::function<sync::Session::SSLVerifyCallback> ssl_verify_callback;
bool is_partial = false;
util::Optional<std::string> custom_partial_sync_identifier;
bool validate_sync_history = true;
// The URL that will be used when connecting to the object server.
// This will differ from `reference_realm_url` when partial sync is being used.
std::string realm_url() const;
#if __GNUC__ < 5
// GCC 4.9 does not support C++14 braced-init
SyncConfig(std::shared_ptr<SyncUser> user, std::string reference_realm_url,
SyncSessionStopPolicy stop_policy,
std::function<SyncBindSessionHandler> bind_session_handler,
std::function<SyncSessionErrorHandler> error_handler = nullptr,
std::shared_ptr<ChangesetTransformer> transformer = nullptr,
util::Optional<std::array<char, 64>> realm_encryption_key = util::none,
bool client_validate_ssl = true,
util::Optional<std::string> ssl_trust_certificate_path = util::none,
std::function<realm::sync::Session::SSLVerifyCallback> ssl_verify_callback = nullptr,
bool is_partial = false,
util::Optional<std::string> custom_partial_sync_identifier = util::none
)
: user(std::move(user))
, reference_realm_url(std::move(reference_realm_url))
, stop_policy(stop_policy)
, bind_session_handler(std::move(bind_session_handler))
, error_handler(std::move(error_handler))
, transformer(std::move(transformer))
, realm_encryption_key(std::move(realm_encryption_key))
, client_validate_ssl(client_validate_ssl)
, ssl_trust_certificate_path(std::move(ssl_trust_certificate_path))
, ssl_verify_callback(std::move(ssl_verify_callback))
, is_partial(is_partial)
, custom_partial_sync_identifier(std::move(custom_partial_sync_identifier))
{
}
SyncConfig() {}
#endif
};
} // namespace realm
#endif // REALM_OS_SYNC_CONFIG_HPP
<|endoftext|>
|
<commit_before>#include "globalenv.h"
#include "mapm/m_apm.h"
#include "types/root_typemanager.h"
#include "context/root_static_context.h"
#include "functions/library.h"
#include "store/naive/simple_store.h"
#include <libxml/parser.h>
using namespace xqp;
GlobalEnvironment *GlobalEnvironment::m_globalEnv = 0;
GlobalEnvironment& GlobalEnvironment::getInstance()
{
if (!m_globalEnv) {
GlobalEnvironment::init();
}
return *m_globalEnv;
}
void GlobalEnvironment::init()
{
m_globalEnv = new GlobalEnvironment();
m_globalEnv->m_store.reset(new SimpleStore());
static_cast<SimpleStore *>(m_globalEnv->m_store.get())->init();
m_globalEnv->m_rootStaticContext.reset(new root_static_context());
BuiltinFunctionLibrary::populateContext(m_globalEnv->m_rootStaticContext.get());
// initialize mapm for bignum handling
m_globalEnv->m_mapm = m_apm_init();
// This initializes the libxml2 library and checks
// potential ABI mismatches between
// the version it was compiled for and the actual
// shared library used.
// calling its init is done here because we also want to
// free it at the end, i.e. when zorba is shutdown
LIBXML_TEST_VERSION
}
void GlobalEnvironment::destroy()
{
// do cleanup of the libxml2 library
// however, after that, a user will have to call
// LIBXML_TEST_VERSION if he wants to use libxml2
// beyond the lifecycle of zorba
xmlCleanupParser();
// release resources aquired by the mapm library
// this will force zorba users to reinit mapm
// if they shutdown zorba but want to use mapm beyond
m_apm_free(m_globalEnv->m_mapm);
m_apm_free_all_mem();
m_globalEnv->m_mapm = 0;
m_globalEnv->m_rootStaticContext.reset(NULL);
m_globalEnv->m_store.reset(NULL);
delete m_globalEnv;
m_globalEnv = NULL;
}
GlobalEnvironment::GlobalEnvironment()
{
}
static_context& GlobalEnvironment::getRootStaticContext()
{
return *m_rootStaticContext;
}
RootTypeManager& GlobalEnvironment::getRootTypeManager()
{
return *(static_cast<RootTypeManager *>(m_rootStaticContext->get_typemanager()));
}
Store& GlobalEnvironment::getStore()
{
return *m_store;
}
/* vim:set ts=2 sw=2: */
<commit_msg>cleanup icu at the end and start it in a single threaded environment at the beginning<commit_after>#include "globalenv.h"
#include "mapm/m_apm.h"
#include "types/root_typemanager.h"
#include "context/root_static_context.h"
#include "functions/library.h"
#include "store/naive/simple_store.h"
#include <libxml/parser.h>
#include <cassert>
#include <unicode/uclean.h>
using namespace xqp;
GlobalEnvironment *GlobalEnvironment::m_globalEnv = 0;
GlobalEnvironment& GlobalEnvironment::getInstance()
{
if (!m_globalEnv) {
GlobalEnvironment::init();
}
return *m_globalEnv;
}
void GlobalEnvironment::init()
{
m_globalEnv = new GlobalEnvironment();
// initialize the icu library
// we do this here because we are sure that is used
// from one thread only
// see http://www.icu-project.org/userguide/design.html#Init_and_Termination
// and http://www.icu-project.org/apiref/icu4c/uclean_8h.html
{
UErrorCode lICUInitStatus = U_ZERO_ERROR;
u_init(&lICUInitStatus);
assert(lICUInitStatus == U_ZERO_ERROR);
}
m_globalEnv->m_store.reset(new SimpleStore());
static_cast<SimpleStore *>(m_globalEnv->m_store.get())->init();
m_globalEnv->m_rootStaticContext.reset(new root_static_context());
BuiltinFunctionLibrary::populateContext(m_globalEnv->m_rootStaticContext.get());
// initialize mapm for bignum handling
m_globalEnv->m_mapm = m_apm_init();
// This initializes the libxml2 library and checks
// potential ABI mismatches between
// the version it was compiled for and the actual
// shared library used.
// calling its init is done here because we also want to
// free it at the end, i.e. when zorba is shutdown
LIBXML_TEST_VERSION
}
void GlobalEnvironment::destroy()
{
// do cleanup of the libxml2 library
// however, after that, a user will have to call
// LIBXML_TEST_VERSION if he wants to use libxml2
// beyond the lifecycle of zorba
xmlCleanupParser();
// release resources aquired by the mapm library
// this will force zorba users to reinit mapm
// if they shutdown zorba but want to use mapm beyond
m_apm_free(m_globalEnv->m_mapm);
m_apm_free_all_mem();
m_globalEnv->m_mapm = 0;
m_globalEnv->m_rootStaticContext.reset(NULL);
m_globalEnv->m_store.reset(NULL);
// we shutdown icu
// again it is important to mention this in the documentation
// we might disable this call because it only
// releases statically initialized memory and prevents
// valgrind from reporting those problems at the end
// see http://www.icu-project.org/apiref/icu4c/uclean_8h.html#93f27d0ddc7c196a1da864763f2d8920
{
u_cleanup();
}
delete m_globalEnv;
m_globalEnv = NULL;
}
GlobalEnvironment::GlobalEnvironment()
{
}
static_context& GlobalEnvironment::getRootStaticContext()
{
return *m_rootStaticContext;
}
RootTypeManager& GlobalEnvironment::getRootTypeManager()
{
return *(static_cast<RootTypeManager *>(m_rootStaticContext->get_typemanager()));
}
Store& GlobalEnvironment::getStore()
{
return *m_store;
}
/* vim:set ts=2 sw=2: */
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <iostream>
#include <numeric> // for iota
#include <Eigen/Dense>
#include "drake/systems/plants/constraint/RigidBodyConstraint.h"
#include "drake/systems/plants/IKoptions.h"
#include "drake/systems/plants/RigidBodyIK.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "drake/util/eigen_matrix_compare.h"
#include "gtest/gtest.h"
using namespace std;
using namespace Eigen;
using drake::util::CompareMatrices;
using drake::util::MatrixCompareType;
// Find the joint position indices corresponding to 'name'
vector<int> getJointPositionVectorIndices(const RigidBodyTree &model,
const std::string &name) {
RigidBody* joint_parent_body = model.findJoint(name);
int num_positions = joint_parent_body->getJoint().getNumPositions();
vector<int> ret(static_cast<size_t>(num_positions));
// fill with sequentially increasing values, starting at
// joint_parent_body->position_num_start:
iota(ret.begin(), ret.end(), joint_parent_body->position_num_start);
return ret;
}
void findJointAndInsert(const RigidBodyTree &model, const std::string &name,
vector<int> &position_list) {
auto position_indices = getJointPositionVectorIndices(model, name);
position_list.insert(position_list.end(), position_indices.begin(),
position_indices.end());
}
TEST(testIKMoreConstraints, IKMoreConstraints) {
RigidBodyTree model("examples/Atlas/urdf/atlas_minimal_contact.urdf");
Vector2d tspan;
tspan << 0, 1;
// Default Atlas v5 posture:
VectorXd qstar(model.num_positions);
qstar << -0.0260, 0, 0.8440, 0, 0, 0, 0, 0, 0, 0.2700, 0, 0.0550, -0.5700,
1.1300, -0.5500, -0.0550, -1.3300, 2.1530, 0.5000, 0.0985, 0, 0.0008,
-0.2700, 0, -0.0550, -0.5700, 1.1300, -0.5500, 0.0550, 1.3300, 2.1530,
-0.5000, 0.0985, 0, 0.0008, 0.2564;
// 1 Back Posture Constraint
PostureConstraint kc_posture_back(&model, tspan);
std::vector<int> back_idx;
findJointAndInsert(model, "back_bkz", back_idx);
findJointAndInsert(model, "back_bky", back_idx);
findJointAndInsert(model, "back_bkx", back_idx);
VectorXd back_lb = VectorXd::Zero(3);
VectorXd back_ub = VectorXd::Zero(3);
kc_posture_back.setJointLimits(3, back_idx.data(), back_lb, back_ub);
// 2 Knees Constraint
PostureConstraint kc_posture_knees(&model, tspan);
std::vector<int> knee_idx;
findJointAndInsert(model, "l_leg_kny", knee_idx);
findJointAndInsert(model, "r_leg_kny", knee_idx);
VectorXd knee_lb = VectorXd::Zero(2);
knee_lb(0) = 1.0; // usually use 0.6
knee_lb(1) = 1.0; // usually use 0.6
VectorXd knee_ub = VectorXd::Zero(2);
knee_ub(0) = 2.5;
knee_ub(1) = 2.5;
kc_posture_knees.setJointLimits(2, knee_idx.data(), knee_lb, knee_ub);
// 3 Left Arm Constraint
PostureConstraint kc_posture_larm(&model, tspan);
std::vector<int> larm_idx;
findJointAndInsert(model, "l_arm_shz", larm_idx);
findJointAndInsert(model, "l_arm_shx", larm_idx);
findJointAndInsert(model, "l_arm_ely", larm_idx);
findJointAndInsert(model, "l_arm_elx", larm_idx);
findJointAndInsert(model, "l_arm_uwy", larm_idx);
findJointAndInsert(model, "l_arm_mwx", larm_idx);
findJointAndInsert(model, "l_arm_lwy", larm_idx);
VectorXd larm_lb = VectorXd::Zero(7);
larm_lb(0) = 0.27;
larm_lb(1) = -1.33;
larm_lb(2) = 2.153;
larm_lb(3) = 0.500;
larm_lb(4) = 0.0985;
larm_lb(5) = 0;
larm_lb(6) = 0.0008;
VectorXd larm_ub = larm_lb;
kc_posture_larm.setJointLimits(7, larm_idx.data(), larm_lb, larm_ub);
// 4 Left Foot Position and Orientation Constraints
int l_foot = model.findLinkId("l_foot");
Vector3d l_foot_pt = Vector3d::Zero();
Vector3d lfoot_pos0;
lfoot_pos0(0) = 0;
lfoot_pos0(1) = 0.13;
lfoot_pos0(2) = 0.08;
Vector3d lfoot_pos_lb = lfoot_pos0;
lfoot_pos_lb(0) += 0.001;
lfoot_pos_lb(1) += 0.001;
lfoot_pos_lb(2) += 0.001;
Vector3d lfoot_pos_ub = lfoot_pos_lb;
lfoot_pos_ub(2) += 0.01;
// std::cout << lfoot_pos0.transpose() << " lfoot\n" ;
WorldPositionConstraint kc_lfoot_pos(&model, l_foot, l_foot_pt, lfoot_pos_lb,
lfoot_pos_ub, tspan);
Eigen::Vector4d quat_des(1, 0, 0, 0);
double tol = 0.0017453292519943296;
WorldQuatConstraint kc_lfoot_quat(&model, l_foot, quat_des, tol, tspan);
// 5 Right Foot Position and Orientation Constraints
int r_foot = model.findLinkId("r_foot");
Vector3d r_foot_pt = Vector3d::Zero();
Vector3d rfoot_pos0;
rfoot_pos0(0) = 0;
rfoot_pos0(1) = -0.13;
rfoot_pos0(2) = 0.08;
Vector3d rfoot_pos_lb = rfoot_pos0;
rfoot_pos_lb(0) += 0.001;
rfoot_pos_lb(1) += 0.001;
rfoot_pos_lb(2) += 0.001;
Vector3d rfoot_pos_ub = rfoot_pos_lb;
rfoot_pos_ub(2) += 0.001;
// std::cout << rfoot_pos0.transpose() << " lfoot\n" ;
WorldPositionConstraint kc_rfoot_pos(&model, r_foot, r_foot_pt, rfoot_pos_lb,
rfoot_pos_ub, tspan);
WorldQuatConstraint kc_rfoot_quat(&model, r_foot, quat_des, tol, tspan);
// 6 Right Position Constraints (actual reaching constraint)
int r_hand = model.findLinkId("r_hand");
Vector3d r_hand_pt = Vector3d::Zero();
Vector3d rhand_pos0;
// Vector3d rhand_pos0 = model.forwardKin(r_hand_pt, r_hand, 0, 0, 0).value();
rhand_pos0(0) = 0.2;
rhand_pos0(1) = -0.5;
rhand_pos0(2) = 0.4;
Vector3d rhand_pos_lb = rhand_pos0;
rhand_pos_lb(0) += 0.05;
rhand_pos_lb(1) += 0.05;
rhand_pos_lb(2) += 0.05;
Vector3d rhand_pos_ub = rhand_pos_lb;
rhand_pos_ub(2) += 0.05;
// std::cout << rhand_pos_ub.transpose() << " rhand\n" ;
WorldPositionConstraint kc_rhand(&model, r_hand, r_hand_pt, rhand_pos_lb,
rhand_pos_ub, tspan);
// 7 QuasiStatic Constraints
QuasiStaticConstraint kc_quasi(&model, tspan);
kc_quasi.setShrinkFactor(0.2);
kc_quasi.setActive(true);
Eigen::Matrix3Xd l_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);
l_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780, 0.0624, -0.0624, 0.0624,
-0.0624, -0.0811, -0.0811, -0.0811, -0.0811;
kc_quasi.addContact(1, &l_foot, &l_foot_pts);
Eigen::Matrix3Xd r_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);
r_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780, 0.0624, -0.0624, 0.0624,
-0.0624, -0.0811, -0.0811, -0.0811, -0.0811;
kc_quasi.addContact(1, &r_foot, &r_foot_pts);
std::vector<RigidBodyConstraint *> constraint_array;
constraint_array.push_back(&kc_quasi);
constraint_array.push_back(&kc_posture_knees);
constraint_array.push_back(&kc_lfoot_pos);
constraint_array.push_back(&kc_lfoot_quat);
constraint_array.push_back(&kc_rfoot_pos);
constraint_array.push_back(&kc_rfoot_quat);
constraint_array.push_back(&kc_rhand);
constraint_array.push_back(&kc_posture_larm);
constraint_array.push_back(&kc_posture_back);
IKoptions ikoptions(&model);
VectorXd q_sol(model.num_positions);
int info;
vector<string> infeasible_constraint;
inverseKin(&model, qstar, qstar, constraint_array.size(),
constraint_array.data(), ikoptions,
&q_sol, &info, &infeasible_constraint);
printf("INFO = %d\n", info);
EXPECT_EQ(info, 1);
/////////////////////////////////////////
KinematicsCache<double> cache = model.doKinematics(q_sol);
Vector3d com = model.centerOfMass(cache);
printf("%5.6f\n%5.6f\n%5.6f\n", com(0), com(1), com(2));
EXPECT_TRUE(
CompareMatrices(com, Vector3d(0.074890, -0.037551, 1.008913), 1e-6,
MatrixCompareType::absolute));
}
<commit_msg>clang-format on drake/systems/plants/test/testIKMoreConstraints.cpp<commit_after>#include <cstdlib>
#include <iostream>
#include <numeric> // for iota
#include <Eigen/Dense>
#include "drake/systems/plants/constraint/RigidBodyConstraint.h"
#include "drake/systems/plants/IKoptions.h"
#include "drake/systems/plants/RigidBodyIK.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "drake/util/eigen_matrix_compare.h"
#include "gtest/gtest.h"
using namespace std;
using namespace Eigen;
using drake::util::CompareMatrices;
using drake::util::MatrixCompareType;
// Find the joint position indices corresponding to 'name'
vector<int> getJointPositionVectorIndices(const RigidBodyTree& model,
const std::string& name) {
RigidBody* joint_parent_body = model.findJoint(name);
int num_positions = joint_parent_body->getJoint().getNumPositions();
vector<int> ret(static_cast<size_t>(num_positions));
// fill with sequentially increasing values, starting at
// joint_parent_body->position_num_start:
iota(ret.begin(), ret.end(), joint_parent_body->position_num_start);
return ret;
}
void findJointAndInsert(const RigidBodyTree& model, const std::string& name,
vector<int>& position_list) {
auto position_indices = getJointPositionVectorIndices(model, name);
position_list.insert(position_list.end(), position_indices.begin(),
position_indices.end());
}
TEST(testIKMoreConstraints, IKMoreConstraints) {
RigidBodyTree model("examples/Atlas/urdf/atlas_minimal_contact.urdf");
Vector2d tspan;
tspan << 0, 1;
// Default Atlas v5 posture:
VectorXd qstar(model.num_positions);
qstar << -0.0260, 0, 0.8440, 0, 0, 0, 0, 0, 0, 0.2700, 0, 0.0550, -0.5700,
1.1300, -0.5500, -0.0550, -1.3300, 2.1530, 0.5000, 0.0985, 0, 0.0008,
-0.2700, 0, -0.0550, -0.5700, 1.1300, -0.5500, 0.0550, 1.3300, 2.1530,
-0.5000, 0.0985, 0, 0.0008, 0.2564;
// 1 Back Posture Constraint
PostureConstraint kc_posture_back(&model, tspan);
std::vector<int> back_idx;
findJointAndInsert(model, "back_bkz", back_idx);
findJointAndInsert(model, "back_bky", back_idx);
findJointAndInsert(model, "back_bkx", back_idx);
VectorXd back_lb = VectorXd::Zero(3);
VectorXd back_ub = VectorXd::Zero(3);
kc_posture_back.setJointLimits(3, back_idx.data(), back_lb, back_ub);
// 2 Knees Constraint
PostureConstraint kc_posture_knees(&model, tspan);
std::vector<int> knee_idx;
findJointAndInsert(model, "l_leg_kny", knee_idx);
findJointAndInsert(model, "r_leg_kny", knee_idx);
VectorXd knee_lb = VectorXd::Zero(2);
knee_lb(0) = 1.0; // usually use 0.6
knee_lb(1) = 1.0; // usually use 0.6
VectorXd knee_ub = VectorXd::Zero(2);
knee_ub(0) = 2.5;
knee_ub(1) = 2.5;
kc_posture_knees.setJointLimits(2, knee_idx.data(), knee_lb, knee_ub);
// 3 Left Arm Constraint
PostureConstraint kc_posture_larm(&model, tspan);
std::vector<int> larm_idx;
findJointAndInsert(model, "l_arm_shz", larm_idx);
findJointAndInsert(model, "l_arm_shx", larm_idx);
findJointAndInsert(model, "l_arm_ely", larm_idx);
findJointAndInsert(model, "l_arm_elx", larm_idx);
findJointAndInsert(model, "l_arm_uwy", larm_idx);
findJointAndInsert(model, "l_arm_mwx", larm_idx);
findJointAndInsert(model, "l_arm_lwy", larm_idx);
VectorXd larm_lb = VectorXd::Zero(7);
larm_lb(0) = 0.27;
larm_lb(1) = -1.33;
larm_lb(2) = 2.153;
larm_lb(3) = 0.500;
larm_lb(4) = 0.0985;
larm_lb(5) = 0;
larm_lb(6) = 0.0008;
VectorXd larm_ub = larm_lb;
kc_posture_larm.setJointLimits(7, larm_idx.data(), larm_lb, larm_ub);
// 4 Left Foot Position and Orientation Constraints
int l_foot = model.findLinkId("l_foot");
Vector3d l_foot_pt = Vector3d::Zero();
Vector3d lfoot_pos0;
lfoot_pos0(0) = 0;
lfoot_pos0(1) = 0.13;
lfoot_pos0(2) = 0.08;
Vector3d lfoot_pos_lb = lfoot_pos0;
lfoot_pos_lb(0) += 0.001;
lfoot_pos_lb(1) += 0.001;
lfoot_pos_lb(2) += 0.001;
Vector3d lfoot_pos_ub = lfoot_pos_lb;
lfoot_pos_ub(2) += 0.01;
// std::cout << lfoot_pos0.transpose() << " lfoot\n" ;
WorldPositionConstraint kc_lfoot_pos(&model, l_foot, l_foot_pt, lfoot_pos_lb,
lfoot_pos_ub, tspan);
Eigen::Vector4d quat_des(1, 0, 0, 0);
double tol = 0.0017453292519943296;
WorldQuatConstraint kc_lfoot_quat(&model, l_foot, quat_des, tol, tspan);
// 5 Right Foot Position and Orientation Constraints
int r_foot = model.findLinkId("r_foot");
Vector3d r_foot_pt = Vector3d::Zero();
Vector3d rfoot_pos0;
rfoot_pos0(0) = 0;
rfoot_pos0(1) = -0.13;
rfoot_pos0(2) = 0.08;
Vector3d rfoot_pos_lb = rfoot_pos0;
rfoot_pos_lb(0) += 0.001;
rfoot_pos_lb(1) += 0.001;
rfoot_pos_lb(2) += 0.001;
Vector3d rfoot_pos_ub = rfoot_pos_lb;
rfoot_pos_ub(2) += 0.001;
// std::cout << rfoot_pos0.transpose() << " lfoot\n" ;
WorldPositionConstraint kc_rfoot_pos(&model, r_foot, r_foot_pt, rfoot_pos_lb,
rfoot_pos_ub, tspan);
WorldQuatConstraint kc_rfoot_quat(&model, r_foot, quat_des, tol, tspan);
// 6 Right Position Constraints (actual reaching constraint)
int r_hand = model.findLinkId("r_hand");
Vector3d r_hand_pt = Vector3d::Zero();
Vector3d rhand_pos0;
// Vector3d rhand_pos0 = model.forwardKin(r_hand_pt, r_hand, 0, 0, 0).value();
rhand_pos0(0) = 0.2;
rhand_pos0(1) = -0.5;
rhand_pos0(2) = 0.4;
Vector3d rhand_pos_lb = rhand_pos0;
rhand_pos_lb(0) += 0.05;
rhand_pos_lb(1) += 0.05;
rhand_pos_lb(2) += 0.05;
Vector3d rhand_pos_ub = rhand_pos_lb;
rhand_pos_ub(2) += 0.05;
// std::cout << rhand_pos_ub.transpose() << " rhand\n" ;
WorldPositionConstraint kc_rhand(&model, r_hand, r_hand_pt, rhand_pos_lb,
rhand_pos_ub, tspan);
// 7 QuasiStatic Constraints
QuasiStaticConstraint kc_quasi(&model, tspan);
kc_quasi.setShrinkFactor(0.2);
kc_quasi.setActive(true);
Eigen::Matrix3Xd l_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);
l_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780, 0.0624, -0.0624, 0.0624,
-0.0624, -0.0811, -0.0811, -0.0811, -0.0811;
kc_quasi.addContact(1, &l_foot, &l_foot_pts);
Eigen::Matrix3Xd r_foot_pts = Eigen::Matrix3Xd::Zero(3, 4);
r_foot_pts << -0.0820, -0.0820, 0.1780, 0.1780, 0.0624, -0.0624, 0.0624,
-0.0624, -0.0811, -0.0811, -0.0811, -0.0811;
kc_quasi.addContact(1, &r_foot, &r_foot_pts);
std::vector<RigidBodyConstraint*> constraint_array;
constraint_array.push_back(&kc_quasi);
constraint_array.push_back(&kc_posture_knees);
constraint_array.push_back(&kc_lfoot_pos);
constraint_array.push_back(&kc_lfoot_quat);
constraint_array.push_back(&kc_rfoot_pos);
constraint_array.push_back(&kc_rfoot_quat);
constraint_array.push_back(&kc_rhand);
constraint_array.push_back(&kc_posture_larm);
constraint_array.push_back(&kc_posture_back);
IKoptions ikoptions(&model);
VectorXd q_sol(model.num_positions);
int info;
vector<string> infeasible_constraint;
inverseKin(&model, qstar, qstar, constraint_array.size(),
constraint_array.data(), ikoptions, &q_sol, &info,
&infeasible_constraint);
printf("INFO = %d\n", info);
EXPECT_EQ(info, 1);
/////////////////////////////////////////
KinematicsCache<double> cache = model.doKinematics(q_sol);
Vector3d com = model.centerOfMass(cache);
printf("%5.6f\n%5.6f\n%5.6f\n", com(0), com(1), com(2));
EXPECT_TRUE(CompareMatrices(com, Vector3d(0.074890, -0.037551, 1.008913),
1e-6, MatrixCompareType::absolute));
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "ZoneServer.h"
//#include "Zone.h"
#include "ZoneClientSession.h"
//#include "ZoneClientSessionImplementation.h"
//#include "objects/player/Player.h"
ZoneClientSessionImplementation::ZoneClientSessionImplementation(DatagramServiceThread* serv, Socket* sock, SocketAddress* addr)
: ManagedObjectImplementation(), BaseClientProxy(sock, *addr) {
init(serv);
//player = NULL;
sessionKey = 0;
disconnecting = false;
StringBuffer loggingname;
loggingname << "ZoneClientSession " << addr->getFullIPAddress();
setLoggingName(loggingname.toString());
setLogging(false);
}
void ZoneClientSessionImplementation::disconnect() {
BaseClient::disconnect();
}
void ZoneClientSessionImplementation::lock(bool doLock) {
BaseClient::lock(doLock);
}
void ZoneClientSessionImplementation::unlock(bool doLock) {
BaseClient::unlock(doLock);
}
void ZoneClientSessionImplementation::sendMessage(BaseMessage* msg) {
BaseClientProxy::sendPacket((BasePacket*) msg);
}
void ZoneClientSessionImplementation::sendMessage(StandaloneBaseMessage* msg) {
BaseClientProxy::sendPacket((BasePacket*) msg);
}
/*String& ZoneClientSessionImplementation::getAddress() {
return BaseClientProxy::getAddress();
}*/
void ZoneClientSessionImplementation::disconnect(bool doLock) {
lock(doLock);
/*if (disconnecting) {
unlock(doLock);
return;
}
disconnecting = true;
if (hasError || !clientDisconnected) {
if (player != NULL) {
unlock();
player->disconnect(false, true);
lock();
}
closeConnection(true, false);
} else if (player != NULL) {
unlock();
if (player->isLoggingOut())
player->logout();
else {
try {
//player->wlock();
player->setLinkDead();
//player->unlock();
} catch (...) {
//player->unlock();
}
closeConnection(true, true);
}
lock();
}*/
unlock(doLock);
}
void ZoneClientSessionImplementation::closeConnection(bool lockPlayer, bool doLock) {
try {
lock(doLock);
info("disconnecting client \'" + ip + "\'");
/*ZoneServer* server = NULL;
if (player != NULL) {
ZoneServer* srv = NULL;
ManagedReference<Player> play = player;
if (lockPlayer)
unlock();
try {
play->wlock(lockPlayer);
if (play->getZone() != NULL)
srv = play->getZone()->getZoneServer();
play->setClient(NULL);
play->unlock(lockPlayer);
} catch (...) {
play->unlock(lockPlayer);
}
if (lockPlayer)
lock();
server = srv;
player = NULL;
}
BaseClient::disconnect(false);
if (server != NULL) {
server->addTotalSentPacket(getSentPacketCount());
server->addTotalResentPacket(getResentPacketCount());
}*/
unlock(doLock);
} catch (...) {
unlock(doLock);
}
}
/*void ZoneClientSessionImplementation::acquire() {
_this->acquire();
}
void ZoneClientSessionImplementation::release() {
_this->release();
}*/
<commit_msg>[fixed] crash<commit_after>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "ZoneServer.h"
//#include "Zone.h"
#include "ZoneClientSession.h"
//#include "ZoneClientSessionImplementation.h"
//#include "objects/player/Player.h"
ZoneClientSessionImplementation::ZoneClientSessionImplementation(DatagramServiceThread* serv, Socket* sock, SocketAddress* addr)
: ManagedObjectImplementation(), BaseClientProxy(sock, *addr) {
init(serv);
player = NULL;
sessionKey = 0;
disconnecting = false;
StringBuffer loggingname;
loggingname << "ZoneClientSession " << addr->getFullIPAddress();
setLoggingName(loggingname.toString());
setLogging(false);
}
void ZoneClientSessionImplementation::disconnect() {
BaseClient::disconnect();
}
void ZoneClientSessionImplementation::lock(bool doLock) {
BaseClient::lock(doLock);
}
void ZoneClientSessionImplementation::unlock(bool doLock) {
BaseClient::unlock(doLock);
}
void ZoneClientSessionImplementation::sendMessage(BaseMessage* msg) {
BaseClientProxy::sendPacket((BasePacket*) msg);
}
void ZoneClientSessionImplementation::sendMessage(StandaloneBaseMessage* msg) {
BaseClientProxy::sendPacket((BasePacket*) msg);
}
/*String& ZoneClientSessionImplementation::getAddress() {
return BaseClientProxy::getAddress();
}*/
void ZoneClientSessionImplementation::disconnect(bool doLock) {
lock(doLock);
/*if (disconnecting) {
unlock(doLock);
return;
}
disconnecting = true;
if (hasError || !clientDisconnected) {
if (player != NULL) {
unlock();
player->disconnect(false, true);
lock();
}
closeConnection(true, false);
} else if (player != NULL) {
unlock();
if (player->isLoggingOut())
player->logout();
else {
try {
//player->wlock();
player->setLinkDead();
//player->unlock();
} catch (...) {
//player->unlock();
}
closeConnection(true, true);
}
lock();
}*/
unlock(doLock);
}
void ZoneClientSessionImplementation::closeConnection(bool lockPlayer, bool doLock) {
try {
lock(doLock);
info("disconnecting client \'" + ip + "\'");
/*ZoneServer* server = NULL;
if (player != NULL) {
ZoneServer* srv = NULL;
ManagedReference<Player> play = player;
if (lockPlayer)
unlock();
try {
play->wlock(lockPlayer);
if (play->getZone() != NULL)
srv = play->getZone()->getZoneServer();
play->setClient(NULL);
play->unlock(lockPlayer);
} catch (...) {
play->unlock(lockPlayer);
}
if (lockPlayer)
lock();
server = srv;
player = NULL;
}
BaseClient::disconnect(false);
if (server != NULL) {
server->addTotalSentPacket(getSentPacketCount());
server->addTotalResentPacket(getResentPacketCount());
}*/
unlock(doLock);
} catch (...) {
unlock(doLock);
}
}
/*void ZoneClientSessionImplementation::acquire() {
_this->acquire();
}
void ZoneClientSessionImplementation::release() {
_this->release();
}*/
<|endoftext|>
|
<commit_before>GenerateDocumentation01() {
//This macro auto-generates documentation (twiki-style)
//based on all OADBs currently deployed in the AliPhysics
//directory specified here:
TString lPathToOADBs = "$HOME/alice/ali-master/AliPhysics/OADB/COMMON/MULTIPLICITY/data/";
cout<<"Expanding path name..."<<endl;
gSystem->ExpandPathName( lPathToOADBs );
cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl;
//Start: determine list of available OADBs
TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data());
TList *files = dir.GetListOfFiles();
//sorting...
files->Sort();
//Number of automatically found OADB files
Long_t lNOADBs = 0;
//Output text file
TString lOutputDoc = "doc.txt";
ofstream lDocs;
lDocs.open ( lOutputDoc.Data() );
if (files) {
TSystemFile *file;
TString fname;
TIter next(files);
while ((file=(TSystemFile*)next())) {
fname = file->GetName();
TString lProdName = fname;
TString lCalibRuns = "";
TString lTime = "";
TString lEvSels = "";
TString lEstims = "";
TString lEstimPerRun = "";
lProdName.ReplaceAll("OADB-","");
lProdName.ReplaceAll(".root","");
if (!file->IsDirectory() && fname.EndsWith(".root")) {
cout<<"======================================================"<<endl;
cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl;
cout<<" -> Opening OADB and checking for information ... "<<endl;
//Mod time
//Long_t id,size,flags,mt;
//gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt);
//TTimeStamp st(mt);
//cout<<"Date : "<<st.GetDate()<<endl;
//lTime.Append(Form("%i",st.GetDate()));
//Modification time, as per git command:
// git log -1 --format="%ai" -- OADB-blablabla.root
lTime = gSystem->GetFromPipe(Form("cd %s; git log -1 --format=\"%%ai\" -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data()));
cout<<"======================================================"<<endl;
cout<<lTime.Data()<<endl;
cout<<"======================================================"<<endl;
TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data()));
AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel");
cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl;
AliOADBMultSelection * oadbMultSelection = 0x0;
for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) {
//Acquire the MultSelection Object for this run and get the specific
//calibration information (Anchor point and anchor percentile) for each estimator
oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir);
//Get estimator info
lCalibRuns.Append("<element title=\"");
for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName();
Float_t lAP = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint();
Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile();
lCalibRuns.Append(Form("%s",def.Data())); //Name
if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) {
lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics
} else {
lCalibRuns.Append(": Unanchored"); //Characteristics
}
if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 )
lCalibRuns.Append(" "); //Name
}
lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir)));
if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", ");
}
cout<<" ---> Detected calibrated runs: "<<endl;
cout<<lCalibRuns.Data()<<endl;
cout<<" ---> Acquiring example object by index... "<<endl;
oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0);
cout<<" -> Adding: Event selection information ..."<<endl;
if( oadbMultSelection ) {
lEvSels.Append(Form("Vertex position |z| < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) );
if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)");
if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL>0 with SPD tracklets");
if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut");
if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection");
if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK");
if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV");
oadbMultSelection->GetMultSelection()->PrintInfo();
for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
//syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div>
TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition();
cout<<"Def = "<<def.Data()<<endl;
//Replace > and <s for html code
def.ReplaceAll("<","<");
def.ReplaceAll(">",">");
lEstims.Append("<element title=\"");
lEstims.Append(Form("%s",def.Data()));
lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName()));
if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", ");
}
}
cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl;
//Appending event selection as a tooltip next to the dataset name
lProdName.Prepend("*");
lProdName.Append("*");
lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() ));
lProdName.Append("> %ICONURL{help}% </element>");
cout<<" ---> Estimator string: "<<lEstims.Data()<<endl;
cout<<" -> Adding: estimator definition information ..."<<endl;
cout<<"======================================================"<<endl;
//Print this in this format:
//| LHCxxx | RUNLIST | xx/xx/xxx | ESTIMATORS |
lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" | "<<lTime.Data()<<" | "<<lEstims.Data()<<" |"<<endl;
}
}
}
}
<commit_msg>Update macro to auto-generate AliMultSelectionCalibStatus documentation<commit_after>GenerateDocumentation01() {
//This macro auto-generates documentation (twiki-style)
//based on all OADBs currently deployed in the AliPhysics
//directory specified here:
TString lPathToOADBs = "$HOME/alice/ali-master/AliPhysics/OADB/COMMON/MULTIPLICITY/data/";
cout<<"Expanding path name..."<<endl;
gSystem->ExpandPathName( lPathToOADBs );
cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl;
//Start: determine list of available OADBs
TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data());
TList *files = dir.GetListOfFiles();
//sorting...
files->Sort();
//Number of automatically found OADB files
Long_t lNOADBs = 0;
//Output text file
TString lOutputDoc = "doc.txt";
ofstream lDocs;
lDocs.open ( lOutputDoc.Data() );
if (files) {
TSystemFile *file;
TString fname;
TIter next(files);
while ((file=(TSystemFile*)next())) {
fname = file->GetName();
TString lProdName = fname;
TString lCalibRuns = "";
TString lTime = "";
TString lCommitMessage = "";
TString lEvSels = "";
TString lEstims = "";
TString lEstimPerRun = "";
lProdName.ReplaceAll("OADB-","");
lProdName.ReplaceAll(".root","");
if (!file->IsDirectory() && fname.EndsWith(".root")) {
cout<<"======================================================"<<endl;
cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl;
cout<<" -> Opening OADB and checking for information ... "<<endl;
//Mod time
//Long_t id,size,flags,mt;
//gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt);
//TTimeStamp st(mt);
//cout<<"Date : "<<st.GetDate()<<endl;
//lTime.Append(Form("%i",st.GetDate()));
//Modification time, as per git command:
// git log -1 --format="%ai" -- OADB-blablabla.root
lTime = gSystem->GetFromPipe(Form("cd %s; git log -1 --format=\"%%ai\" -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data()));
lCommitMessage = gSystem->GetFromPipe(Form("cd %s; git log -1 --oneline -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data()));
cout<<"======================================================"<<endl;
cout<<lTime.Data()<<endl;
cout<<"Commit Message Text: "<<lCommitMessage.Data()<<endl;
//Will now append lCommitMessage to lTime
lCommitMessage.Prepend(" <noautolink><element title=\"Last Commit Message: ");
lCommitMessage.Append("\"> %ICONURL{help}% </element></noautolink>");
lTime.Append(lCommitMessage);
cout<<" lTime string, final: "<<lTime.Data()<<endl;
cout<<"======================================================"<<endl;
TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data()));
AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel");
cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl;
AliOADBMultSelection * oadbMultSelection = 0x0;
for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) {
//Acquire the MultSelection Object for this run and get the specific
//calibration information (Anchor point and anchor percentile) for each estimator
oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir);
//Get estimator info
lCalibRuns.Append("<element title=\"");
for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName();
Float_t lAP = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint();
Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile();
lCalibRuns.Append(Form("%s",def.Data())); //Name
if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) {
lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics
} else {
lCalibRuns.Append(": Unanchored"); //Characteristics
}
if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 )
lCalibRuns.Append(" "); //Name
}
lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir)));
if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", ");
}
cout<<" ---> Detected calibrated runs: "<<endl;
cout<<lCalibRuns.Data()<<endl;
cout<<" ---> Acquiring example object by index... "<<endl;
oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0);
cout<<" -> Adding: Event selection information ..."<<endl;
if( oadbMultSelection ) {
lEvSels.Append(Form("Vertex position |z| < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) );
if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)");
if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL>0 with SPD tracklets");
if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut");
if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection");
if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK");
if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV");
oadbMultSelection->GetMultSelection()->PrintInfo();
for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
//syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div>
TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition();
cout<<"Def = "<<def.Data()<<endl;
//Replace > and <s for html code
def.ReplaceAll("<","<");
def.ReplaceAll(">",">");
lEstims.Append("<element title=\"");
lEstims.Append(Form("%s",def.Data()));
lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName()));
if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", ");
}
}
cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl;
//Appending event selection as a tooltip next to the dataset name
lProdName.Prepend("*");
lProdName.Append("*");
lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() ));
lProdName.Append("> %ICONURL{help}% </element>");
cout<<" ---> Estimator string: "<<lEstims.Data()<<endl;
cout<<" -> Adding: estimator definition information ..."<<endl;
cout<<"======================================================"<<endl;
//Print this in this format:
//| LHCxxx | RUNLIST | xx/xx/xxx | ESTIMATORS |
lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" | "<<lTime.Data()<<" | "<<lEstims.Data()<<" |"<<endl;
}
}
}
}
<|endoftext|>
|
<commit_before>AliGenerator* CreatePythia8GenCustom( TString lTune = "pp",
Float_t e_cms = 13000.
);
AliGenerator* AddCustomMCGenPythia8( TString lTune = "pp",
Float_t e_cms = 13000.
) {
gSystem->Load("liblhapdf");
AliGenerator *genP = NULL;
genP = CreatePythia8GenCustom(lTune, e_cms);
return genP;
}
AliGenerator* CreatePythia8GenCustom( TString lTune,
Float_t e_cms
) {
gSystem->Load("libpythia6");
gSystem->Load("libEGPythia6");
gSystem->Load("libAliPythia6");
gSystem->Load("libpythia8");
gSystem->Load("libAliPythia8");
gSystem->Setenv("PYTHIA8DATA", gSystem->ExpandPathName("$ALICE_ROOT/PYTHIA8/pythia8/xmldoc"));
gSystem->Setenv("LHAPDF", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF"));
gSystem->Setenv("LHAPATH", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF/PDFsets"));
AliPythia8 *pythia = AliPythia8::Instance(); // For ROOT6 needs to be created before AliGenPythiaPlus object, otherwise ending in "illegal instruction"
AliGenPythiaPlus* gener = new AliGenPythiaPlus(pythia);
std::cout << "*****************************************************************" << std::endl;
std::cout << " Desired PYTHIA configuration: "<< lTune.Data()<< std::endl;
std::cout << "*****************************************************************" << std::endl;
// set process (MB)
gener->SetProcess(kPyMbDefault);
//Centre of mass energy
gener->SetEnergyCMS(e_cms); // in GeV
//random seed based on time
(AliPythia8::Instance())->ReadString("Beams:idA = 2212");
(AliPythia8::Instance())->ReadString("Beams:idB = 2212");
if ( lTune.EqualTo("pp") ){
// Specific settings go here
// default: do nothing, Monash 2013 will do its thing
}
if ( lTune.EqualTo("pp-experimental") ){
// This is me testing a few things
TRandom3 gRand3;
gRand3.SetSeed(0);
Float_t lRandpT0Ref = 2.0+(((Float_t)((Int_t)(10.*gRand3.Uniform())))/10.);
(AliPythia8::Instance())->ReadString(Form("MultipartonInteractions:pT0Ref = %.2f",lRandpT0Ref));
std::cout << " Random pT0Ref: "<< lRandpT0Ref << std::endl;
}
if ( lTune.EqualTo("pp-moreqcd") ){
std::cout << " Setting pp-moreqcd parameters..." << std::endl;
//Paper reference: https://arxiv.org/pdf/1505.01681.pdf ("mode 0")
//===========================================================================
(AliPythia8::Instance())->ReadString("StringPT:sigma = 0.335");
(AliPythia8::Instance())->ReadString("StringZ:aLund = 0.36");
(AliPythia8::Instance())->ReadString("StringZ:bLund = 0.56");
(AliPythia8::Instance())->ReadString("StringFlav:probQQtoQ = 0.078");
(AliPythia8::Instance())->ReadString("StringFlav:ProbStoUD = 0.2");
(AliPythia8::Instance())->ReadString("StringFlav:probQQ1toQQ0join = 0.0275,0.0275,0.0275,0.0275");
//===========================================================================
(AliPythia8::Instance())->ReadString("MultiPartonInteractions:pT0Ref = 2.12");
//===========================================================================
(AliPythia8::Instance())->ReadString("BeamRemnants:remnantMode = 1");
(AliPythia8::Instance())->ReadString("BeamRemnants:saturation = 5");
//===========================================================================
(AliPythia8::Instance())->ReadString("ColourReconnection:mode = 1");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowDoubleJunRem = off");
(AliPythia8::Instance())->ReadString("ColourReconnection:m0 = 2.9");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowJunctions = on");
(AliPythia8::Instance())->ReadString("ColourReconnection:junctionCorrection = 1.43");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationMode = 0");
//===========================================================================
}
if ( lTune.EqualTo("pp-nocr") ){
(AliPythia8::Instance())->ReadString("ColourReconnection:reconnect = off");
(AliPythia8::Instance())->ReadString("PartonLevel:earlyResDec = off");
(AliPythia8::Instance())->ReadString("MultipartonInteractions:pT0Ref = 2.30");
}
if ( lTune.EqualTo("pp-ropes") ){
// This is a ropes setting acquired from Peter Christiansen on the Lund thing
//===========================================================================
(AliPythia8::Instance())->ReadString("MultiPartonInteractions:pT0Ref = 2.15");
//===========================================================================
(AliPythia8::Instance())->ReadString("BeamRemnants:remnantMode = 1");
(AliPythia8::Instance())->ReadString("BeamRemnants:saturation = 5");
//===========================================================================
(AliPythia8::Instance())->ReadString("ColourReconnection:mode = 1");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowDoubleJunRem = off");
(AliPythia8::Instance())->ReadString("ColourReconnection:m0 = 0.3");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowJunctions = on");
(AliPythia8::Instance())->ReadString("ColourReconnection:junctionCorrection = 1.2");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationMode = 2");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationPar = 0.18");
//===========================================================================
(AliPythia8::Instance())->ReadString("Ropewalk:RopeHadronization = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doShoving = on");
(AliPythia8::Instance())->ReadString("Ropewalk:tInit = 1.5"); // Propagation time
(AliPythia8::Instance())->ReadString("Ropewalk:deltat = 0.05");
(AliPythia8::Instance())->ReadString("Ropewalk:tShove 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:gAmplitude = 0."); // Set shoving strength to 0 explicitly
(AliPythia8::Instance())->ReadString("Ropewalk:doFlavour = on");
(AliPythia8::Instance())->ReadString("Ropewalk:r0 = 0.5");
(AliPythia8::Instance())->ReadString("Ropewalk:m0 = 0.2");
(AliPythia8::Instance())->ReadString("Ropewalk:beta = 0.1");
//===========================================================================
// Enabling setting of vertex information.
(AliPythia8::Instance())->ReadString("PartonVertex:setVertex = on");
(AliPythia8::Instance())->ReadString("PartonVertex:protonRadius = 0.7");
(AliPythia8::Instance())->ReadString("PartonVertex:emissionWidth = 0.1");
//===========================================================================
}
if ( lTune.EqualTo("pp-shoving") ){
// Enabling flavour ropes, setting model parameters.
// The model is still untuned. These parameter values
// are choosen for illustrative purposes.
// This is a shoving setting acquired from Peter Christiansen on the Lund thing
//===========================================================================
(AliPythia8::Instance())->ReadString("Ropewalk:RopeHadronization = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doShoving = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doFlavour = off");
(AliPythia8::Instance())->ReadString("Ropewalk:rCutOff = 10.0");
(AliPythia8::Instance())->ReadString("Ropewalk:limitMom = on");
(AliPythia8::Instance())->ReadString("Ropewalk:pTcut = 2.0");
(AliPythia8::Instance())->ReadString("Ropewalk:r0 = 0.41");
(AliPythia8::Instance())->ReadString("Ropewalk:m0 = 0.2");
(AliPythia8::Instance())->ReadString("Ropewalk:gAmplitude = 10.0");
(AliPythia8::Instance())->ReadString("Ropewalk:gExponent = 1.0");
(AliPythia8::Instance())->ReadString("Ropewalk:deltat = 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:tShove = 1.");
(AliPythia8::Instance())->ReadString("Ropewalk:deltay = 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:tInit = 1.5");
//===========================================================================
// Enabling setting of vertex information.
(AliPythia8::Instance())->ReadString("PartonVertex:setVertex = on");
(AliPythia8::Instance())->ReadString("PartonVertex:protonRadius = 0.7");
(AliPythia8::Instance())->ReadString("PartonVertex:emissionWidth = 0.1");
//===========================================================================
}
(AliPythia8::Instance())->SetDecayLonglived();
return gener;
}
<commit_msg>Fix pTHatMax, set tune number in default case<commit_after>AliGenerator* CreatePythia8GenCustom( TString lTune = "pp",
Float_t e_cms = 13000.
);
AliGenerator* AddCustomMCGenPythia8( TString lTune = "pp",
Float_t e_cms = 13000.
) {
gSystem->Load("liblhapdf");
AliGenerator *genP = NULL;
genP = CreatePythia8GenCustom(lTune, e_cms);
return genP;
}
AliGenerator* CreatePythia8GenCustom( TString lTune,
Float_t e_cms
) {
gSystem->Load("libpythia6");
gSystem->Load("libEGPythia6");
gSystem->Load("libAliPythia6");
gSystem->Load("libpythia8");
gSystem->Load("libAliPythia8");
gSystem->Setenv("PYTHIA8DATA", gSystem->ExpandPathName("$ALICE_ROOT/PYTHIA8/pythia8/xmldoc"));
gSystem->Setenv("LHAPDF", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF"));
gSystem->Setenv("LHAPATH", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF/PDFsets"));
AliPythia8 *pythia = AliPythia8::Instance(); // For ROOT6 needs to be created before AliGenPythiaPlus object, otherwise ending in "illegal instruction"
AliGenPythiaPlus* gener = new AliGenPythiaPlus(pythia);
std::cout << "*****************************************************************" << std::endl;
std::cout << " Desired PYTHIA configuration: "<< lTune.Data()<< std::endl;
std::cout << "*****************************************************************" << std::endl;
// set process (MB)
gener->SetProcess(kPyMbDefault);
//Centre of mass energy
gener->SetEnergyCMS(e_cms); // in GeV
//random seed based on time
(AliPythia8::Instance())->ReadString("Beams:idA = 2212");
(AliPythia8::Instance())->ReadString("Beams:idB = 2212");
(AliPythia8::Instance())->ReadString("PhaseSpace:pTHatMax = -1.0"); //this should be fixed in the constructor
if ( lTune.EqualTo("pp") ){
// Specific settings go here
// default: do nothing, Monash 2013 will do its thing
(AliPythia8::Instance())->ReadString(Form("Tune:pp = %d",14));
}
if ( lTune.EqualTo("pp-experimental") ){
// This is me testing a few things
TRandom3 gRand3;
gRand3.SetSeed(0);
Float_t lRandpT0Ref = 2.0+(((Float_t)((Int_t)(10.*gRand3.Uniform())))/10.);
(AliPythia8::Instance())->ReadString(Form("MultipartonInteractions:pT0Ref = %.2f",lRandpT0Ref));
std::cout << " Random pT0Ref: "<< lRandpT0Ref << std::endl;
}
if ( lTune.EqualTo("pp-moreqcd") ){
std::cout << " Setting pp-moreqcd parameters..." << std::endl;
//Paper reference: https://arxiv.org/pdf/1505.01681.pdf ("mode 0")
//===========================================================================
(AliPythia8::Instance())->ReadString("StringPT:sigma = 0.335");
(AliPythia8::Instance())->ReadString("StringZ:aLund = 0.36");
(AliPythia8::Instance())->ReadString("StringZ:bLund = 0.56");
(AliPythia8::Instance())->ReadString("StringFlav:probQQtoQ = 0.078");
(AliPythia8::Instance())->ReadString("StringFlav:ProbStoUD = 0.2");
(AliPythia8::Instance())->ReadString("StringFlav:probQQ1toQQ0join = 0.0275,0.0275,0.0275,0.0275");
//===========================================================================
(AliPythia8::Instance())->ReadString("MultiPartonInteractions:pT0Ref = 2.12");
//===========================================================================
(AliPythia8::Instance())->ReadString("BeamRemnants:remnantMode = 1");
(AliPythia8::Instance())->ReadString("BeamRemnants:saturation = 5");
//===========================================================================
(AliPythia8::Instance())->ReadString("ColourReconnection:mode = 1");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowDoubleJunRem = off");
(AliPythia8::Instance())->ReadString("ColourReconnection:m0 = 2.9");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowJunctions = on");
(AliPythia8::Instance())->ReadString("ColourReconnection:junctionCorrection = 1.43");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationMode = 0");
//===========================================================================
}
if ( lTune.EqualTo("pp-nocr") ){
(AliPythia8::Instance())->ReadString("ColourReconnection:reconnect = off");
(AliPythia8::Instance())->ReadString("PartonLevel:earlyResDec = off");
(AliPythia8::Instance())->ReadString("MultipartonInteractions:pT0Ref = 2.30");
}
if ( lTune.EqualTo("pp-ropes") ){
// This is a ropes setting acquired from Peter Christiansen on the Lund thing
//===========================================================================
(AliPythia8::Instance())->ReadString("MultiPartonInteractions:pT0Ref = 2.15");
//===========================================================================
(AliPythia8::Instance())->ReadString("BeamRemnants:remnantMode = 1");
(AliPythia8::Instance())->ReadString("BeamRemnants:saturation = 5");
//===========================================================================
(AliPythia8::Instance())->ReadString("ColourReconnection:mode = 1");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowDoubleJunRem = off");
(AliPythia8::Instance())->ReadString("ColourReconnection:m0 = 0.3");
(AliPythia8::Instance())->ReadString("ColourReconnection:allowJunctions = on");
(AliPythia8::Instance())->ReadString("ColourReconnection:junctionCorrection = 1.2");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationMode = 2");
(AliPythia8::Instance())->ReadString("ColourReconnection:timeDilationPar = 0.18");
//===========================================================================
(AliPythia8::Instance())->ReadString("Ropewalk:RopeHadronization = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doShoving = on");
(AliPythia8::Instance())->ReadString("Ropewalk:tInit = 1.5"); // Propagation time
(AliPythia8::Instance())->ReadString("Ropewalk:deltat = 0.05");
(AliPythia8::Instance())->ReadString("Ropewalk:tShove 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:gAmplitude = 0."); // Set shoving strength to 0 explicitly
(AliPythia8::Instance())->ReadString("Ropewalk:doFlavour = on");
(AliPythia8::Instance())->ReadString("Ropewalk:r0 = 0.5");
(AliPythia8::Instance())->ReadString("Ropewalk:m0 = 0.2");
(AliPythia8::Instance())->ReadString("Ropewalk:beta = 0.1");
//===========================================================================
// Enabling setting of vertex information.
(AliPythia8::Instance())->ReadString("PartonVertex:setVertex = on");
(AliPythia8::Instance())->ReadString("PartonVertex:protonRadius = 0.7");
(AliPythia8::Instance())->ReadString("PartonVertex:emissionWidth = 0.1");
//===========================================================================
}
if ( lTune.EqualTo("pp-shoving") ){
// Enabling flavour ropes, setting model parameters.
// The model is still untuned. These parameter values
// are choosen for illustrative purposes.
// This is a shoving setting acquired from Peter Christiansen on the Lund thing
//===========================================================================
(AliPythia8::Instance())->ReadString("Ropewalk:RopeHadronization = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doShoving = on");
(AliPythia8::Instance())->ReadString("Ropewalk:doFlavour = off");
(AliPythia8::Instance())->ReadString("Ropewalk:rCutOff = 10.0");
(AliPythia8::Instance())->ReadString("Ropewalk:limitMom = on");
(AliPythia8::Instance())->ReadString("Ropewalk:pTcut = 2.0");
(AliPythia8::Instance())->ReadString("Ropewalk:r0 = 0.41");
(AliPythia8::Instance())->ReadString("Ropewalk:m0 = 0.2");
(AliPythia8::Instance())->ReadString("Ropewalk:gAmplitude = 10.0");
(AliPythia8::Instance())->ReadString("Ropewalk:gExponent = 1.0");
(AliPythia8::Instance())->ReadString("Ropewalk:deltat = 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:tShove = 1.");
(AliPythia8::Instance())->ReadString("Ropewalk:deltay = 0.1");
(AliPythia8::Instance())->ReadString("Ropewalk:tInit = 1.5");
//===========================================================================
// Enabling setting of vertex information.
(AliPythia8::Instance())->ReadString("PartonVertex:setVertex = on");
(AliPythia8::Instance())->ReadString("PartonVertex:protonRadius = 0.7");
(AliPythia8::Instance())->ReadString("PartonVertex:emissionWidth = 0.1");
//===========================================================================
}
(AliPythia8::Instance())->SetDecayLonglived();
return gener;
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "common/Data.h"
// ospray
#include "DistributedRaycast.h"
#include "../../common/DistributedModel.h"
#include "../MPILoadBalancer.h"
#include "../../fb/DistributedFrameBuffer.h"
// ispc exports
#include "DistributedRaycast_ispc.h"
namespace ospray {
namespace mpi {
struct RegionInfo
{
int currentRegion;
bool *regionVisible;
RegionInfo() : currentRegion(0), regionVisible(nullptr) {}
};
// DistributedRaycastRenderer definitions /////////////////////////////////
DistributedRaycastRenderer::DistributedRaycastRenderer()
{
ispcEquivalent = ispc::DistributedRaycastRenderer_create(this);
}
void DistributedRaycastRenderer::commit()
{
Renderer::commit();
if (!dynamic_cast<DistributedModel*>(model)) {
throw std::runtime_error("DistributedRaycastRender must use a DistributedModel from "
"the MPIDistributedDevice");
}
}
float DistributedRaycastRenderer::renderFrame(FrameBuffer *fb,
const uint32 channelFlags)
{
using namespace mpicommon;
auto *dfb = dynamic_cast<DistributedFrameBuffer *>(fb);
dfb->setFrameMode(DistributedFrameBuffer::ALPHA_BLEND);
dfb->startNewFrame(errorThreshold);
dfb->beginFrame();
DistributedModel *distribModel = dynamic_cast<DistributedModel*>(model);
ispc::DistributedRaycastRenderer_setRegions(ispcEquivalent,
(ispc::box3f*)distribModel->myRegions.data(),
distribModel->myRegions.size(),
(ispc::box3f*)distribModel->othersRegions.data(),
distribModel->othersRegions.size());
const size_t numRegions = distribModel->myRegions.size()
+ distribModel->othersRegions.size();
const void *perFrameData = beginFrame(dfb);
// This renderer doesn't use per frame data, since we sneak in some tile
// info in this pointer.
assert(!perFrameData);
tasking::parallel_for(dfb->getTotalTiles(), [&](int taskIndex) {
const size_t numTiles_x = fb->getNumTiles().x;
const size_t tile_y = taskIndex / numTiles_x;
const size_t tile_x = taskIndex - tile_y*numTiles_x;
const vec2i tileID(tile_x, tile_y);
const int32 accumID = fb->accumID(tileID);
const bool tileOwner = (taskIndex % numGlobalRanks()) == globalRank();
if (dfb->tileError(tileID) <= errorThreshold) {
return;
}
// The first 0..myRegions.size() - 1 entries are for my regions,
// the following entries are for other nodes regions
RegionInfo regionInfo;
regionInfo.regionVisible = STACK_BUFFER(bool, numRegions);
std::fill(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, false);
Tile __aligned(64) tile(tileID, dfb->size, accumID);
// We use the task of rendering the first region to also fill out the block visiblility list
const int NUM_JOBS = (TILE_SIZE * TILE_SIZE) / RENDERTILE_PIXELS_PER_JOB;
tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
renderTile(®ionInfo, tile, tIdx);
});
if (regionInfo.regionVisible[0]) {
tile.generation = 1;
tile.children = 0;
fb->setTile(tile);
}
// If we own the tile send the background color and the count of children for the
// number of regions projecting to it that will be sent.
if (tileOwner) {
tile.generation = 0;
tile.children = std::count(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, true);
std::fill(tile.r, tile.r + TILE_SIZE * TILE_SIZE, bgColor.x);
std::fill(tile.g, tile.g + TILE_SIZE * TILE_SIZE, bgColor.y);
std::fill(tile.b, tile.b + TILE_SIZE * TILE_SIZE, bgColor.z);
std::fill(tile.a, tile.a + TILE_SIZE * TILE_SIZE, 1.0);
std::fill(tile.z, tile.z + TILE_SIZE * TILE_SIZE, std::numeric_limits<float>::infinity());
fb->setTile(tile);
}
// Render the rest of our regions that project to this tile and ship them off
tile.generation = 1;
tile.children = 0;
for (size_t bid = 1; bid < distribModel->myRegions.size(); ++bid) {
if (!regionInfo.regionVisible[bid]) {
continue;
}
regionInfo.currentRegion = bid;
tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
renderTile(®ionInfo, tile, tIdx);
});
fb->setTile(tile);
}
});
dfb->waitUntilFinished();
endFrame(nullptr, channelFlags);
return dfb->endFrame(errorThreshold);
}
std::string DistributedRaycastRenderer::toString() const
{
return "ospray::mpi::DistributedRaycastRenderer";
}
OSP_REGISTER_RENDERER(DistributedRaycastRenderer, mpi_raycast);
} // ::ospray::mpi
} // ::ospray
<commit_msg>fix gcc-7.2 warning<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "common/Data.h"
// ospray
#include "DistributedRaycast.h"
#include "../../common/DistributedModel.h"
#include "../MPILoadBalancer.h"
#include "../../fb/DistributedFrameBuffer.h"
// ispc exports
#include "DistributedRaycast_ispc.h"
namespace ospray {
namespace mpi {
struct RegionInfo
{
int currentRegion;
bool *regionVisible;
RegionInfo() : currentRegion(0), regionVisible(nullptr) {}
};
// DistributedRaycastRenderer definitions /////////////////////////////////
DistributedRaycastRenderer::DistributedRaycastRenderer()
{
ispcEquivalent = ispc::DistributedRaycastRenderer_create(this);
}
void DistributedRaycastRenderer::commit()
{
Renderer::commit();
if (!dynamic_cast<DistributedModel*>(model)) {
throw std::runtime_error("DistributedRaycastRender must use a DistributedModel from "
"the MPIDistributedDevice");
}
}
float DistributedRaycastRenderer::renderFrame(FrameBuffer *fb,
const uint32 channelFlags)
{
using namespace mpicommon;
auto *dfb = dynamic_cast<DistributedFrameBuffer *>(fb);
dfb->setFrameMode(DistributedFrameBuffer::ALPHA_BLEND);
dfb->startNewFrame(errorThreshold);
dfb->beginFrame();
DistributedModel *distribModel = dynamic_cast<DistributedModel*>(model);
ispc::DistributedRaycastRenderer_setRegions(ispcEquivalent,
(ispc::box3f*)distribModel->myRegions.data(),
distribModel->myRegions.size(),
(ispc::box3f*)distribModel->othersRegions.data(),
distribModel->othersRegions.size());
const size_t numRegions = distribModel->myRegions.size()
+ distribModel->othersRegions.size();
beginFrame(dfb);
tasking::parallel_for(dfb->getTotalTiles(), [&](int taskIndex) {
const size_t numTiles_x = fb->getNumTiles().x;
const size_t tile_y = taskIndex / numTiles_x;
const size_t tile_x = taskIndex - tile_y*numTiles_x;
const vec2i tileID(tile_x, tile_y);
const int32 accumID = fb->accumID(tileID);
const bool tileOwner = (taskIndex % numGlobalRanks()) == globalRank();
if (dfb->tileError(tileID) <= errorThreshold) {
return;
}
// The first 0..myRegions.size() - 1 entries are for my regions,
// the following entries are for other nodes regions
RegionInfo regionInfo;
regionInfo.regionVisible = STACK_BUFFER(bool, numRegions);
std::fill(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, false);
Tile __aligned(64) tile(tileID, dfb->size, accumID);
// We use the task of rendering the first region to also fill out the block visiblility list
const int NUM_JOBS = (TILE_SIZE * TILE_SIZE) / RENDERTILE_PIXELS_PER_JOB;
tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
renderTile(®ionInfo, tile, tIdx);
});
if (regionInfo.regionVisible[0]) {
tile.generation = 1;
tile.children = 0;
fb->setTile(tile);
}
// If we own the tile send the background color and the count of children for the
// number of regions projecting to it that will be sent.
if (tileOwner) {
tile.generation = 0;
tile.children = std::count(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, true);
std::fill(tile.r, tile.r + TILE_SIZE * TILE_SIZE, bgColor.x);
std::fill(tile.g, tile.g + TILE_SIZE * TILE_SIZE, bgColor.y);
std::fill(tile.b, tile.b + TILE_SIZE * TILE_SIZE, bgColor.z);
std::fill(tile.a, tile.a + TILE_SIZE * TILE_SIZE, 1.0);
std::fill(tile.z, tile.z + TILE_SIZE * TILE_SIZE, std::numeric_limits<float>::infinity());
fb->setTile(tile);
}
// Render the rest of our regions that project to this tile and ship them off
tile.generation = 1;
tile.children = 0;
for (size_t bid = 1; bid < distribModel->myRegions.size(); ++bid) {
if (!regionInfo.regionVisible[bid]) {
continue;
}
regionInfo.currentRegion = bid;
tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
renderTile(®ionInfo, tile, tIdx);
});
fb->setTile(tile);
}
});
dfb->waitUntilFinished();
endFrame(nullptr, channelFlags);
return dfb->endFrame(errorThreshold);
}
std::string DistributedRaycastRenderer::toString() const
{
return "ospray::mpi::DistributedRaycastRenderer";
}
OSP_REGISTER_RENDERER(DistributedRaycastRenderer, mpi_raycast);
} // ::ospray::mpi
} // ::ospray
<|endoftext|>
|
<commit_before>#include "task_manager_mpi.hpp"
namespace TaskDistribution {
MPITaskManager::MPITaskManager(boost::mpi::communicator& world,
MPIHandler& handler, MPIObjectArchive<Key>& archive,
MPIComputingUnitManager& unit_manager):
MPITaskManager(Tags(), world, handler, archive, unit_manager) { }
MPITaskManager::MPITaskManager(Tags const& tags,
boost::mpi::communicator& world, MPIHandler& handler,
MPIObjectArchive<Key>& archive, MPIComputingUnitManager& unit_manager):
TaskManager(archive, unit_manager),
tags_(tags),
world_(world),
handler_(handler),
archive_(archive),
unit_manager_(unit_manager),
finished_(false),
tasks_per_node_(world_.size()-1, 0) {
handler.insert(tags_.finish,
std::bind(&MPITaskManager::process_finish, this,
std::placeholders::_1, tags.finish));
handler.insert(tags_.key_update,
std::bind(&MPITaskManager::process_key_update, this,
std::placeholders::_1, tags.key_update));
clear_task_creation_handler();
clear_task_begin_handler();
clear_task_end_handler();
archive_.set_insert_filter(
[](Key const& key, boost::mpi::communicator& world)
{ return key.is_valid() && world.rank() == 0; });
}
MPITaskManager::~MPITaskManager() { }
void MPITaskManager::run() {
if (world_.size() > 1) {
if (world_.rank() == 0)
run_master();
else
run_slave();
} else
run_single();
}
void MPITaskManager::run_master() {
size_t n_running = 0;
// Process whatever is left for MPI first
handler_.run();
n_running += allocate_tasks();
while (!ready_.empty() || n_running != 0) {
// Process MPI stuff until a task has ended
unit_manager_.clear_tasks_ended();
do {
handler_.run();
} while (unit_manager_.get_tasks_ended().empty());
MPIComputingUnitManager::TasksList const& finished_tasks =
unit_manager_.get_tasks_ended();
for (auto& it : finished_tasks) {
task_completed(it.first);
int slave = it.second;
--tasks_per_node_[slave-1];
--n_running;
}
n_running += allocate_tasks();
}
broadcast_finish();
}
size_t MPITaskManager::allocate_tasks() {
size_t n_running = 0;
bool allocated_a_task = true;
while (!ready_.empty() && allocated_a_task) {
allocated_a_task = false;
for (int i = 1; i < world_.size(); i++) {
// Maximum fixed allocation. TODO: not fixed
if (tasks_per_node_[i-1] < 1) {
// Tries to send task to slave. Fails if ready_.empty() after running
// local tasks.
if (!send_next_task(i))
break;
allocated_a_task = true;
tasks_per_node_[i-1]++;
n_running++;
}
}
}
return n_running;
}
void MPITaskManager::run_slave() {
while (!finished_)
unit_manager_.process_remote();
}
bool MPITaskManager::send_next_task(int slave) {
bool got_task_for_remote = false;
Key task_key;
TaskEntry entry;
while (!got_task_for_remote) {
if (ready_.empty())
return false;
task_key = ready_.front();
ready_.pop_front();
archive_.load(task_key, entry);
// If we already computed this task, gets the next one
if (!entry.result_key.is_valid()) {
if (entry.run_locally) {
task_begin_handler_(task_key);
unit_manager_.process_local(entry);
task_completed(task_key);
}
else
got_task_for_remote = true;
}
}
task_begin_handler_(task_key);
unit_manager_.send_remote(entry, slave);
return true;
}
bool MPITaskManager::process_finish(int source, int tag) {
world_.recv(source, tag, finished_);
return true;
}
bool MPITaskManager::process_key_update(int source, int tag) {
size_t key;
world_.recv(source, tag, key);
Key::next_obj = std::max(Key::next_obj, key);
return true;
}
void MPITaskManager::broadcast_finish() {
for (int i = 1; i < world_.size(); i++)
world_.send(i, tags_.finish, true);
}
size_t MPITaskManager::id() const {
return world_.rank();
}
void MPITaskManager::update_used_keys(
std::map<int, size_t> const& used_keys) {
for (auto it = used_keys.begin(); it != used_keys.end(); ++it) {
if (it->first == world_.rank())
Key::next_obj = std::max(Key::next_obj, it->second + 1);
else
world_.send(it->first, tags_.key_update, it->second + 1);
}
}
Key MPITaskManager::new_key(Key::Type type) {
return Key::new_key(world_, type);
}
};
<commit_msg>Fixed bug when running without mpi but have multiple node_id in archive.<commit_after>#include "task_manager_mpi.hpp"
namespace TaskDistribution {
MPITaskManager::MPITaskManager(boost::mpi::communicator& world,
MPIHandler& handler, MPIObjectArchive<Key>& archive,
MPIComputingUnitManager& unit_manager):
MPITaskManager(Tags(), world, handler, archive, unit_manager) { }
MPITaskManager::MPITaskManager(Tags const& tags,
boost::mpi::communicator& world, MPIHandler& handler,
MPIObjectArchive<Key>& archive, MPIComputingUnitManager& unit_manager):
TaskManager(archive, unit_manager),
tags_(tags),
world_(world),
handler_(handler),
archive_(archive),
unit_manager_(unit_manager),
finished_(false),
tasks_per_node_(world_.size()-1, 0) {
handler.insert(tags_.finish,
std::bind(&MPITaskManager::process_finish, this,
std::placeholders::_1, tags.finish));
handler.insert(tags_.key_update,
std::bind(&MPITaskManager::process_key_update, this,
std::placeholders::_1, tags.key_update));
clear_task_creation_handler();
clear_task_begin_handler();
clear_task_end_handler();
archive_.set_insert_filter(
[](Key const& key, boost::mpi::communicator& world)
{ return key.is_valid() && world.rank() == 0; });
}
MPITaskManager::~MPITaskManager() { }
void MPITaskManager::run() {
if (world_.size() > 1) {
if (world_.rank() == 0)
run_master();
else
run_slave();
} else
run_single();
}
void MPITaskManager::run_master() {
size_t n_running = 0;
// Process whatever is left for MPI first
handler_.run();
n_running += allocate_tasks();
while (!ready_.empty() || n_running != 0) {
// Process MPI stuff until a task has ended
unit_manager_.clear_tasks_ended();
do {
handler_.run();
} while (unit_manager_.get_tasks_ended().empty());
MPIComputingUnitManager::TasksList const& finished_tasks =
unit_manager_.get_tasks_ended();
for (auto& it : finished_tasks) {
task_completed(it.first);
int slave = it.second;
--tasks_per_node_[slave-1];
--n_running;
}
n_running += allocate_tasks();
}
broadcast_finish();
}
size_t MPITaskManager::allocate_tasks() {
size_t n_running = 0;
bool allocated_a_task = true;
while (!ready_.empty() && allocated_a_task) {
allocated_a_task = false;
for (int i = 1; i < world_.size(); i++) {
// Maximum fixed allocation. TODO: not fixed
if (tasks_per_node_[i-1] < 1) {
// Tries to send task to slave. Fails if ready_.empty() after running
// local tasks.
if (!send_next_task(i))
break;
allocated_a_task = true;
tasks_per_node_[i-1]++;
n_running++;
}
}
}
return n_running;
}
void MPITaskManager::run_slave() {
while (!finished_)
unit_manager_.process_remote();
}
bool MPITaskManager::send_next_task(int slave) {
bool got_task_for_remote = false;
Key task_key;
TaskEntry entry;
while (!got_task_for_remote) {
if (ready_.empty())
return false;
task_key = ready_.front();
ready_.pop_front();
archive_.load(task_key, entry);
// If we already computed this task, gets the next one
if (!entry.result_key.is_valid()) {
if (entry.run_locally) {
task_begin_handler_(task_key);
unit_manager_.process_local(entry);
task_completed(task_key);
}
else
got_task_for_remote = true;
}
}
task_begin_handler_(task_key);
unit_manager_.send_remote(entry, slave);
return true;
}
bool MPITaskManager::process_finish(int source, int tag) {
world_.recv(source, tag, finished_);
return true;
}
bool MPITaskManager::process_key_update(int source, int tag) {
size_t key;
world_.recv(source, tag, key);
Key::next_obj = std::max(Key::next_obj, key);
return true;
}
void MPITaskManager::broadcast_finish() {
for (int i = 1; i < world_.size(); i++)
world_.send(i, tags_.finish, true);
}
size_t MPITaskManager::id() const {
return world_.rank();
}
void MPITaskManager::update_used_keys(
std::map<int, size_t> const& used_keys) {
if (world_.size() == 1)
TaskManager::update_used_keys(used_keys);
else {
for (auto it = used_keys.begin(); it != used_keys.end(); ++it) {
if (it->first == world_.rank())
Key::next_obj = std::max(Key::next_obj, it->second + 1);
else
world_.send(it->first, tags_.key_update, it->second + 1);
}
}
}
Key MPITaskManager::new_key(Key::Type type) {
return Key::new_key(world_, type);
}
};
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <costmap_2d/costmap_2d_ros.h>
#include <navfn/navfn_ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <nav_msgs/Path.h>
#include <string>
#include "movebase_state_service/MovebaseStateService.h"
class state_service {
public:
ros::NodeHandle n;
ros::ServiceServer service;
geometry_msgs::PoseStampedConstPtr last_goal;
geometry_msgs::PoseConstPtr last_pose;
nav_msgs::Path::ConstPtr global_last_path;
nav_msgs::Path::ConstPtr local_last_path;
std::string snapshot_folder;
int counter;
ros::Subscriber goal_sub;
ros::Subscriber pose_sub;
ros::Subscriber global_path_sub;
ros::Subscriber local_path_sub;
std::string image_input;
std::string global_costmap_input;
std::string local_costmap_input;
std::string goal_input;
std::string pose_input;
std::string global_path_input;
std::string local_path_input;
state_service(const std::string& name)
{
ros::NodeHandle pn("~");
pn.param<std::string>("image_input", image_input, std::string("/head_xtion/rgb/image_color"));
pn.param<std::string>("global_costmap_input", global_costmap_input, std::string("/move_base/global_costmap/costmap"));
pn.param<std::string>("local_costmap_input", local_costmap_input, std::string("/move_base/local_costmap/costmap"));
pn.param<std::string>("snapshot_folder", snapshot_folder, std::string(getenv("HOME")) + std::string("/.ros/movebase_state_service"));
pn.param<std::string>("goal_input", goal_input, std::string("/move_base/current_goal"));
pn.param<std::string>("pose_input", pose_input, std::string("/robot_pose"));
pn.param<std::string>("global_path_input", global_path_input, std::string("/move_base/DWAPlannerROS/global_plan"));
pn.param<std::string>("local_path_input", local_path_input, std::string("/move_base/DWAPlannerROS/local_plan"));
goal_sub = n.subscribe(goal_input, 1, &state_service::goal_callback, this);
pose_sub = n.subscribe(pose_input, 1, &state_service::pose_callback, this);
global_path_sub = n.subscribe(global_path_input, 1, &state_service::global_path_callback, this);
local_path_sub = n.subscribe(local_path_input, 1, &state_service::local_path_callback, this);
counter = 0;
service = n.advertiseService(name, &state_service::service_callback, this);
}
void goal_callback(const geometry_msgs::PoseStampedConstPtr& goal_msg)
{
last_goal = goal_msg;
}
void pose_callback(const geometry_msgs::PoseConstPtr& pose_msg)
{
last_pose = pose_msg;
}
void global_path_callback(const nav_msgs::Path::ConstPtr& path_msg)
{
global_last_path = path_msg;
}
void local_path_callback(const nav_msgs::Path::ConstPtr& path_msg)
{
local_last_path = path_msg;
}
void color_around_point(cv::Mat& map, int x, int y, int c)
{
for (int i = x - 2; i < x + 3; ++i) {
for (int j = y - 2; j < y + 3; ++j) {
// add out-of-bounds check
if (i < 0 || i >= map.cols || j < 0 || j >= map.rows) {
continue;
}
map.at<cv::Vec3b>(j, i)[0] = 0;
map.at<cv::Vec3b>(j, i)[1] = 0;
map.at<cv::Vec3b>(j, i)[2] = 0;
map.at<cv::Vec3b>(j, i)[c] = 255;
}
}
}
void save_map(sensor_msgs::Image& image_msg, const std::string& map_file, const std::string& rgb_map_file,
nav_msgs::OccupancyGrid::ConstPtr& last_map, nav_msgs::Path::ConstPtr& last_path, bool save_to_disk)
{
// save map
double map_height = last_map->info.height;
double map_width = last_map->info.width;
double map_origin_x = last_map->info.origin.position.x;
double map_origin_y = last_map->info.origin.position.y;
double map_res = last_map->info.resolution;
ROS_INFO_STREAM("Map width x height: " << map_width << " x " << map_height);
costmap_2d::Costmap2D map(map_width, map_height, map_res, map_origin_x, map_origin_y);
cv::Mat image = cv::Mat::zeros(map_height, map_width, CV_8UC3);
// incoming dynamic map to Costmap2D
for(int i = 0; i < map_width; i++) {
for(int j = 0; j < map_height; j++) {
map.setCost(i, j, last_map->data[map.getIndex(i, j)]);
image.at<cv::Vec3b>(j, i)[0] = last_map->data[map.getIndex(i, j)];
image.at<cv::Vec3b>(j, i)[1] = last_map->data[map.getIndex(i, j)];
image.at<cv::Vec3b>(j, i)[2] = last_map->data[map.getIndex(i, j)];
}
}
double x, y;
int map_x, map_y;
if (last_path) {
for (size_t i = 0; i < last_path->poses.size(); ++i) {
x = last_path->poses[i].pose.position.x;
y = last_path->poses[i].pose.position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 1);
}
}
if (last_goal) {
x = last_goal->pose.position.x;
y = last_goal->pose.position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 2);
}
if (last_pose) {
x = last_pose->position.x;
y = last_pose->position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 0);
}
if (save_to_disk) {
map.saveMap(map_file);
// use lossless png compression
std::vector<int> compression;
compression.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression.push_back(0); // no compression
cv::imwrite(rgb_map_file, image, compression);
}
std_msgs::Header header;
header.seq = counter;
header.stamp = ros::Time::now();
header.frame_id = "/map";
cv_bridge::CvImage global_costmap_tmp = cv_bridge::CvImage(header, "8UC3", image);
global_costmap_tmp.toImageMsg(image_msg);
}
bool service_callback(movebase_state_service::MovebaseStateService::Request& req,
movebase_state_service::MovebaseStateService::Response& res)
{
sensor_msgs::Image::ConstPtr last_img = ros::topic::waitForMessage<sensor_msgs::Image>(image_input, n, ros::Duration(5));
if (!last_img) {
return false;
}
if (req.save_to_disk) {
// save image
boost::shared_ptr<sensor_msgs::Image> rgb_tracked_object;
cv_bridge::CvImageConstPtr rgb_cv_img_boost_ptr;
try {
rgb_cv_img_boost_ptr = cv_bridge::toCvShare(*last_img, rgb_tracked_object);
}
catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
return false;
}
// use lossless png compression
std::vector<int> compression;
compression.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression.push_back(0); // no compression
std::string image_file = snapshot_folder + "/image" + std::to_string(counter) + ".png";
cv::imwrite(image_file, rgb_cv_img_boost_ptr->image, compression);
}
res.camera_image = *last_img;
nav_msgs::OccupancyGrid::ConstPtr global_costmap_msg = ros::topic::waitForMessage<nav_msgs::OccupancyGrid>(global_costmap_input, n, ros::Duration(5));
if (!global_costmap_msg) {
return false;
}
std::string global_map_file = snapshot_folder + "/global_costmap" + std::to_string(counter) + ".pgm";
std::string global_rgb_map_file = snapshot_folder + "/global_costmap_path" + std::to_string(counter) + ".png";
save_map(res.global_costmap_image, global_map_file, global_rgb_map_file, global_costmap_msg, global_last_path, req.save_to_disk);
nav_msgs::OccupancyGrid::ConstPtr local_costmap_msg = ros::topic::waitForMessage<nav_msgs::OccupancyGrid>(local_costmap_input, n, ros::Duration(5));
if (!local_costmap_msg) {
return false;
}
std::string local_map_file = snapshot_folder + "/local_costmap" + std::to_string(counter) + ".pgm";
std::string local_rgb_map_file = snapshot_folder + "/local_costmap_path" + std::to_string(counter) + ".png";
save_map(res.local_costmap_image, local_map_file, local_rgb_map_file, local_costmap_msg, local_last_path, req.save_to_disk);
++counter;
return true;
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "movebase_state_service");
state_service sc(ros::this_node::getName());
ros::spin();
return 0;
}
<commit_msg>Changed enum to be portable<commit_after>#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <costmap_2d/costmap_2d_ros.h>
#include <navfn/navfn_ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <nav_msgs/Path.h>
#include <string>
#include "movebase_state_service/MovebaseStateService.h"
class state_service {
public:
ros::NodeHandle n;
ros::ServiceServer service;
geometry_msgs::PoseStampedConstPtr last_goal;
geometry_msgs::PoseConstPtr last_pose;
nav_msgs::Path::ConstPtr global_last_path;
nav_msgs::Path::ConstPtr local_last_path;
std::string snapshot_folder;
int counter;
ros::Subscriber goal_sub;
ros::Subscriber pose_sub;
ros::Subscriber global_path_sub;
ros::Subscriber local_path_sub;
std::string image_input;
std::string global_costmap_input;
std::string local_costmap_input;
std::string goal_input;
std::string pose_input;
std::string global_path_input;
std::string local_path_input;
state_service(const std::string& name)
{
ros::NodeHandle pn("~");
pn.param<std::string>("image_input", image_input, std::string("/head_xtion/rgb/image_color"));
pn.param<std::string>("global_costmap_input", global_costmap_input, std::string("/move_base/global_costmap/costmap"));
pn.param<std::string>("local_costmap_input", local_costmap_input, std::string("/move_base/local_costmap/costmap"));
pn.param<std::string>("snapshot_folder", snapshot_folder, std::string(getenv("HOME")) + std::string("/.ros/movebase_state_service"));
pn.param<std::string>("goal_input", goal_input, std::string("/move_base/current_goal"));
pn.param<std::string>("pose_input", pose_input, std::string("/robot_pose"));
pn.param<std::string>("global_path_input", global_path_input, std::string("/move_base/DWAPlannerROS/global_plan"));
pn.param<std::string>("local_path_input", local_path_input, std::string("/move_base/DWAPlannerROS/local_plan"));
goal_sub = n.subscribe(goal_input, 1, &state_service::goal_callback, this);
pose_sub = n.subscribe(pose_input, 1, &state_service::pose_callback, this);
global_path_sub = n.subscribe(global_path_input, 1, &state_service::global_path_callback, this);
local_path_sub = n.subscribe(local_path_input, 1, &state_service::local_path_callback, this);
counter = 0;
service = n.advertiseService(name, &state_service::service_callback, this);
}
void goal_callback(const geometry_msgs::PoseStampedConstPtr& goal_msg)
{
last_goal = goal_msg;
}
void pose_callback(const geometry_msgs::PoseConstPtr& pose_msg)
{
last_pose = pose_msg;
}
void global_path_callback(const nav_msgs::Path::ConstPtr& path_msg)
{
global_last_path = path_msg;
}
void local_path_callback(const nav_msgs::Path::ConstPtr& path_msg)
{
local_last_path = path_msg;
}
void color_around_point(cv::Mat& map, int x, int y, int c)
{
for (int i = x - 2; i < x + 3; ++i) {
for (int j = y - 2; j < y + 3; ++j) {
// add out-of-bounds check
if (i < 0 || i >= map.cols || j < 0 || j >= map.rows) {
continue;
}
map.at<cv::Vec3b>(j, i)[0] = 0;
map.at<cv::Vec3b>(j, i)[1] = 0;
map.at<cv::Vec3b>(j, i)[2] = 0;
map.at<cv::Vec3b>(j, i)[c] = 255;
}
}
}
void save_map(sensor_msgs::Image& image_msg, const std::string& map_file, const std::string& rgb_map_file,
nav_msgs::OccupancyGrid::ConstPtr& last_map, nav_msgs::Path::ConstPtr& last_path, bool save_to_disk)
{
// save map
double map_height = last_map->info.height;
double map_width = last_map->info.width;
double map_origin_x = last_map->info.origin.position.x;
double map_origin_y = last_map->info.origin.position.y;
double map_res = last_map->info.resolution;
ROS_INFO_STREAM("Map width x height: " << map_width << " x " << map_height);
costmap_2d::Costmap2D map(map_width, map_height, map_res, map_origin_x, map_origin_y);
cv::Mat image = cv::Mat::zeros(map_height, map_width, CV_8UC3);
// incoming dynamic map to Costmap2D
for(int i = 0; i < map_width; i++) {
for(int j = 0; j < map_height; j++) {
map.setCost(i, j, last_map->data[map.getIndex(i, j)]);
image.at<cv::Vec3b>(j, i)[0] = last_map->data[map.getIndex(i, j)];
image.at<cv::Vec3b>(j, i)[1] = last_map->data[map.getIndex(i, j)];
image.at<cv::Vec3b>(j, i)[2] = last_map->data[map.getIndex(i, j)];
}
}
double x, y;
int map_x, map_y;
if (last_path) {
for (size_t i = 0; i < last_path->poses.size(); ++i) {
x = last_path->poses[i].pose.position.x;
y = last_path->poses[i].pose.position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 1);
}
}
if (last_goal) {
x = last_goal->pose.position.x;
y = last_goal->pose.position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 2);
}
if (last_pose) {
x = last_pose->position.x;
y = last_pose->position.y;
map.worldToMapEnforceBounds(x, y, map_x, map_y);
color_around_point(image, map_x, map_y, 0);
}
if (save_to_disk) {
map.saveMap(map_file);
// use lossless png compression
std::vector<int> compression;
compression.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression.push_back(0); // no compression
cv::imwrite(rgb_map_file, image, compression);
}
std_msgs::Header header;
header.seq = counter;
header.stamp = ros::Time::now();
header.frame_id = "/map";
cv_bridge::CvImage global_costmap_tmp = cv_bridge::CvImage(header, "8UC3", image);
global_costmap_tmp.toImageMsg(image_msg);
}
bool service_callback(movebase_state_service::MovebaseStateService::Request& req,
movebase_state_service::MovebaseStateService::Response& res)
{
sensor_msgs::Image::ConstPtr last_img = ros::topic::waitForMessage<sensor_msgs::Image>(image_input, n, ros::Duration(5));
if (!last_img) {
return false;
}
if (req.save_to_disk) {
// save image
boost::shared_ptr<sensor_msgs::Image> rgb_tracked_object;
cv_bridge::CvImageConstPtr rgb_cv_img_boost_ptr;
try {
rgb_cv_img_boost_ptr = cv_bridge::toCvShare(*last_img, rgb_tracked_object);
}
catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
return false;
}
// use lossless png compression
std::vector<int> compression;
compression.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression.push_back(0); // no compression
std::string image_file = snapshot_folder + "/image" + std::to_string(counter) + ".png";
cv::imwrite(image_file, rgb_cv_img_boost_ptr->image, compression);
}
res.camera_image = *last_img;
nav_msgs::OccupancyGrid::ConstPtr global_costmap_msg = ros::topic::waitForMessage<nav_msgs::OccupancyGrid>(global_costmap_input, n, ros::Duration(5));
if (!global_costmap_msg) {
return false;
}
std::string global_map_file = snapshot_folder + "/global_costmap" + std::to_string(counter) + ".pgm";
std::string global_rgb_map_file = snapshot_folder + "/global_costmap_path" + std::to_string(counter) + ".png";
save_map(res.global_costmap_image, global_map_file, global_rgb_map_file, global_costmap_msg, global_last_path, req.save_to_disk);
nav_msgs::OccupancyGrid::ConstPtr local_costmap_msg = ros::topic::waitForMessage<nav_msgs::OccupancyGrid>(local_costmap_input, n, ros::Duration(5));
if (!local_costmap_msg) {
return false;
}
std::string local_map_file = snapshot_folder + "/local_costmap" + std::to_string(counter) + ".pgm";
std::string local_rgb_map_file = snapshot_folder + "/local_costmap_path" + std::to_string(counter) + ".png";
save_map(res.local_costmap_image, local_map_file, local_rgb_map_file, local_costmap_msg, local_last_path, req.save_to_disk);
++counter;
return true;
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "movebase_state_service");
state_service sc(ros::this_node::getName());
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include <ctime>
#include <iostream>
#include <cassert>
// Interface of this cpp file is used by C code, we need to declare
// extern "C" to prevent linking errors.
extern "C" {
#include "keystate/keystate_ds_submit_cmd.h"
#include "keystate/keystate_ds_submit_task.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "shared/str.h"
#include "daemon/engine.h"
}
static const char *module_str = "keystate_ds_submit_cmd";
/**
* Print help for the 'key list' command
*
*/
void help_keystate_ds_submit_cmd(int sockfd)
{
char buf[ODS_SE_MAXLINE];
(void) snprintf(buf, ODS_SE_MAXLINE,
"key ds-submit show ds-submit flag for all keys.\n"
" --zone <zone> (aka -z) perform submit for KSK key of zone <zone>.\n"
" --id <id> (aka -k) perform submit for key with id <id>.\n"
" --auto (aka -a) perform submit for all keys that actually "
"need it.\n"
" --task (aka -t) schedule command to run once as a separate task.\n"
);
ods_writen(sockfd, buf, strlen(buf));
}
int handled_keystate_ds_submit_cmd(int sockfd, engine_type* engine,
const char *cmd, ssize_t n)
{
char buf[ODS_SE_MAXLINE];
const char *argv[8];
const int NARGV = sizeof(argv)/sizeof(char*);
int argc;
task_type *task;
ods_status status;
const char *scmd = "key ds-submit";
cmd = ods_check_command(cmd,n,scmd);
if (!cmd)
return 0; // not handled
ods_log_debug("[%s] %s command", module_str, scmd);
// Use buf as an intermediate buffer for the command.
strncpy(buf,cmd,sizeof(buf));
buf[sizeof(buf)-1] = '\0';
// separate the arguments
argc = ods_str_explode(&buf[0], NARGV, &argv[0]);
if (argc > NARGV) {
ods_log_warning("[%s] too many arguments for %s command",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
ods_writen(sockfd, buf, strlen(buf));
return 1; // errors, but handled
}
const char *zone = NULL;
const char *id = NULL;
(void)ods_find_arg_and_param(&argc,argv,"zone","z",&zone);
(void)ods_find_arg_and_param(&argc,argv,"id","k",&id);
bool bAutomatic = ods_find_arg(&argc,argv,"auto","a") != -1;
bool bScheduleTask = ods_find_arg(&argc,argv,"task","t") != -1;
if (argc) {
ods_log_warning("[%s] unknown arguments for %s command",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
ods_writen(sockfd, buf, strlen(buf));
return 1; // errors, but handled
}
if (bScheduleTask) {
if (zone || id) {
ods_log_crit("[%s] --zone and/or --id options not allowed when "
"scheduling as %s task", module_str, scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,
"Unable to schedule %s task, --zone and/or --id "
"not allowed\n",scmd);
ods_writen(sockfd, buf, strlen(buf));
} else {
/* schedule task */
task = keystate_ds_submit_task(engine->config,scmd);
if (!task) {
ods_log_crit("[%s] failed to create %s task",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,
"Failed to create %s task.\n",scmd);
ods_writen(sockfd, buf, strlen(buf));
} else {
status = schedule_task_from_thread(engine->taskq, task, 0);
if (status != ODS_STATUS_OK) {
ods_log_crit("[%s] failed to create %s task",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,
"Unable to schedule %s task.\n",scmd);
ods_writen(sockfd, buf, strlen(buf));
} else {
(void)snprintf(buf, ODS_SE_MAXLINE,"Scheduled %s task.\n",
scmd);
ods_writen(sockfd, buf, strlen(buf));
}
}
}
} else {
/* perform task immediately */
time_t tstart = time(NULL);
perform_keystate_ds_submit(sockfd,engine->config,zone,id,bAutomatic?1:0);
if (!zone && !id) {
(void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
scmd,time(NULL)-tstart);
ods_writen(sockfd, buf, strlen(buf));
}
}
return 1;
}
<commit_msg>Remove --task parameter from ds-submit command<commit_after>#include <ctime>
#include <iostream>
#include <cassert>
// Interface of this cpp file is used by C code, we need to declare
// extern "C" to prevent linking errors.
extern "C" {
#include "keystate/keystate_ds_submit_cmd.h"
#include "keystate/keystate_ds_submit_task.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "shared/str.h"
#include "daemon/engine.h"
}
static const char *module_str = "keystate_ds_submit_cmd";
/**
* Print help for the 'key list' command
*
*/
void help_keystate_ds_submit_cmd(int sockfd)
{
char buf[ODS_SE_MAXLINE];
(void) snprintf(buf, ODS_SE_MAXLINE,
"key ds-submit show ds-submit flag for all keys.\n"
" --zone <zone> (aka -z) perform submit for KSK key of zone <zone>.\n"
" --id <id> (aka -k) perform submit for key with id <id>.\n"
" --auto (aka -a) perform submit for all keys that actually "
"need it.\n"
);
ods_writen(sockfd, buf, strlen(buf));
}
int handled_keystate_ds_submit_cmd(int sockfd, engine_type* engine,
const char *cmd, ssize_t n)
{
char buf[ODS_SE_MAXLINE];
const char *argv[8];
const int NARGV = sizeof(argv)/sizeof(char*);
int argc;
task_type *task;
ods_status status;
const char *scmd = "key ds-submit";
cmd = ods_check_command(cmd,n,scmd);
if (!cmd)
return 0; // not handled
ods_log_debug("[%s] %s command", module_str, scmd);
// Use buf as an intermediate buffer for the command.
strncpy(buf,cmd,sizeof(buf));
buf[sizeof(buf)-1] = '\0';
// separate the arguments
argc = ods_str_explode(&buf[0], NARGV, &argv[0]);
if (argc > NARGV) {
ods_log_warning("[%s] too many arguments for %s command",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
ods_writen(sockfd, buf, strlen(buf));
return 1; // errors, but handled
}
const char *zone = NULL;
const char *id = NULL;
(void)ods_find_arg_and_param(&argc,argv,"zone","z",&zone);
(void)ods_find_arg_and_param(&argc,argv,"id","k",&id);
bool bAutomatic = ods_find_arg(&argc,argv,"auto","a") != -1;
if (argc) {
ods_log_warning("[%s] unknown arguments for %s command",
module_str,scmd);
(void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
ods_writen(sockfd, buf, strlen(buf));
return 1; // errors, but handled
}
/* perform task immediately */
time_t tstart = time(NULL);
perform_keystate_ds_submit(sockfd,engine->config,zone,id,bAutomatic?1:0);
if (!zone && !id) {
(void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
scmd,time(NULL)-tstart);
ods_writen(sockfd, buf, strlen(buf));
}
return 1;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "CodeGenerator.h"
#include "ArticyImportData.h"
#include "DatabaseGenerator.h"
#include "GlobalVarsGenerator.h"
#include "InterfacesGenerator.h"
#include "Developer/HotReload/Public/IHotReload.h"
#include "ArticyRuntime/Public/ArticyGlobalVariables.h"
#include "ObjectDefinitionsGenerator.h"
#include "PackagesGenerator.h"
#include "ArticyDatabase.h"
#include "ExpressoScriptsGenerator.h"
#include "FileHelpers.h"
#include "GenericPlatform/GenericPlatformMisc.h"
#include "ArticyImporter.h"
#include "ArticyPluginSettings.h"
#include "Dialogs/Dialogs.h"
#include "IContentBrowserSingleton.h"
#include "Interfaces/IPluginManager.h"
#include "ObjectTools.h"
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
#define LOCTEXT_NAMESPACE "CodeGenerator"
TMap<FString, FString> CodeGenerator::CachedFiles;
FString CodeGenerator::GetSourceFolder()
{
FString GeneratedFilesSourceFolder = IPluginManager::Get().FindPlugin(TEXT("ArticyImporter"))->GetBaseDir() / TEXT("Source") / TEXT("ArticyGenerated") / TEXT("ArticyGenerated");
return GeneratedFilesSourceFolder;
}
FString CodeGenerator::GetGeneratedInterfacesFilename(const UArticyImportData* Data)
{
return Data->GetProject().TechnicalName + "Interfaces";
}
FString CodeGenerator::GetGeneratedTypesFilename(const UArticyImportData* Data)
{
return Data->GetProject().TechnicalName + "ArticyTypes";
}
FString CodeGenerator::GetGlobalVarsClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "GlobalVariables";
}
FString CodeGenerator::GetGVNamespaceClassname(const UArticyImportData* Data, const FString& Namespace)
{
return "U" + Data->GetProject().TechnicalName + Namespace + "Variables";
}
FString CodeGenerator::GetDatabaseClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "Database";
}
FString CodeGenerator::GetMethodsProviderClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "MethodsProvider";
}
FString CodeGenerator::GetExpressoScriptsClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "ExpressoScripts";
}
FString CodeGenerator::GetFeatureInterfaceClassName(const UArticyImportData* Data, const FArticyTemplateFeatureDef& Feature, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "I") + Data->GetProject().TechnicalName + "ObjectWith" + Feature.GetTechnicalName() + "Feature";
}
bool CodeGenerator::DeleteGeneratedCode(const FString& Filename)
{
if (Filename.IsEmpty())
return FPlatformFileManager::Get().GetPlatformFile().DeleteDirectoryRecursively(*GetSourceFolder());
return FPlatformFileManager::Get().GetPlatformFile().DeleteFile(*(GetSourceFolder() / Filename));
}
bool CodeGenerator::GenerateCode(UArticyImportData* Data)
{
if (!Data)
return false;
bool bCodeGenerated = false;
TArray<FString> FileNames;
IFileManager::Get().FindFiles(FileNames, *GetSourceFolder());
TArray<FString> FileContents;
FileContents.SetNumZeroed(FileNames.Num());
for (int32 i = 0; i < FileNames.Num(); i++)
{
FileNames[i] = GetSourceFolder() / FileNames[i];
}
for(int32 i=0; i < FileNames.Num(); i++)
{
FFileHelper::LoadFileToString(FileContents[i], *FileNames[i]);
CachedFiles.Add(FileNames[i], FileContents[i]);
}
//generate all files if ObjectDefs or GVs changed
if (Data->GetSettings().DidObjectDefsOrGVsChange())
{
//DeleteGeneratedCode();
GlobalVarsGenerator::GenerateCode(Data);
DatabaseGenerator::GenerateCode(Data);
InterfacesGenerator::GenerateCode(Data);
ObjectDefinitionsGenerator::GenerateCode(Data);
/* generate scripts as well due to them including the generated global variables
* if we remove a GV set but don't regenerate expresso scripts, the resulting class won't compile */
ExpressoScriptsGenerator::GenerateCode(Data);
bCodeGenerated = true;
}
// if object defs of GVs didn't change, but scripts changed, regenerate only expresso scripts
else if (Data->GetSettings().DidScriptFragmentsChange())
{
ExpressoScriptsGenerator::GenerateCode(Data);
bCodeGenerated = true;
}
return bCodeGenerated;
}
void CodeGenerator::Recompile(UArticyImportData* Data)
{
Compile(Data);
}
bool CodeGenerator::DeleteGeneratedAssets()
{
FAssetRegistryModule& AssetRegistry = FModuleManager::Get().GetModuleChecked<FAssetRegistryModule>("AssetRegistry");
TArray<FAssetData> OutAssets;
AssetRegistry.Get().GetAssetsByPath(FName(*ArticyHelpers::ArticyGeneratedFolder), OutAssets, true, false);
TArray<UObject*> ExistingAssets;
for(FAssetData data : OutAssets)
{
ExistingAssets.Add(data.GetAsset());
}
if(ExistingAssets.Num() > 0)
{
return ObjectTools::ForceDeleteObjects(ExistingAssets, false) > 0;
}
// returns true if there is nothing to delete to not trigger the ensure
return true;
}
void CodeGenerator::Compile(UArticyImportData* Data)
{
bool bWaitingForOtherCompile = false;
// We can only hot-reload via DoHotReloadFromEditor when we already had code in our project
IHotReloadInterface& HotReloadSupport = FModuleManager::LoadModuleChecked<IHotReloadInterface>("HotReload");
if (HotReloadSupport.IsCurrentlyCompiling())
{
bWaitingForOtherCompile = true;
UE_LOG(LogArticyImporter, Warning, TEXT("Already compiling, waiting until it's done."));
}
static FDelegateHandle AfterCompileLambda;
if(AfterCompileLambda.IsValid())
{
IHotReloadModule::Get().OnHotReload().Remove(AfterCompileLambda);
AfterCompileLambda.Reset();
}
AfterCompileLambda = IHotReloadModule::Get().OnHotReload().AddLambda([=](bool bWasTriggeredAutomatically)
{
UE_LOG(LogArticyImporter, Warning, TEXT("AfterCompileLamba Called"));
OnCompiled(Data);
});
// register a lambda to handle failure in code generation (compilation failed due to generated articy code)
// detection of faulty articy code is a heuristic and not optimal!
static FDelegateHandle RestoreCachedVersionHandle;
if(RestoreCachedVersionHandle.IsValid())
{
IHotReloadModule::Get().OnModuleCompilerFinished().Remove(RestoreCachedVersionHandle);
RestoreCachedVersionHandle.Reset();
}
RestoreCachedVersionHandle = IHotReloadModule::Get().OnModuleCompilerFinished().AddLambda([=](const FString& Log, ECompilationResult::Type Type, bool bSuccess)
{
UE_LOG(LogArticyImporter, Warning, TEXT("Restore Cached Lamba Called"));
if (Type == ECompilationResult::Succeeded || Type == ECompilationResult::Canceled || Type == ECompilationResult::UpToDate)
{
// do nothing in case the compilation was successful or intentionally cancelled
}
else
{
TArray<FString> Lines;
// parsing into individual FStrings for each line. Using \n as delimiter, should cover both Mac OSX and Windows
Log.ParseIntoArray(Lines, TEXT("\n"));
// heuristic: error due to articy?
bool bErrorInGeneratedCode = false;
for (const FString& Line : Lines)
{
if (Line.Contains(TEXT("error")) && Line.Contains(TEXT("ArticyGenerated")))
{
bErrorInGeneratedCode = true;
break;
}
}
/** if error is due to articy, restore the previous data, consisting of:
* ImportData (base truth for generation of assets and code),
* Generated code (previous code should have been working, so we'll restore that instead of just generating the code again)
* Assets (we can restore the assets by generating them normally, because the ImportData was restored and the code is the same as before)
*/
if (bErrorInGeneratedCode)
{
// transfer the cached data into the current one
Data->ResolveCachedVersion();
// attempt to restore all generated files
const bool bFilesRestored = RestoreCachedFiles();
// if we succeeded, tell the user and call OnCompiled - which will then create the assets
if(bFilesRestored)
{
const FText CacheRestoredText = LOCTEXT("ImportDataCacheRestoredText", "Error in generated articy code detected. Previous data restored. Proceeding with asset generation with the restored data.");
const FText CacheRestoredTitle = LOCTEXT("ImportDataCacheRestoredTitle", "Articy code generation failed - restoration succeeded");
OpenMsgDlgInt(EAppMsgType::Ok, CacheRestoredText, CacheRestoredTitle);
// although we didn't actually compile, we act as if we did to trigger asset generation and post import
OnCompiled(Data);
}
else
{
// if there were no previous files or not all files could be restored, delete them instead
if(DeleteGeneratedCode())
{
const FText CacheDeletedText = LOCTEXT("ImportDataCacheDeletedText", "Error in generated articy code detected. Code deleted.");
const FText CacheDeletedTitle = LOCTEXT("ImportDataCacheDeletedTitle", "Articy code generation failed - restoration succeeded");
OpenMsgDlgInt(EAppMsgType::Ok, CacheDeletedText, CacheDeletedTitle);
}
// if deletion didn't work for some reason, notify the user
else
{
const FText CacheDeletionFailedText = LOCTEXT("ImportDataCacheDeletionFailedText", "Error in generated articy code detected. Code could not be deleted.");
const FText CacheDeletionFailedTitle = LOCTEXT("ImportDataCacheDeletionFailedTitle", "Articy code generation failed - restoration failed");
OpenMsgDlgInt(EAppMsgType::Ok, CacheDeletionFailedText, CacheDeletionFailedTitle);
}
}
}
}
});
if (!bWaitingForOtherCompile)
{
HotReloadSupport.DoHotReloadFromEditor(EHotReloadFlags::None /*async*/);
//IHotReloadModule::Get().RecompileModule(FName(TEXT("ArticyGenerated")), )
}
}
void CodeGenerator::GenerateAssets(UArticyImportData* Data)
{
ensure(Data);
//compiling is done!
//check if UArticyBaseGlobalVariables can be found, otherwise something went wrong!
const auto ClassName = GetGlobalVarsClassname(Data, true);
auto FullClassName = FString::Printf(TEXT("Class'/Script/%s.%s'"), TEXT("ArticyGenerated"), *ClassName);
if (!ensure(ConstructorHelpersInternal::FindOrLoadClass(FullClassName, UArticyGlobalVariables::StaticClass())))
UE_LOG(LogArticyImporter, Error, TEXT("Could not find generated global variables class after compile!"));
ensure(DeleteGeneratedAssets());
//generate the global variables asset
GlobalVarsGenerator::GenerateAsset(Data);
//generate the database asset
auto db = DatabaseGenerator::GenerateAsset(Data);
//generate assets for all the imported objects
PackagesGenerator::GenerateAssets(Data);
//register the newly imported packages in the database
if (ensureMsgf(db, TEXT("Could not create ArticyDatabase asset!")))
{
db->SetLoadedPackages(Data->GetPackagesDirect());
}
//gather all articy assets to save them
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry");
TArray<FAssetData> GeneratedAssets;
AssetRegistryModule.Get().GetAssetsByPath(FName(*ArticyHelpers::ArticyGeneratedFolder), GeneratedAssets, true);
TArray<UPackage*> PackagesToSave;
PackagesToSave.Add(Data->GetOutermost());
for (FAssetData AssetData : GeneratedAssets)
{
PackagesToSave.Add(AssetData.GetAsset()->GetOutermost());
}
// automatically save all articy assets
TArray<UPackage*> FailedToSavePackages;
FEditorFileUtils::PromptForCheckoutAndSave(PackagesToSave, false, false, &FailedToSavePackages);
for (auto Package : FailedToSavePackages)
{
UE_LOG(LogArticyImporter, Error, TEXT("Could not save package %s"), *Package->GetName());
}
}
void CodeGenerator::OnCompiled(UArticyImportData* Data)
{
Data->GetSettings().SetObjectDefinitionsRebuilt();
Data->GetSettings().SetScriptFragmentsRebuilt();
// broadcast that compilation has finished. ArticyImportData will then generate the assets and perform post import operations
FArticyImporterModule::Get().OnCompilationFinished.Broadcast(Data);
}
bool CodeGenerator::RestoreCachedFiles()
{
bool bFilesRestored = CachedFiles.Num() > 0 ? true : false;
for(auto& CachedFile : CachedFiles)
{
bFilesRestored = bFilesRestored && FFileHelper::SaveStringToFile(CachedFile.Value, *CachedFile.Key);
}
return bFilesRestored;
}
#undef LOCTEXT_NAMESPACE<commit_msg>Code restoration now happens if user cancels compilation<commit_after>//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "CodeGenerator.h"
#include "ArticyImportData.h"
#include "DatabaseGenerator.h"
#include "GlobalVarsGenerator.h"
#include "InterfacesGenerator.h"
#include "Developer/HotReload/Public/IHotReload.h"
#include "ArticyRuntime/Public/ArticyGlobalVariables.h"
#include "ObjectDefinitionsGenerator.h"
#include "PackagesGenerator.h"
#include "ArticyDatabase.h"
#include "ExpressoScriptsGenerator.h"
#include "FileHelpers.h"
#include "GenericPlatform/GenericPlatformMisc.h"
#include "ArticyImporter.h"
#include "ArticyPluginSettings.h"
#include "Dialogs/Dialogs.h"
#include "IContentBrowserSingleton.h"
#include "Interfaces/IPluginManager.h"
#include "ObjectTools.h"
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
#define LOCTEXT_NAMESPACE "CodeGenerator"
TMap<FString, FString> CodeGenerator::CachedFiles;
FString CodeGenerator::GetSourceFolder()
{
FString GeneratedFilesSourceFolder = IPluginManager::Get().FindPlugin(TEXT("ArticyImporter"))->GetBaseDir() / TEXT("Source") / TEXT("ArticyGenerated") / TEXT("ArticyGenerated");
return GeneratedFilesSourceFolder;
}
FString CodeGenerator::GetGeneratedInterfacesFilename(const UArticyImportData* Data)
{
return Data->GetProject().TechnicalName + "Interfaces";
}
FString CodeGenerator::GetGeneratedTypesFilename(const UArticyImportData* Data)
{
return Data->GetProject().TechnicalName + "ArticyTypes";
}
FString CodeGenerator::GetGlobalVarsClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "GlobalVariables";
}
FString CodeGenerator::GetGVNamespaceClassname(const UArticyImportData* Data, const FString& Namespace)
{
return "U" + Data->GetProject().TechnicalName + Namespace + "Variables";
}
FString CodeGenerator::GetDatabaseClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "Database";
}
FString CodeGenerator::GetMethodsProviderClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "MethodsProvider";
}
FString CodeGenerator::GetExpressoScriptsClassname(const UArticyImportData* Data, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "U") + Data->GetProject().TechnicalName + "ExpressoScripts";
}
FString CodeGenerator::GetFeatureInterfaceClassName(const UArticyImportData* Data, const FArticyTemplateFeatureDef& Feature, const bool bOmittPrefix)
{
return (bOmittPrefix ? "" : "I") + Data->GetProject().TechnicalName + "ObjectWith" + Feature.GetTechnicalName() + "Feature";
}
bool CodeGenerator::DeleteGeneratedCode(const FString& Filename)
{
if (Filename.IsEmpty())
return FPlatformFileManager::Get().GetPlatformFile().DeleteDirectoryRecursively(*GetSourceFolder());
return FPlatformFileManager::Get().GetPlatformFile().DeleteFile(*(GetSourceFolder() / Filename));
}
bool CodeGenerator::GenerateCode(UArticyImportData* Data)
{
if (!Data)
return false;
bool bCodeGenerated = false;
TArray<FString> FileNames;
IFileManager::Get().FindFiles(FileNames, *GetSourceFolder());
TArray<FString> FileContents;
FileContents.SetNumZeroed(FileNames.Num());
for (int32 i = 0; i < FileNames.Num(); i++)
{
FileNames[i] = GetSourceFolder() / FileNames[i];
}
for(int32 i=0; i < FileNames.Num(); i++)
{
FFileHelper::LoadFileToString(FileContents[i], *FileNames[i]);
CachedFiles.Add(FileNames[i], FileContents[i]);
}
//generate all files if ObjectDefs or GVs changed
if (Data->GetSettings().DidObjectDefsOrGVsChange())
{
//DeleteGeneratedCode();
GlobalVarsGenerator::GenerateCode(Data);
DatabaseGenerator::GenerateCode(Data);
InterfacesGenerator::GenerateCode(Data);
ObjectDefinitionsGenerator::GenerateCode(Data);
/* generate scripts as well due to them including the generated global variables
* if we remove a GV set but don't regenerate expresso scripts, the resulting class won't compile */
ExpressoScriptsGenerator::GenerateCode(Data);
bCodeGenerated = true;
}
// if object defs of GVs didn't change, but scripts changed, regenerate only expresso scripts
else if (Data->GetSettings().DidScriptFragmentsChange())
{
ExpressoScriptsGenerator::GenerateCode(Data);
bCodeGenerated = true;
}
return bCodeGenerated;
}
void CodeGenerator::Recompile(UArticyImportData* Data)
{
Compile(Data);
}
bool CodeGenerator::DeleteGeneratedAssets()
{
FAssetRegistryModule& AssetRegistry = FModuleManager::Get().GetModuleChecked<FAssetRegistryModule>("AssetRegistry");
TArray<FAssetData> OutAssets;
AssetRegistry.Get().GetAssetsByPath(FName(*ArticyHelpers::ArticyGeneratedFolder), OutAssets, true, false);
TArray<UObject*> ExistingAssets;
for(FAssetData data : OutAssets)
{
ExistingAssets.Add(data.GetAsset());
}
if(ExistingAssets.Num() > 0)
{
return ObjectTools::ForceDeleteObjects(ExistingAssets, false) > 0;
}
// returns true if there is nothing to delete to not trigger the ensure
return true;
}
void CodeGenerator::Compile(UArticyImportData* Data)
{
bool bWaitingForOtherCompile = false;
// We can only hot-reload via DoHotReloadFromEditor when we already had code in our project
IHotReloadInterface& HotReloadSupport = FModuleManager::LoadModuleChecked<IHotReloadInterface>("HotReload");
if (HotReloadSupport.IsCurrentlyCompiling())
{
bWaitingForOtherCompile = true;
UE_LOG(LogArticyImporter, Warning, TEXT("Already compiling, waiting until it's done."));
}
static FDelegateHandle AfterCompileLambda;
if(AfterCompileLambda.IsValid())
{
IHotReloadModule::Get().OnHotReload().Remove(AfterCompileLambda);
AfterCompileLambda.Reset();
}
AfterCompileLambda = IHotReloadModule::Get().OnHotReload().AddLambda([=](bool bWasTriggeredAutomatically)
{
UE_LOG(LogArticyImporter, Warning, TEXT("AfterCompileLamba Called"));
OnCompiled(Data);
});
// register a lambda to handle failure in code generation (compilation failed due to generated articy code)
// detection of faulty articy code is a heuristic and not optimal!
static FDelegateHandle RestoreCachedVersionHandle;
if(RestoreCachedVersionHandle.IsValid())
{
IHotReloadModule::Get().OnModuleCompilerFinished().Remove(RestoreCachedVersionHandle);
RestoreCachedVersionHandle.Reset();
}
RestoreCachedVersionHandle = IHotReloadModule::Get().OnModuleCompilerFinished().AddLambda([=](const FString& Log, ECompilationResult::Type Type, bool bSuccess)
{
UE_LOG(LogArticyImporter, Warning, TEXT("Restore Cached Lamba Called"));
if (Type == ECompilationResult::Succeeded || Type == ECompilationResult::UpToDate)
{
// do nothing in case the compilation was successful or intentionally cancelled
}
else
{
TArray<FString> Lines;
// parsing into individual FStrings for each line. Using \n as delimiter, should cover both Mac OSX and Windows
Log.ParseIntoArray(Lines, TEXT("\n"));
// heuristic: error due to articy?
bool bErrorInGeneratedCode = false;
for (const FString& Line : Lines)
{
if (Line.Contains(TEXT("error")) && Line.Contains(TEXT("ArticyGenerated")))
{
bErrorInGeneratedCode = true;
break;
}
}
/** if error is due to articy, restore the previous data, consisting of:
* ImportData (base truth for generation of assets and code),
* Generated code (previous code should have been working, so we'll restore that instead of just generating the code again)
* Assets (we can restore the assets by generating them normally, because the ImportData was restored and the code is the same as before)
*/
if (bErrorInGeneratedCode)
{
// transfer the cached data into the current one
Data->ResolveCachedVersion();
// attempt to restore all generated files
const bool bFilesRestored = RestoreCachedFiles();
// if we succeeded, tell the user and call OnCompiled - which will then create the assets
if(bFilesRestored)
{
const FText CacheRestoredText = LOCTEXT("ImportDataCacheRestoredText", "Error in generated articy code detected. Previous data restored. Proceeding with asset generation with the restored data.");
const FText CacheRestoredTitle = LOCTEXT("ImportDataCacheRestoredTitle", "Articy code generation failed - restoration succeeded");
OpenMsgDlgInt(EAppMsgType::Ok, CacheRestoredText, CacheRestoredTitle);
// although we didn't actually compile, we act as if we did to trigger asset generation and post import
OnCompiled(Data);
}
else
{
// if there were no previous files or not all files could be restored, delete them instead
if(DeleteGeneratedCode())
{
const FText CacheDeletedText = LOCTEXT("ImportDataCacheDeletedText", "Error in generated articy code detected. Code deleted.");
const FText CacheDeletedTitle = LOCTEXT("ImportDataCacheDeletedTitle", "Articy code generation failed - restoration succeeded");
OpenMsgDlgInt(EAppMsgType::Ok, CacheDeletedText, CacheDeletedTitle);
}
// if deletion didn't work for some reason, notify the user
else
{
const FText CacheDeletionFailedText = LOCTEXT("ImportDataCacheDeletionFailedText", "Error in generated articy code detected. Code could not be deleted.");
const FText CacheDeletionFailedTitle = LOCTEXT("ImportDataCacheDeletionFailedTitle", "Articy code generation failed - restoration failed");
OpenMsgDlgInt(EAppMsgType::Ok, CacheDeletionFailedText, CacheDeletionFailedTitle);
}
}
}
}
});
if (!bWaitingForOtherCompile)
{
HotReloadSupport.DoHotReloadFromEditor(EHotReloadFlags::None /*async*/);
//IHotReloadModule::Get().RecompileModule(FName(TEXT("ArticyGenerated")), )
}
}
void CodeGenerator::GenerateAssets(UArticyImportData* Data)
{
ensure(Data);
//compiling is done!
//check if UArticyBaseGlobalVariables can be found, otherwise something went wrong!
const auto ClassName = GetGlobalVarsClassname(Data, true);
auto FullClassName = FString::Printf(TEXT("Class'/Script/%s.%s'"), TEXT("ArticyGenerated"), *ClassName);
if (!ensure(ConstructorHelpersInternal::FindOrLoadClass(FullClassName, UArticyGlobalVariables::StaticClass())))
UE_LOG(LogArticyImporter, Error, TEXT("Could not find generated global variables class after compile!"));
ensure(DeleteGeneratedAssets());
//generate the global variables asset
GlobalVarsGenerator::GenerateAsset(Data);
//generate the database asset
auto db = DatabaseGenerator::GenerateAsset(Data);
//generate assets for all the imported objects
PackagesGenerator::GenerateAssets(Data);
//register the newly imported packages in the database
if (ensureMsgf(db, TEXT("Could not create ArticyDatabase asset!")))
{
db->SetLoadedPackages(Data->GetPackagesDirect());
}
//gather all articy assets to save them
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry");
TArray<FAssetData> GeneratedAssets;
AssetRegistryModule.Get().GetAssetsByPath(FName(*ArticyHelpers::ArticyGeneratedFolder), GeneratedAssets, true);
TArray<UPackage*> PackagesToSave;
PackagesToSave.Add(Data->GetOutermost());
for (FAssetData AssetData : GeneratedAssets)
{
PackagesToSave.Add(AssetData.GetAsset()->GetOutermost());
}
// automatically save all articy assets
TArray<UPackage*> FailedToSavePackages;
FEditorFileUtils::PromptForCheckoutAndSave(PackagesToSave, false, false, &FailedToSavePackages);
for (auto Package : FailedToSavePackages)
{
UE_LOG(LogArticyImporter, Error, TEXT("Could not save package %s"), *Package->GetName());
}
}
void CodeGenerator::OnCompiled(UArticyImportData* Data)
{
Data->GetSettings().SetObjectDefinitionsRebuilt();
Data->GetSettings().SetScriptFragmentsRebuilt();
// broadcast that compilation has finished. ArticyImportData will then generate the assets and perform post import operations
FArticyImporterModule::Get().OnCompilationFinished.Broadcast(Data);
}
bool CodeGenerator::RestoreCachedFiles()
{
bool bFilesRestored = CachedFiles.Num() > 0 ? true : false;
for(auto& CachedFile : CachedFiles)
{
bFilesRestored = bFilesRestored && FFileHelper::SaveStringToFile(CachedFile.Value, *CachedFile.Key);
}
return bFilesRestored;
}
#undef LOCTEXT_NAMESPACE<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2018 The Crown developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode.h"
#include "keystore.h"
#include <boost/test/unit_test.hpp>
namespace
{
CMasternode CreateMasternode(CTxIn vin)
{
CMasternode mn;
mn.vin = vin;
mn.activeState = CMasternode::MASTERNODE_ENABLED;
return mn;
}
void FillBlock(CBlockIndex& block, /*const*/ CBlockIndex* prevBlock, const uint256& hash)
{
if (prevBlock)
{
block.nHeight = prevBlock->nHeight + 1;
block.pprev = prevBlock;
}
else
{
block.nHeight = 0;
}
block.phashBlock = &hash;
block.BuildSkip();
}
void FillHash(uint256& hash, const arith_uint256& height)
{
hash = ArithToUint256(height);
}
void FillBlock(CBlockIndex& block, uint256& hash, /*const*/ CBlockIndex* prevBlock, size_t height)
{
FillHash(hash, height);
FillBlock(block, height ? prevBlock : NULL, hash);
assert(static_cast<int>(UintToArith256(block.GetBlockHash()).GetLow64()) == block.nHeight);
assert(block.pprev == NULL || block.nHeight == block.pprev->nHeight + 1);
}
struct CalculateScoreFixture
{
const CMasternode mn1;
const CMasternode mn2;
const CMasternode mn3;
const CMasternode mn4;
const CMasternode mn5;
std::vector<uint256> hashes;
std::vector<CBlockIndex> blocks;
std::vector<CMasternode> masternodes;
CalculateScoreFixture()
: mn1(CreateMasternode(CTxIn(COutPoint(ArithToUint256(1), 1 * COIN))))
, mn2(CreateMasternode(CTxIn(COutPoint(ArithToUint256(2), 1 * COIN))))
, mn3(CreateMasternode(CTxIn(COutPoint(ArithToUint256(3), 1 * COIN))))
, mn4(CreateMasternode(CTxIn(COutPoint(ArithToUint256(4), 1 * COIN))))
, mn5(CreateMasternode(CTxIn(COutPoint(ArithToUint256(5), 1 * COIN))))
, hashes(1000)
, blocks(1000)
{
masternodes.push_back(mn1);
masternodes.push_back(mn2);
masternodes.push_back(mn3);
masternodes.push_back(mn4);
masternodes.push_back(mn5);
}
void BuildChain()
{
// Build a main chain 1000 blocks long.
for (size_t i = 0; i < blocks.size(); ++i)
{
FillBlock(blocks[i], hashes[i], &blocks[i - 1], i);
}
chainActive.SetTip(&blocks.back());
}
};
}
BOOST_FIXTURE_TEST_SUITE(CalculateScore, CalculateScoreFixture)
BOOST_AUTO_TEST_CASE(NullTip)
{
BOOST_CHECK(mn1.CalculateScore(1) == arith_uint256());
}
BOOST_AUTO_TEST_CASE(NotExistingBlock)
{
BuildChain();
BOOST_CHECK(mn1.CalculateScore(1001) == arith_uint256());
}
BOOST_AUTO_TEST_CASE(ScoreChanges)
{
BuildChain();
CMasternode mn = CreateMasternode(CTxIn(COutPoint(ArithToUint256(1), 1 * COIN)));
int64_t score = mn.CalculateScore(100).GetCompact(false);
// Change masternode vin
mn.vin = CTxIn(COutPoint(ArithToUint256(2), 1 * COIN));
// Calculate new score
int64_t newScore = mn.CalculateScore(100).GetCompact(false);
BOOST_CHECK(score != newScore);
}
BOOST_AUTO_TEST_CASE(DistributionCheck)
{
// Find winner masternode for all 1000 blocks and
// make sure all masternodes have the same probability to win
BuildChain();
std::vector<pair<int64_t, CTxIn> > vecMasternodeScores;
std::map<int, int> winningCount;
for (int i = 1; i < 1001; ++i)
{
int64_t score = 0;
int index = 0;
for (size_t j = 0; j < masternodes.size(); ++j)
{
int s = masternodes[j].CalculateScore(i).GetCompact(false);
if (s > score)
{
score = s;
index = j;
}
}
winningCount[index]++;
}
std::map<int, int>::iterator it = winningCount.begin();
for (; it != winningCount.end(); ++it)
{
// +- 15%
BOOST_CHECK(it->second < 200 + 30);
BOOST_CHECK(it->second > 200 - 30);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Resolved discussions (#121)<commit_after>// Copyright (c) 2014-2018 The Crown developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode.h"
#include "keystore.h"
#include <boost/test/unit_test.hpp>
namespace
{
CMasternode CreateMasternode(CTxIn vin)
{
CMasternode mn;
mn.vin = vin;
mn.activeState = CMasternode::MASTERNODE_ENABLED;
return mn;
}
void FillBlock(CBlockIndex& block, CBlockIndex* prevBlock, const uint256& hash)
{
if (prevBlock)
{
block.nHeight = prevBlock->nHeight + 1;
block.pprev = prevBlock;
}
else
{
block.nHeight = 0;
}
block.phashBlock = &hash;
block.BuildSkip();
}
void FillHash(uint256& hash, const arith_uint256& height)
{
hash = ArithToUint256(height);
}
void FillBlock(CBlockIndex& block, uint256& hash, CBlockIndex* prevBlock, size_t height)
{
FillHash(hash, height);
FillBlock(block, height ? prevBlock : NULL, hash);
assert(static_cast<int>(UintToArith256(block.GetBlockHash()).GetLow64()) == block.nHeight);
assert(block.pprev == NULL || block.nHeight == block.pprev->nHeight + 1);
}
struct CalculateScoreFixture
{
const CMasternode mn;
std::vector<uint256> hashes;
std::vector<CBlockIndex> blocks;
CalculateScoreFixture()
: mn(CreateMasternode(CTxIn(COutPoint(ArithToUint256(1), 1 * COIN))))
, hashes(1000)
, blocks(1000)
{
BuildChain();
}
void BuildChain()
{
// Build a main chain 1000 blocks long.
for (size_t i = 0; i < blocks.size(); ++i)
{
FillBlock(blocks[i], hashes[i], &blocks[i - 1], i);
}
chainActive.SetTip(&blocks.back());
}
~CalculateScoreFixture()
{
chainActive = CChain();
}
};
}
BOOST_FIXTURE_TEST_SUITE(CalculateScore, CalculateScoreFixture)
BOOST_AUTO_TEST_CASE(NullTip)
{
chainActive = CChain();
BOOST_CHECK(mn.CalculateScore(1) == arith_uint256());
}
BOOST_AUTO_TEST_CASE(NotExistingBlock)
{
BOOST_CHECK(mn.CalculateScore(1001) == arith_uint256());
}
BOOST_AUTO_TEST_CASE(ScoreChanges)
{
CMasternode mn = CreateMasternode(CTxIn(COutPoint(ArithToUint256(1), 1 * COIN)));
int64_t score = mn.CalculateScore(100).GetCompact(false);
// Change masternode vin
mn.vin = CTxIn(COutPoint(ArithToUint256(2), 1 * COIN));
// Calculate new score
int64_t newScore = mn.CalculateScore(100).GetCompact(false);
BOOST_CHECK(score != newScore);
}
BOOST_AUTO_TEST_CASE(DistributionCheck)
{
std::vector<CMasternode> masternodes;
masternodes.push_back(CreateMasternode(CTxIn(COutPoint(ArithToUint256(1), 1 * COIN))));
masternodes.push_back(CreateMasternode(CTxIn(COutPoint(ArithToUint256(2), 1 * COIN))));
masternodes.push_back(CreateMasternode(CTxIn(COutPoint(ArithToUint256(3), 1 * COIN))));
masternodes.push_back(CreateMasternode(CTxIn(COutPoint(ArithToUint256(4), 1 * COIN))));
masternodes.push_back(CreateMasternode(CTxIn(COutPoint(ArithToUint256(5), 1 * COIN))));
// Find winner masternode for all 1000 blocks and
// make sure all masternodes have the same probability to win
std::vector<pair<int64_t, CTxIn> > vecMasternodeScores;
std::map<int, int> winningCount;
for (int i = 0; i <= chainActive.Height(); ++i)
{
int64_t score = 0;
int index = 0;
for (size_t j = 0; j < masternodes.size(); ++j)
{
int s = masternodes[j].CalculateScore(i).GetCompact(false);
if (s > score)
{
score = s;
index = j;
}
}
winningCount[index]++;
}
std::map<int, int>::iterator it = winningCount.begin();
const int averageWinCount = chainActive.Height() / masternodes.size();
for (; it != winningCount.end(); ++it)
{
// +- 15%
BOOST_CHECK(it->second < averageWinCount + 0.15 * averageWinCount);
BOOST_CHECK(it->second > averageWinCount - 0.15 * averageWinCount);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2008-2013. All Rights Reserved.
*
* The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved online at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* %CopyrightEnd%
*/
#include "wxe_return.h"
// see http://docs.wxwidgets.org/stable/wx_wxarray.html#arraymacros
// this is a magic incantation which must be done!
#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(wxErlDrvTermDataArray);
#define INLINE
wxeReturn::wxeReturn (ErlDrvTermData _port,
ErlDrvTermData _caller,
bool _isResult) {
port = _port;
caller = _caller;
isResult = _isResult;
if (isResult) {
addAtom("_wxe_result_");
}
}
wxeReturn::~wxeReturn () {
//depending on which version of wxArray we use, we may have to clear it ourselves.
}
int wxeReturn::send() {
if ((rt.GetCount() == 2 && isResult) || rt.GetCount() == 0)
return 1; // not a call bail out
if (isResult) {
addTupleCount(2);
}
// rt to array
unsigned int rtLength = rt.GetCount(); //signed int
size_t size = sizeof(ErlDrvTermData)*(rtLength);
ErlDrvTermData* rtData = (ErlDrvTermData *) driver_alloc(size);
for (unsigned int i=0; i < rtLength; i++) {
rtData[i] = rt[i];
}
int res = erl_drv_send_term(port, caller, rtData, rtLength);
driver_free(rtData);
#ifdef DEBUG
if(res == -1) {
wxString msg;
msg.Printf(wxT("Failed to send return or event msg"));
send_msg("internal_error", &msg);
}
#endif
reset();
return res;
}
//clear everything so we can re-use if we want
void wxeReturn::reset() {
rt.empty();
temp_float.empty();
}
INLINE
unsigned int wxeReturn::size() {
return rt.GetCount();
}
INLINE
void wxeReturn::add(ErlDrvTermData type, ErlDrvTermData data) {
rt.Add(type);
rt.Add(data);
}
// INLINE
// void wxeReturn::addRef(const void *ptr, const char* className) {
// unsigned int ref_idx = wxe_app->getRef((void *)ptr, memEnv);
// addRef(ref_idx, className);
// }
INLINE
void wxeReturn::addRef(const unsigned int ref, const char* className) {
addAtom("wx_ref");
addUint(ref);
addAtom(className);
rt.Add(ERL_DRV_NIL);
addTupleCount(4);
}
INLINE
void wxeReturn::addAtom(const char* atomName) {
add(ERL_DRV_ATOM, driver_mk_atom((char *)atomName));
}
INLINE
void wxeReturn::addBinary(const char* buf, const size_t size) {
rt.Add(ERL_DRV_BUF2BINARY);
rt.Add((ErlDrvTermData)buf);
rt.Add((ErlDrvTermData)size);
}
INLINE
void wxeReturn::addExt2Term(wxeErlTerm *term) {
if(term) {
rt.Add(ERL_DRV_EXT2TERM);
rt.Add((ErlDrvTermData)term->bin);
rt.Add((ErlDrvTermData)term->size);
} else {
rt.Add(ERL_DRV_NIL);
}
}
INLINE
void wxeReturn::addExt2Term(wxETreeItemData *val) {
if(val) {
rt.Add(ERL_DRV_EXT2TERM);
rt.Add((ErlDrvTermData)(val->bin));
rt.Add((ErlDrvTermData)(val->size));
} else
rt.Add(ERL_DRV_NIL);
}
INLINE
void wxeReturn::addUint(unsigned int n) {
add(ERL_DRV_UINT, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::addInt(int n) {
add(ERL_DRV_INT, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::addFloat(double f) {
// Erlang expects a pointer to double...
// Hmm is temp_float moved if reallocated
// the pointer may be wrong.
// Harryhuk - use a list instead?
temp_float.Add(f);
add(ERL_DRV_FLOAT, (ErlDrvTermData)&temp_float.Last());
}
INLINE
void wxeReturn::addTupleCount(unsigned int n) {
add(ERL_DRV_TUPLE, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::endList(unsigned int n) {
rt.Add(ERL_DRV_NIL);
add(ERL_DRV_LIST, (ErlDrvTermData)(n+1));
}
INLINE
void wxeReturn::addBool(int val) {
if (val) {
addAtom("true");
} else {
addAtom("false");
}
}
INLINE
void wxeReturn::add(const wxString s) {
int strLen = s.Len();
wxCharBuffer resultCB = s.mb_str(utfConverter);
int * resultPtr = (int *) resultCB.data();
for (int i = 0; i < strLen; i++, resultPtr++) {
addInt(*resultPtr);
}
endList(strLen);
}
INLINE
void wxeReturn::add(const wxString* s) {
add(*s);
}
INLINE
void wxeReturn::add(wxArrayString val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
add(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxArrayInt val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
addInt(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxArrayDouble val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
addFloat(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxUIntPtr *val) {
add(ERL_DRV_UINT, (ErlDrvTermData) val);
}
INLINE
void wxeReturn::add(wxPoint pt) {
addInt(pt.x);
addInt(pt.y);
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxPoint2DDouble pt) {
addFloat(pt.m_x);
addFloat(pt.m_y);
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxSize size) {
addInt(size.GetWidth());
addInt(size.GetHeight());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxRect rect) {
addInt(rect.x);
addInt(rect.y);
addInt(rect.width);
addInt(rect.height);
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxColour colour) {
addInt(colour.Red());
addInt(colour.Green());
addInt(colour.Blue());
addInt(colour.Alpha());
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxDateTime dateTime) {
addDate(dateTime);
addTime(dateTime);
addTupleCount(2);
}
INLINE
void wxeReturn::addDate(wxDateTime dateTime) {
addInt(dateTime.GetYear());
addInt(dateTime.GetMonth()+1); // c++ month is zero based
addInt(dateTime.GetDay());
addTupleCount(3);
}
INLINE void wxeReturn::addTime(wxDateTime dateTime) {
addInt(dateTime.GetHour());
addInt(dateTime.GetMinute());
addInt(dateTime.GetSecond());
addTupleCount(3);
}
INLINE
void wxeReturn::add(wxRect2DDouble rect2D) {
addFloat(rect2D.m_x);
addFloat(rect2D.m_y);
addFloat(rect2D.m_width);
addFloat(rect2D.m_height);
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxGridCellCoords val) {
addInt(val.GetRow());
addInt(val.GetCol());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxGBPosition val) {
addInt(val.GetRow());
addInt(val.GetCol());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxGBSpan val) {
addInt(val.GetRowspan());
addInt(val.GetColspan());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxMouseState val) {
addAtom("wxMouseState");
// TODO not int?
addUint(val.GetX());
addUint(val.GetY());
addBool(val.LeftDown());
addBool(val.MiddleDown());
addBool(val.RightDown());
addBool(val.ControlDown());
addBool(val.ShiftDown());
addBool(val.AltDown());
addBool(val.MetaDown());
addBool(val.CmdDown());
addTupleCount(11);
}
INLINE
void wxeReturn::add(const wxHtmlLinkInfo *val) {
addAtom("wxHtmlLinkInfo");
add(val->GetHref());
add(val->GetTarget());
addTupleCount(3);
}
INLINE
void wxeReturn::add(const wxHtmlLinkInfo &val) {
addAtom("wxHtmlLinkInfo");
add(val.GetHref());
add(val.GetTarget());
addTupleCount(3);
}
<commit_msg>wx: Fix looping debug printout<commit_after>/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2008-2013. All Rights Reserved.
*
* The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved online at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* %CopyrightEnd%
*/
#include "wxe_return.h"
// see http://docs.wxwidgets.org/stable/wx_wxarray.html#arraymacros
// this is a magic incantation which must be done!
#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(wxErlDrvTermDataArray);
#define INLINE
wxeReturn::wxeReturn (ErlDrvTermData _port,
ErlDrvTermData _caller,
bool _isResult) {
port = _port;
caller = _caller;
isResult = _isResult;
if (isResult) {
addAtom("_wxe_result_");
}
}
wxeReturn::~wxeReturn () {
//depending on which version of wxArray we use, we may have to clear it ourselves.
}
int wxeReturn::send() {
if ((rt.GetCount() == 2 && isResult) || rt.GetCount() == 0)
return 1; // not a call bail out
if (isResult) {
addTupleCount(2);
}
// rt to array
unsigned int rtLength = rt.GetCount(); //signed int
size_t size = sizeof(ErlDrvTermData)*(rtLength);
ErlDrvTermData* rtData = (ErlDrvTermData *) driver_alloc(size);
for (unsigned int i=0; i < rtLength; i++) {
rtData[i] = rt[i];
}
int res = erl_drv_send_term(port, caller, rtData, rtLength);
driver_free(rtData);
#ifdef DEBUG
if(res == -1) {
fprintf(stderr, "Failed to send return or event msg\r\n");
}
#endif
reset();
return res;
}
//clear everything so we can re-use if we want
void wxeReturn::reset() {
rt.empty();
temp_float.empty();
}
INLINE
unsigned int wxeReturn::size() {
return rt.GetCount();
}
INLINE
void wxeReturn::add(ErlDrvTermData type, ErlDrvTermData data) {
rt.Add(type);
rt.Add(data);
}
// INLINE
// void wxeReturn::addRef(const void *ptr, const char* className) {
// unsigned int ref_idx = wxe_app->getRef((void *)ptr, memEnv);
// addRef(ref_idx, className);
// }
INLINE
void wxeReturn::addRef(const unsigned int ref, const char* className) {
addAtom("wx_ref");
addUint(ref);
addAtom(className);
rt.Add(ERL_DRV_NIL);
addTupleCount(4);
}
INLINE
void wxeReturn::addAtom(const char* atomName) {
add(ERL_DRV_ATOM, driver_mk_atom((char *)atomName));
}
INLINE
void wxeReturn::addBinary(const char* buf, const size_t size) {
rt.Add(ERL_DRV_BUF2BINARY);
rt.Add((ErlDrvTermData)buf);
rt.Add((ErlDrvTermData)size);
}
INLINE
void wxeReturn::addExt2Term(wxeErlTerm *term) {
if(term) {
rt.Add(ERL_DRV_EXT2TERM);
rt.Add((ErlDrvTermData)term->bin);
rt.Add((ErlDrvTermData)term->size);
} else {
rt.Add(ERL_DRV_NIL);
}
}
INLINE
void wxeReturn::addExt2Term(wxETreeItemData *val) {
if(val) {
rt.Add(ERL_DRV_EXT2TERM);
rt.Add((ErlDrvTermData)(val->bin));
rt.Add((ErlDrvTermData)(val->size));
} else
rt.Add(ERL_DRV_NIL);
}
INLINE
void wxeReturn::addUint(unsigned int n) {
add(ERL_DRV_UINT, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::addInt(int n) {
add(ERL_DRV_INT, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::addFloat(double f) {
// Erlang expects a pointer to double...
// Hmm is temp_float moved if reallocated
// the pointer may be wrong.
// Harryhuk - use a list instead?
temp_float.Add(f);
add(ERL_DRV_FLOAT, (ErlDrvTermData)&temp_float.Last());
}
INLINE
void wxeReturn::addTupleCount(unsigned int n) {
add(ERL_DRV_TUPLE, (ErlDrvTermData)n);
}
INLINE
void wxeReturn::endList(unsigned int n) {
rt.Add(ERL_DRV_NIL);
add(ERL_DRV_LIST, (ErlDrvTermData)(n+1));
}
INLINE
void wxeReturn::addBool(int val) {
if (val) {
addAtom("true");
} else {
addAtom("false");
}
}
INLINE
void wxeReturn::add(const wxString s) {
int strLen = s.Len();
wxCharBuffer resultCB = s.mb_str(utfConverter);
int * resultPtr = (int *) resultCB.data();
for (int i = 0; i < strLen; i++, resultPtr++) {
addInt(*resultPtr);
}
endList(strLen);
}
INLINE
void wxeReturn::add(const wxString* s) {
add(*s);
}
INLINE
void wxeReturn::add(wxArrayString val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
add(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxArrayInt val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
addInt(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxArrayDouble val) {
unsigned int len = val.GetCount();
for (unsigned int i = 0; i< len; i++) {
addFloat(val[i]);
}
endList(len);
}
INLINE
void wxeReturn::add(wxUIntPtr *val) {
add(ERL_DRV_UINT, (ErlDrvTermData) val);
}
INLINE
void wxeReturn::add(wxPoint pt) {
addInt(pt.x);
addInt(pt.y);
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxPoint2DDouble pt) {
addFloat(pt.m_x);
addFloat(pt.m_y);
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxSize size) {
addInt(size.GetWidth());
addInt(size.GetHeight());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxRect rect) {
addInt(rect.x);
addInt(rect.y);
addInt(rect.width);
addInt(rect.height);
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxColour colour) {
addInt(colour.Red());
addInt(colour.Green());
addInt(colour.Blue());
addInt(colour.Alpha());
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxDateTime dateTime) {
addDate(dateTime);
addTime(dateTime);
addTupleCount(2);
}
INLINE
void wxeReturn::addDate(wxDateTime dateTime) {
addInt(dateTime.GetYear());
addInt(dateTime.GetMonth()+1); // c++ month is zero based
addInt(dateTime.GetDay());
addTupleCount(3);
}
INLINE void wxeReturn::addTime(wxDateTime dateTime) {
addInt(dateTime.GetHour());
addInt(dateTime.GetMinute());
addInt(dateTime.GetSecond());
addTupleCount(3);
}
INLINE
void wxeReturn::add(wxRect2DDouble rect2D) {
addFloat(rect2D.m_x);
addFloat(rect2D.m_y);
addFloat(rect2D.m_width);
addFloat(rect2D.m_height);
addTupleCount(4);
}
INLINE
void wxeReturn::add(wxGridCellCoords val) {
addInt(val.GetRow());
addInt(val.GetCol());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxGBPosition val) {
addInt(val.GetRow());
addInt(val.GetCol());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxGBSpan val) {
addInt(val.GetRowspan());
addInt(val.GetColspan());
addTupleCount(2);
}
INLINE
void wxeReturn::add(wxMouseState val) {
addAtom("wxMouseState");
// TODO not int?
addUint(val.GetX());
addUint(val.GetY());
addBool(val.LeftDown());
addBool(val.MiddleDown());
addBool(val.RightDown());
addBool(val.ControlDown());
addBool(val.ShiftDown());
addBool(val.AltDown());
addBool(val.MetaDown());
addBool(val.CmdDown());
addTupleCount(11);
}
INLINE
void wxeReturn::add(const wxHtmlLinkInfo *val) {
addAtom("wxHtmlLinkInfo");
add(val->GetHref());
add(val->GetTarget());
addTupleCount(3);
}
INLINE
void wxeReturn::add(const wxHtmlLinkInfo &val) {
addAtom("wxHtmlLinkInfo");
add(val.GetHref());
add(val.GetTarget());
addTupleCount(3);
}
<|endoftext|>
|
<commit_before>// Copyright 2019 TF.Text Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "base/integral_types.h"
#include "tensorflow/core/framework/lookup_interface.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace text {
namespace {
} // namespace
// ROUGE-L implementation based on
// https://www.microsoft.com/en-us/research/publication/
// rouge-a-package-for-automatic-evaluation-of-summaries/
template <typename SPLITS_TYPE, typename VALUES_TYPE>
class RougeLOp : public OpKernel {
public:
using ConstFlatSplits = typename TTypes<SPLITS_TYPE>::ConstFlat;
using ConstFlatValues = typename TTypes<VALUES_TYPE>::ConstFlat;
explicit RougeLOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor& hyp_tensor = ctx->input(0);
const auto hyp_tensor_flat = hyp_tensor.flat<VALUES_TYPE>();
const Tensor& hyp_splits = ctx->input(1);
const auto hyp_splits_flat = hyp_splits.flat<SPLITS_TYPE>();
const Tensor& ref_tensor = ctx->input(2);
const auto ref_tensor_flat = ref_tensor.flat<VALUES_TYPE>();
const Tensor& ref_splits = ctx->input(3);
const auto ref_splits_flat = ref_splits.flat<SPLITS_TYPE>();
const Tensor& alpha_tensor = ctx->input(4);
const auto alpha_scalar = alpha_tensor.scalar<float>();
const float alpha = alpha_scalar();
// Alpha must be <=1.
OP_REQUIRES(ctx, alpha <= 1,
errors::InvalidArgument("alpha must be <1 but was=", alpha));
// Ref and Hyp must have the same number of rows.
OP_REQUIRES(ctx, ref_splits_flat.size() == hyp_splits_flat.size(),
errors::InvalidArgument(
"ref splits len=", ref_splits_flat.size(),
"must equal hyp splits len=", hyp_splits_flat.size()));
// All inputs must be vectors.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(hyp_tensor.shape()),
errors::InvalidArgument("hypotheses values must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ref_tensor.shape()),
errors::InvalidArgument("references values must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(hyp_splits.shape()),
errors::InvalidArgument("hypotheses splits must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ref_splits.shape()),
errors::InvalidArgument("references splits must be a vector"));
// Ref and Hyp must have at least one split.
OP_REQUIRES(ctx, ref_splits_flat.size() > 0,
errors::InvalidArgument(
"ref splits len=0; must have at least 1 split"));
// Output is a dense Tensor containing one row per input row.
TensorShape output_shape({ref_splits_flat.size() - 1});
// Allocate the F-Measure output tensor.
Tensor* f_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("f_measure", output_shape,
&f_measure_tensor));
auto f_measures_flat = f_measure_tensor->flat<float>();
// Allocate the P-Measure output tensor.
Tensor* p_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("p_measure", output_shape,
&p_measure_tensor));
auto p_measures_flat = p_measure_tensor->flat<float>();
// Allocate the R-Measure output tensor.
Tensor* r_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("r_measure", output_shape,
&r_measure_tensor));
auto r_measures_flat = r_measure_tensor->flat<float>();
// Iterate over the splits, skipping the first split as it is always zero.
for (int i = 1; i < hyp_splits_flat.size(); i++) {
// Length of hyp and ref.
SPLITS_TYPE lhyp = hyp_splits_flat(i) - hyp_splits_flat(i-1);
SPLITS_TYPE lref = ref_splits_flat(i) - ref_splits_flat(i-1);
// Length of longest common substring.
int32 llcs = LongestCommonSubsequenceLength(hyp_splits_flat(i-1),
hyp_splits_flat(i),
hyp_tensor_flat,
ref_splits_flat(i-1),
ref_splits_flat(i),
ref_tensor_flat);
auto measures = ComputeMeasures(lhyp, lref, llcs, alpha);
f_measures_flat(i - 1) = std::get<0>(measures);
p_measures_flat(i - 1) = std::get<1>(measures);
r_measures_flat(i - 1) = std::get<2>(measures);
}
}
private:
// By using LCS, the ROUGE-L algorithm does not require consecutive matches
// but rather credits the order of N-grams.
int32 LongestCommonSubsequenceLength(
const SPLITS_TYPE hyp_i,
const SPLITS_TYPE hyp_j,
const ConstFlatValues& hyp,
const SPLITS_TYPE ref_i,
const SPLITS_TYPE ref_j,
const ConstFlatValues& ref) {
SPLITS_TYPE lhyp = hyp_j - hyp_i;
SPLITS_TYPE lref = ref_j - ref_i;
// Create a scratch matrix to keep track of the LCS seen so far using DP.
// http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Tensor scratch(DT_INT32, {lhyp + 2, lref + 2});
auto scratch2d = scratch.matrix<int32>();
for (SPLITS_TYPE x = hyp_i; x <= hyp_j + 1; x++) {
for (SPLITS_TYPE y = ref_i; y <= ref_j + 1; y++) {
SPLITS_TYPE a = x - hyp_i;
SPLITS_TYPE b = y - ref_i;
if (a == 0 || b == 0) {
// If in first row or column, we write a zero to the table.
scratch2d(a, b) = 0;
} else if (x == hyp_j+1 || y == ref_j+1 || hyp(x-1) != ref(y-1)) {
// If in the last row or column, or if the tokens are not equal,
// carry the largest score seen in the cell above or to the left of
// the current cell.
scratch2d(a, b) = max({scratch2d(a - 1, b), scratch2d(a, b - 1)});
} else {
// If tokens are equal, we are part of a subsequence, so increment the
// diagonal score.
scratch2d(a, b) = scratch2d(a - 1, b - 1) + 1;
}
}
}
return scratch2d(lhyp, lref);
}
std::tuple<float, float, float> ComputeMeasures(const SPLITS_TYPE lhyp_int,
const SPLITS_TYPE lref_int,
const int32 llcs_int,
const float alpha) {
const float lhyp = static_cast<float>(lhyp_int);
const float lref = static_cast<float>(lref_int);
const float llcs = static_cast<float>(llcs_int);
const float p_lcs = llcs / (lhyp + 1e-12);
const float r_lcs = llcs / (lref + 1e-12);
// Use the tensor2tensor formulation if the alpha value is <0,
// which does not make sense as a weighted average term.
const float f_lcs = alpha < 0 ?
ComputeTensor2TensorF(p_lcs, r_lcs) :
ComputeOfficialF(p_lcs, r_lcs, alpha);
return std::make_tuple(f_lcs, p_lcs, r_lcs);
}
float ComputeTensor2TensorF(const float p_lcs, const float r_lcs) {
const float beta = p_lcs / (r_lcs + 1e-12);
const float numerator = (1 + (beta * beta)) * r_lcs * p_lcs;
const float denominator = r_lcs + ((beta * beta) * p_lcs);
if (denominator > 0) {
return numerator / denominator;
}
return 0;
}
float ComputeOfficialF(const float p_lcs, const float r_lcs,
const float alpha) {
float denominator = (alpha * r_lcs + (1 - alpha) * p_lcs);
if (denominator > 0) {
return (p_lcs * r_lcs) / denominator;
}
return denominator;
}
TF_DISALLOW_COPY_AND_ASSIGN(RougeLOp);
};
#define REGISTER(VALUES_TYPE) \
REGISTER_KERNEL_BUILDER(Name("RougeL") \
.Device(DEVICE_CPU) \
.TypeConstraint<int32>("Tsplits") \
.TypeConstraint<VALUES_TYPE>("Tvalues"), \
RougeLOp<int32, VALUES_TYPE>); \
REGISTER_KERNEL_BUILDER(Name("RougeL") \
.Device(DEVICE_CPU) \
.TypeConstraint<int64>("Tsplits") \
.TypeConstraint<VALUES_TYPE>("Tvalues"), \
RougeLOp<int64, VALUES_TYPE>);
TF_CALL_int32(REGISTER);
TF_CALL_int64(REGISTER);
TF_CALL_string(REGISTER);
#undef REGISTER
} // namespace text
} // namespace tensorflow
<commit_msg>Internal change<commit_after>// Copyright 2019 TF.Text Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "base/integral_types.h"
#include "tensorflow/core/framework/lookup_interface.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace text {
namespace {
} // namespace
// ROUGE-L implementation based on
// https://www.microsoft.com/en-us/research/publication/
// rouge-a-package-for-automatic-evaluation-of-summaries/
template <typename SPLITS_TYPE, typename VALUES_TYPE>
class RougeLOp : public OpKernel {
public:
using ConstFlatSplits = typename TTypes<SPLITS_TYPE>::ConstFlat;
using ConstFlatValues = typename TTypes<VALUES_TYPE>::ConstFlat;
explicit RougeLOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor& hyp_tensor = ctx->input(0);
const auto hyp_tensor_flat = hyp_tensor.flat<VALUES_TYPE>();
const Tensor& hyp_splits = ctx->input(1);
const auto hyp_splits_flat = hyp_splits.flat<SPLITS_TYPE>();
const Tensor& ref_tensor = ctx->input(2);
const auto ref_tensor_flat = ref_tensor.flat<VALUES_TYPE>();
const Tensor& ref_splits = ctx->input(3);
const auto ref_splits_flat = ref_splits.flat<SPLITS_TYPE>();
const Tensor& alpha_tensor = ctx->input(4);
const auto alpha_scalar = alpha_tensor.scalar<float>();
const float alpha = alpha_scalar();
// Alpha must be <=1.
OP_REQUIRES(ctx, alpha <= 1,
errors::InvalidArgument("alpha must be <1 but was=", alpha));
// Ref and Hyp must have the same number of rows.
OP_REQUIRES(ctx, ref_splits_flat.size() == hyp_splits_flat.size(),
errors::InvalidArgument(
"ref splits len=", ref_splits_flat.size(),
"must equal hyp splits len=", hyp_splits_flat.size()));
// All inputs must be vectors.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(hyp_tensor.shape()),
errors::InvalidArgument("hypotheses values must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ref_tensor.shape()),
errors::InvalidArgument("references values must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(hyp_splits.shape()),
errors::InvalidArgument("hypotheses splits must be a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ref_splits.shape()),
errors::InvalidArgument("references splits must be a vector"));
// Ref and Hyp must have at least one split.
OP_REQUIRES(ctx, ref_splits_flat.size() > 0,
errors::InvalidArgument(
"ref splits len=0; must have at least 1 split"));
// Output is a dense Tensor containing one row per input row.
TensorShape output_shape({ref_splits_flat.size() - 1});
// Allocate the F-Measure output tensor.
Tensor* f_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("f_measure", output_shape,
&f_measure_tensor));
auto f_measures_flat = f_measure_tensor->flat<float>();
// Allocate the P-Measure output tensor.
Tensor* p_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("p_measure", output_shape,
&p_measure_tensor));
auto p_measures_flat = p_measure_tensor->flat<float>();
// Allocate the R-Measure output tensor.
Tensor* r_measure_tensor;
OP_REQUIRES_OK(ctx, ctx->allocate_output("r_measure", output_shape,
&r_measure_tensor));
auto r_measures_flat = r_measure_tensor->flat<float>();
// Iterate over the splits, skipping the first split as it is always zero.
for (int i = 1; i < hyp_splits_flat.size(); i++) {
// Length of hyp and ref.
SPLITS_TYPE lhyp = hyp_splits_flat(i) - hyp_splits_flat(i-1);
SPLITS_TYPE lref = ref_splits_flat(i) - ref_splits_flat(i-1);
// Length of longest common substring.
int32 llcs = LongestCommonSubsequenceLength(hyp_splits_flat(i-1),
hyp_splits_flat(i),
hyp_tensor_flat,
ref_splits_flat(i-1),
ref_splits_flat(i),
ref_tensor_flat);
auto measures = ComputeMeasures(lhyp, lref, llcs, alpha);
f_measures_flat(i - 1) = std::get<0>(measures);
p_measures_flat(i - 1) = std::get<1>(measures);
r_measures_flat(i - 1) = std::get<2>(measures);
}
}
private:
// By using LCS, the ROUGE-L algorithm does not require consecutive matches
// but rather credits the order of N-grams.
int32 LongestCommonSubsequenceLength(
const SPLITS_TYPE hyp_i,
const SPLITS_TYPE hyp_j,
const ConstFlatValues& hyp,
const SPLITS_TYPE ref_i,
const SPLITS_TYPE ref_j,
const ConstFlatValues& ref) {
SPLITS_TYPE lhyp = hyp_j - hyp_i;
SPLITS_TYPE lref = ref_j - ref_i;
// Create a scratch matrix to keep track of the LCS seen so far using DP.
// http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Tensor scratch(DT_INT32, {lhyp + 2, lref + 2});
auto scratch2d = scratch.matrix<int32>();
for (SPLITS_TYPE x = hyp_i; x <= hyp_j + 1; x++) {
for (SPLITS_TYPE y = ref_i; y <= ref_j + 1; y++) {
SPLITS_TYPE a = x - hyp_i;
SPLITS_TYPE b = y - ref_i;
if (a == 0 || b == 0) {
// If in first row or column, we write a zero to the table.
scratch2d(a, b) = 0;
} else if (x == hyp_j+1 || y == ref_j+1 || hyp(x-1) != ref(y-1)) {
// If in the last row or column, or if the tokens are not equal,
// carry the largest score seen in the cell above or to the left of
// the current cell.
scratch2d(a, b) =
std::max({scratch2d(a - 1, b), scratch2d(a, b - 1)});
} else {
// If tokens are equal, we are part of a subsequence, so increment the
// diagonal score.
scratch2d(a, b) = scratch2d(a - 1, b - 1) + 1;
}
}
}
return scratch2d(lhyp, lref);
}
std::tuple<float, float, float> ComputeMeasures(const SPLITS_TYPE lhyp_int,
const SPLITS_TYPE lref_int,
const int32 llcs_int,
const float alpha) {
const float lhyp = static_cast<float>(lhyp_int);
const float lref = static_cast<float>(lref_int);
const float llcs = static_cast<float>(llcs_int);
const float p_lcs = llcs / (lhyp + 1e-12);
const float r_lcs = llcs / (lref + 1e-12);
// Use the tensor2tensor formulation if the alpha value is <0,
// which does not make sense as a weighted average term.
const float f_lcs = alpha < 0 ?
ComputeTensor2TensorF(p_lcs, r_lcs) :
ComputeOfficialF(p_lcs, r_lcs, alpha);
return std::make_tuple(f_lcs, p_lcs, r_lcs);
}
float ComputeTensor2TensorF(const float p_lcs, const float r_lcs) {
const float beta = p_lcs / (r_lcs + 1e-12);
const float numerator = (1 + (beta * beta)) * r_lcs * p_lcs;
const float denominator = r_lcs + ((beta * beta) * p_lcs);
if (denominator > 0) {
return numerator / denominator;
}
return 0;
}
float ComputeOfficialF(const float p_lcs, const float r_lcs,
const float alpha) {
float denominator = (alpha * r_lcs + (1 - alpha) * p_lcs);
if (denominator > 0) {
return (p_lcs * r_lcs) / denominator;
}
return denominator;
}
TF_DISALLOW_COPY_AND_ASSIGN(RougeLOp);
};
#define REGISTER(VALUES_TYPE) \
REGISTER_KERNEL_BUILDER(Name("RougeL") \
.Device(DEVICE_CPU) \
.TypeConstraint<int32>("Tsplits") \
.TypeConstraint<VALUES_TYPE>("Tvalues"), \
RougeLOp<int32, VALUES_TYPE>); \
REGISTER_KERNEL_BUILDER(Name("RougeL") \
.Device(DEVICE_CPU) \
.TypeConstraint<int64>("Tsplits") \
.TypeConstraint<VALUES_TYPE>("Tvalues"), \
RougeLOp<int64, VALUES_TYPE>);
TF_CALL_int32(REGISTER);
TF_CALL_int64(REGISTER);
TF_CALL_string(REGISTER);
#undef REGISTER
} // namespace text
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*
kopeteaccount.cpp - Kopete Account
Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@tiscalinet.be>
Copyright (c) 2003-2004 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2004 by Richard Smith <kde@metafoo.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include <qapplication.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kdialogbase.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kiconeffect.h>
#include <kaction.h>
#include <kpopupmenu.h>
#include "kopetecontactlist.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontact.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
#include "kopetegroup.h"
#include "kopeteprefs.h"
#include "kopeteblacklister.h"
#include "kopeteonlinestatusmanager.h"
#include "editaccountwidget.h"
namespace Kopete
{
class Account::Private
{
public:
Private( Protocol *protocol, const QString &accountId )
: protocol( protocol ), id( accountId )
, autoconnect( true ), priority( 0 ), myself( 0 )
, suppressStatusTimer( 0 ), suppressStatusNotification( false )
, blackList( new Kopete::BlackLister( protocol->pluginId(), accountId ) )
{ }
~Private() { delete blackList; }
Protocol *protocol;
QString id;
bool autoconnect;
uint priority;
QDict<Contact> contacts;
QColor color;
Contact *myself;
QTimer suppressStatusTimer;
bool suppressStatusNotification;
Kopete::BlackLister *blackList;
KConfigGroup *configGroup;
};
Account::Account( Protocol *parent, const QString &accountId, const char *name )
: QObject( parent, name ), d( new Private( parent, accountId ) )
{
d->configGroup=new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Account_%1_%2" ).arg( d->protocol->pluginId(), d->id ));
d->autoconnect = d->configGroup->readBoolEntry( "AutoConnect", true );
d->color = d->configGroup->readColorEntry( "Color", &d->color );
d->priority = d->configGroup->readNumEntry( "Priority", 0 );
QObject::connect( &d->suppressStatusTimer, SIGNAL( timeout() ),
this, SLOT( slotStopSuppression() ) );
}
Account::~Account()
{
emit accountDestroyed(this);
// Delete all registered child contacts first
while ( !d->contacts.isEmpty() )
delete *QDictIterator<Contact>( d->contacts );
emit accountDestroyed(this);
delete d->configGroup;
delete d;
}
void Account::disconnected( DisconnectReason reason )
{
//reconnect if needed
if ( ( KopetePrefs::prefs()->reconnectOnDisconnect() == true && reason > Manual ) ||
reason == BadPassword )
{
//use a timer to allow the plugins to clean up after return
QTimer::singleShot(0, this, SLOT(connect()));
}
}
Protocol *Account::protocol() const
{
return d->protocol;
}
QString Account::accountId() const
{
return d->id;
}
const QColor Account::color() const
{
return d->color;
}
void Account::setColor( const QColor &color )
{
d->color = color;
if ( d->color.isValid() )
d->configGroup->writeEntry( "Color", d->color );
else
d->configGroup->deleteEntry( "Color" );
emit colorChanged( color );
}
void Account::setPriority( uint priority )
{
d->priority = priority;
d->configGroup->writeEntry( "Priority", d->priority );
}
uint Account::priority() const
{
return d->priority;
}
QPixmap Account::accountIcon(const int size) const
{
// FIXME: this code is duplicated with OnlineStatus, can we merge it somehow?
QPixmap base = KGlobal::instance()->iconLoader()->loadIcon(
d->protocol->pluginIcon(), KIcon::Small, size );
if ( d->color.isValid() )
{
KIconEffect effect;
base = effect.apply( base, KIconEffect::Colorize, 1, d->color, 0);
}
if ( size > 0 && base.width() != size )
{
base = QPixmap( base.convertToImage().smoothScale( size, size ) );
}
return base;
}
KConfigGroup* Kopete::Account::configGroup() const
{
return d->configGroup;
}
void Account::setAutoConnect( bool b )
{
d->autoconnect = b;
d->configGroup->writeEntry( "AutoConnect", d->autoconnect );
}
bool Account::autoConnect() const
{
return d->autoconnect;
}
void Account::registerContact( Contact *c )
{
d->contacts.insert( c->contactId(), c );
QObject::connect( c, SIGNAL( contactDestroyed( Kopete::Contact * ) ),
SLOT( contactDestroyed( Kopete::Contact * ) ) );
}
void Account::contactDestroyed( Contact *c )
{
d->contacts.remove( c->contactId() );
}
const QDict<Contact>& Account::contacts()
{
return d->contacts;
}
bool Account::addContact( const QString &contactId, const QString &displayName , Group *group, AddMode mode )
{
if ( contactId == d->myself->contactId() )
{
kdDebug( 14010 ) << k_funcinfo <<
"WARNING: the user try to add myself to his contactlist - abort" << endl;
return false;
}
bool isTemporary = mode == Temporary;
Contact *c = d->contacts[ contactId ];
if(!group)
group=Group::topLevel();
if ( c && c->metaContact() )
{
if ( c->metaContact()->isTemporary() && !isTemporary )
{
kdDebug( 14010 ) << k_funcinfo << " You are trying to add an existing temporary contact. Just add it on the list" << endl;
c->metaContact()->setTemporary(false, group );
ContactList::self()->addMetaContact(c->metaContact());
}
else
{
// should we here add the contact to the parentContact if any?
kdDebug( 14010 ) << k_funcinfo << "Contact already exists" << endl;
}
return c->metaContact();
}
MetaContact *parentContact = new MetaContact();
if(!displayName.isEmpty())
parentContact->setDisplayName( displayName );
//Set it as a temporary contact if requested
if ( isTemporary )
parentContact->setTemporary( true );
else
parentContact->addToGroup( group );
if ( c )
{
c->setMetaContact( parentContact );
if ( mode == ChangeKABC )
{
parentContact->updateKABC();
}
}
else
{
if ( !createContact( contactId, parentContact ) )
{
delete parentContact;
return false;
}
}
ContactList::self()->addMetaContact( parentContact );
return true;
}
bool Account::addContact(const QString &contactId , MetaContact *parent, AddMode mode )
{
if ( contactId == myself()->contactId() )
{
kdDebug( 14010 ) << k_funcinfo <<
"WARNING: the user try to add myself to his contactlist - abort" << endl;
return 0L;
}
bool isTemporary= parent->isTemporary();
Contact *c = d->contacts[ contactId ];
if ( c && c->metaContact() )
{
if ( c->metaContact()->isTemporary() && !isTemporary )
{
kdDebug( 14010 ) <<
"Account::addContact: You are trying to add an existing temporary contact. Just add it on the list" << endl;
//setMetaContact ill take care about the deletion of the old contact
c->setMetaContact(parent);
return true;
}
else
{
// should we here add the contact to the parentContact if any?
kdDebug( 14010 ) << "Account::addContact: Contact already exists" << endl;
}
return false; //(the contact is not in the correct metacontact, so false)
}
bool success = createContact(contactId, parent);
if ( success && mode == ChangeKABC )
{
kdDebug( 14010 ) << k_funcinfo << " changing KABC" << endl;
parent->updateKABC();
}
return success;
}
KActionMenu * Account::actionMenu()
{
//default implementation
KActionMenu * menu=new KActionMenu( accountId(), myself()->onlineStatus().iconFor( this ), this );
QString nick=myself()->property( Kopete::Global::Properties::self()->nickName()).value().toString();
menu->popupMenu()->insertTitle( myself()->onlineStatus().iconFor( myself() ),
nick.isNull() ? accountId() : i18n( "%2 <%1>" ).arg( accountId() , nick ) );
OnlineStatusManager::self()->createAccountStatusActions(this, menu);
menu->popupMenu()->insertSeparator();
menu->insert( new KAction ( i18n( "Properties" ), 0, this, SLOT( editAccount() ), menu, "actionAccountProperties" ) );
return menu;
}
bool Account::isConnected() const
{
return myself() && myself()->isOnline();
}
bool Account::isAway() const
{
return d->myself && ( d->myself->onlineStatus().status() == Kopete::OnlineStatus::Away );
}
Contact * Account::myself() const
{
return d->myself;
}
void Account::setMyself( Contact *myself )
{
bool wasConnected = isConnected();
if ( d->myself )
{
QObject::disconnect( d->myself, SIGNAL( onlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ),
this, SLOT( slotOnlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ) );
}
d->myself = myself;
QObject::connect( d->myself, SIGNAL( onlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ),
this, SLOT( slotOnlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ) );
if ( isConnected() != wasConnected )
emit isConnectedChanged();
}
void Account::slotOnlineStatusChanged( Contact * /* contact */,
const OnlineStatus &newStatus, const OnlineStatus &oldStatus )
{
bool wasOffline = !oldStatus.isDefinitelyOnline();
bool isOffline = !newStatus.isDefinitelyOnline();
if ( wasOffline || newStatus.status() == OnlineStatus::Offline )
{
// Wait for five seconds until we treat status notifications for contacts
// as unrelated to our own status change.
// Five seconds may seem like a long time, but just after your own
// connection it's basically neglectible, and depending on your own
// contact list's size, the protocol you are using, your internet
// connection's speed and your computer's speed you *will* need it.
d->suppressStatusNotification = true;
d->suppressStatusTimer.start( 5000, true );
}
kdDebug(14010) << k_funcinfo << "account " << d->id << " changed status. was "
<< Kopete::OnlineStatus::statusTypeToString(oldStatus.status()) << ", is "
<< Kopete::OnlineStatus::statusTypeToString(newStatus.status()) << endl;
if ( wasOffline != isOffline )
emit isConnectedChanged();
}
void Account::setAllContactsStatus( const Kopete::OnlineStatus &status )
{
for ( QDictIterator<Contact> it( d->contacts ); it.current(); ++it )
if ( it.current() != d->myself )
it.current()->setOnlineStatus( status );
}
void Account::slotStopSuppression()
{
d->suppressStatusNotification = false;
}
bool Account::suppressStatusNotification() const
{
return d->suppressStatusNotification;
}
bool Account::removeAccount()
{
//default implementation
return true;
}
BlackLister* Account::blackLister()
{
return d->blackList;
}
void Account::block( const QString &contactId )
{
d->blackList->addContact( contactId );
}
void Account::unblock( const QString &contactId )
{
d->blackList->removeContact( contactId );
}
bool Account::isBlocked( const QString &contactId )
{
return d->blackList->isBlocked( contactId );
}
void Account::editAccount(QWidget *parent)
{
KDialogBase *editDialog = new KDialogBase( parent, "KopeteAccountConfig::editDialog", true,
i18n( "Edit Account" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true );
KopeteEditAccountWidget *m_accountWidget = protocol()->createEditAccountWidget( this, editDialog );
if ( !m_accountWidget )
return;
// FIXME: Why the #### is EditAccountWidget not a QWidget?!? This sideways casting
// is braindead and error-prone. Looking at MSN the only reason I can see is
// because it allows direct subclassing of designer widgets. But what is
// wrong with embedding the designer widget in an empty QWidget instead?
// Also, if this REALLY has to be a pure class and not a widget, then the
// class should at least be renamed to EditAccountIface instead - Martijn
QWidget *w = dynamic_cast<QWidget *>( m_accountWidget );
if ( !w )
return;
editDialog->setMainWidget( w );
if ( editDialog->exec() == QDialog::Accepted )
{
if( m_accountWidget->validateData() )
m_accountWidget->apply();
}
editDialog->deleteLater();
}
void Account::setPluginData( Plugin* /*plugin*/, const QString &key, const QString &value )
{
configGroup()->writeEntry(key,value);
}
QString Account::pluginData( Plugin* /*plugin*/, const QString &key ) const
{
return configGroup()->readEntry(key);
}
void Account::virtual_hook( uint /*id*/, void* /*data*/)
{
}
} //END namespace Kopete
#include "kopeteaccount.moc"
<commit_msg>indent and spacing fixes<commit_after>/*
kopeteaccount.cpp - Kopete Account
Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@tiscalinet.be>
Copyright (c) 2003-2004 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2004 by Richard Smith <kde@metafoo.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include <qapplication.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kdialogbase.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kiconeffect.h>
#include <kaction.h>
#include <kpopupmenu.h>
#include "kopetecontactlist.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontact.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
#include "kopetegroup.h"
#include "kopeteprefs.h"
#include "kopeteblacklister.h"
#include "kopeteonlinestatusmanager.h"
#include "editaccountwidget.h"
namespace Kopete
{
class Account::Private
{
public:
Private( Protocol *protocol, const QString &accountId )
: protocol( protocol ), id( accountId )
, autoconnect( true ), priority( 0 ), myself( 0 )
, suppressStatusTimer( 0 ), suppressStatusNotification( false )
, blackList( new Kopete::BlackLister( protocol->pluginId(), accountId ) )
{ }
~Private() { delete blackList; }
Protocol *protocol;
QString id;
bool autoconnect;
uint priority;
QDict<Contact> contacts;
QColor color;
Contact *myself;
QTimer suppressStatusTimer;
bool suppressStatusNotification;
Kopete::BlackLister *blackList;
KConfigGroup *configGroup;
};
Account::Account( Protocol *parent, const QString &accountId, const char *name )
: QObject( parent, name ), d( new Private( parent, accountId ) )
{
d->configGroup=new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Account_%1_%2" ).arg( d->protocol->pluginId(), d->id ));
d->autoconnect = d->configGroup->readBoolEntry( "AutoConnect", true );
d->color = d->configGroup->readColorEntry( "Color", &d->color );
d->priority = d->configGroup->readNumEntry( "Priority", 0 );
QObject::connect( &d->suppressStatusTimer, SIGNAL( timeout() ),
this, SLOT( slotStopSuppression() ) );
}
Account::~Account()
{
emit accountDestroyed(this);
// Delete all registered child contacts first
while ( !d->contacts.isEmpty() )
delete *QDictIterator<Contact>( d->contacts );
emit accountDestroyed(this);
delete d->configGroup;
delete d;
}
void Account::disconnected( DisconnectReason reason )
{
//reconnect if needed
if ( ( KopetePrefs::prefs()->reconnectOnDisconnect() == true && reason > Manual ) ||
reason == BadPassword )
{
//use a timer to allow the plugins to clean up after return
QTimer::singleShot(0, this, SLOT(connect()));
}
}
Protocol *Account::protocol() const
{
return d->protocol;
}
QString Account::accountId() const
{
return d->id;
}
const QColor Account::color() const
{
return d->color;
}
void Account::setColor( const QColor &color )
{
d->color = color;
if ( d->color.isValid() )
d->configGroup->writeEntry( "Color", d->color );
else
d->configGroup->deleteEntry( "Color" );
emit colorChanged( color );
}
void Account::setPriority( uint priority )
{
d->priority = priority;
d->configGroup->writeEntry( "Priority", d->priority );
}
uint Account::priority() const
{
return d->priority;
}
QPixmap Account::accountIcon(const int size) const
{
// FIXME: this code is duplicated with OnlineStatus, can we merge it somehow?
QPixmap base = KGlobal::instance()->iconLoader()->loadIcon(
d->protocol->pluginIcon(), KIcon::Small, size );
if ( d->color.isValid() )
{
KIconEffect effect;
base = effect.apply( base, KIconEffect::Colorize, 1, d->color, 0);
}
if ( size > 0 && base.width() != size )
{
base = QPixmap( base.convertToImage().smoothScale( size, size ) );
}
return base;
}
KConfigGroup* Kopete::Account::configGroup() const
{
return d->configGroup;
}
void Account::setAutoConnect( bool b )
{
d->autoconnect = b;
d->configGroup->writeEntry( "AutoConnect", d->autoconnect );
}
bool Account::autoConnect() const
{
return d->autoconnect;
}
void Account::registerContact( Contact *c )
{
d->contacts.insert( c->contactId(), c );
QObject::connect( c, SIGNAL( contactDestroyed( Kopete::Contact * ) ),
SLOT( contactDestroyed( Kopete::Contact * ) ) );
}
void Account::contactDestroyed( Contact *c )
{
d->contacts.remove( c->contactId() );
}
const QDict<Contact>& Account::contacts()
{
return d->contacts;
}
bool Account::addContact( const QString &contactId, const QString &displayName , Group *group, AddMode mode )
{
if ( contactId == d->myself->contactId() )
{
kdDebug( 14010 ) << k_funcinfo <<
"WARNING: the user try to add myself to his contactlist - abort" << endl;
return false;
}
bool isTemporary = mode == Temporary;
Contact *c = d->contacts[ contactId ];
if(!group)
group=Group::topLevel();
if ( c && c->metaContact() )
{
if ( c->metaContact()->isTemporary() && !isTemporary )
{
kdDebug( 14010 ) << k_funcinfo << " You are trying to add an existing temporary contact. Just add it on the list" << endl;
c->metaContact()->setTemporary(false, group );
ContactList::self()->addMetaContact(c->metaContact());
}
else
{
// should we here add the contact to the parentContact if any?
kdDebug( 14010 ) << k_funcinfo << "Contact already exists" << endl;
}
return c->metaContact();
}
MetaContact *parentContact = new MetaContact();
if(!displayName.isEmpty())
parentContact->setDisplayName( displayName );
//Set it as a temporary contact if requested
if ( isTemporary )
parentContact->setTemporary( true );
else
parentContact->addToGroup( group );
if ( c )
{
c->setMetaContact( parentContact );
if ( mode == ChangeKABC )
{
parentContact->updateKABC();
}
}
else
{
if ( !createContact( contactId, parentContact ) )
{
delete parentContact;
return false;
}
}
ContactList::self()->addMetaContact( parentContact );
return true;
}
bool Account::addContact(const QString &contactId , MetaContact *parent, AddMode mode )
{
if ( contactId == myself()->contactId() )
{
kdDebug( 14010 ) << k_funcinfo <<
"WARNING: the user try to add myself to his contactlist - abort" << endl;
return 0L;
}
bool isTemporary= parent->isTemporary();
Contact *c = d->contacts[ contactId ];
if ( c && c->metaContact() )
{
if ( c->metaContact()->isTemporary() && !isTemporary )
{
kdDebug( 14010 ) <<
"Account::addContact: You are trying to add an existing temporary contact. Just add it on the list" << endl;
//setMetaContact ill take care about the deletion of the old contact
c->setMetaContact(parent);
return true;
}
else
{
// should we here add the contact to the parentContact if any?
kdDebug( 14010 ) << "Account::addContact: Contact already exists" << endl;
}
return false; //(the contact is not in the correct metacontact, so false)
}
bool success = createContact(contactId, parent);
if ( success && mode == ChangeKABC )
{
kdDebug( 14010 ) << k_funcinfo << " changing KABC" << endl;
parent->updateKABC();
}
return success;
}
KActionMenu * Account::actionMenu()
{
//default implementation
KActionMenu * menu=new KActionMenu( accountId(), myself()->onlineStatus().iconFor( this ), this );
QString nick=myself()->property( Kopete::Global::Properties::self()->nickName()).value().toString();
menu->popupMenu()->insertTitle( myself()->onlineStatus().iconFor( myself() ),
nick.isNull() ? accountId() : i18n( "%2 <%1>" ).arg( accountId() , nick ) );
OnlineStatusManager::self()->createAccountStatusActions(this, menu);
menu->popupMenu()->insertSeparator();
menu->insert( new KAction ( i18n( "Properties" ), 0, this, SLOT( editAccount() ), menu, "actionAccountProperties" ) );
return menu;
}
bool Account::isConnected() const
{
return myself() && myself()->isOnline();
}
bool Account::isAway() const
{
return d->myself && ( d->myself->onlineStatus().status() == Kopete::OnlineStatus::Away );
}
Contact * Account::myself() const
{
return d->myself;
}
void Account::setMyself( Contact *myself )
{
bool wasConnected = isConnected();
if ( d->myself )
{
QObject::disconnect( d->myself, SIGNAL( onlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ),
this, SLOT( slotOnlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ) );
}
d->myself = myself;
QObject::connect( d->myself, SIGNAL( onlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ),
this, SLOT( slotOnlineStatusChanged( Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus & ) ) );
if ( isConnected() != wasConnected )
emit isConnectedChanged();
}
void Account::slotOnlineStatusChanged( Contact * /* contact */,
const OnlineStatus &newStatus, const OnlineStatus &oldStatus )
{
bool wasOffline = !oldStatus.isDefinitelyOnline();
bool isOffline = !newStatus.isDefinitelyOnline();
if ( wasOffline || newStatus.status() == OnlineStatus::Offline )
{
// Wait for five seconds until we treat status notifications for contacts
// as unrelated to our own status change.
// Five seconds may seem like a long time, but just after your own
// connection it's basically neglectible, and depending on your own
// contact list's size, the protocol you are using, your internet
// connection's speed and your computer's speed you *will* need it.
d->suppressStatusNotification = true;
d->suppressStatusTimer.start( 5000, true );
}
kdDebug(14010) << k_funcinfo << "account " << d->id << " changed status. was "
<< Kopete::OnlineStatus::statusTypeToString(oldStatus.status()) << ", is "
<< Kopete::OnlineStatus::statusTypeToString(newStatus.status()) << endl;
if ( wasOffline != isOffline )
emit isConnectedChanged();
}
void Account::setAllContactsStatus( const Kopete::OnlineStatus &status )
{
for ( QDictIterator<Contact> it( d->contacts ); it.current(); ++it )
if ( it.current() != d->myself )
it.current()->setOnlineStatus( status );
}
void Account::slotStopSuppression()
{
d->suppressStatusNotification = false;
}
bool Account::suppressStatusNotification() const
{
return d->suppressStatusNotification;
}
bool Account::removeAccount()
{
//default implementation
return true;
}
BlackLister* Account::blackLister()
{
return d->blackList;
}
void Account::block( const QString &contactId )
{
d->blackList->addContact( contactId );
}
void Account::unblock( const QString &contactId )
{
d->blackList->removeContact( contactId );
}
bool Account::isBlocked( const QString &contactId )
{
return d->blackList->isBlocked( contactId );
}
void Account::editAccount(QWidget *parent)
{
KDialogBase *editDialog = new KDialogBase( parent, "KopeteAccountConfig::editDialog", true,
i18n( "Edit Account" ), KDialogBase::Ok | KDialogBase::Cancel,
KDialogBase::Ok, true );
KopeteEditAccountWidget *m_accountWidget = protocol()->createEditAccountWidget( this, editDialog );
if ( !m_accountWidget )
return;
// FIXME: Why the #### is EditAccountWidget not a QWidget?!? This sideways casting
// is braindead and error-prone. Looking at MSN the only reason I can see is
// because it allows direct subclassing of designer widgets. But what is
// wrong with embedding the designer widget in an empty QWidget instead?
// Also, if this REALLY has to be a pure class and not a widget, then the
// class should at least be renamed to EditAccountIface instead - Martijn
QWidget *w = dynamic_cast<QWidget *>( m_accountWidget );
if ( !w )
return;
editDialog->setMainWidget( w );
if ( editDialog->exec() == QDialog::Accepted )
{
if( m_accountWidget->validateData() )
m_accountWidget->apply();
}
editDialog->deleteLater();
}
void Account::setPluginData( Plugin* /*plugin*/, const QString &key, const QString &value )
{
configGroup()->writeEntry(key,value);
}
QString Account::pluginData( Plugin* /*plugin*/, const QString &key ) const
{
return configGroup()->readEntry(key);
}
void Account::virtual_hook( uint /*id*/, void* /*data*/)
{
}
} //END namespace Kopete
#include "kopeteaccount.moc"
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "maildirresource.h"
#include "settings.h"
#include "settingsadaptor.h"
#include "configdialog.h"
#include <QtCore/QDir>
#include <QtDBus/QDBusConnection>
#include <akonadi/kmime/messageparts.h>
#include <akonadi/changerecorder.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collectionfetchscope.h>
#include <kdebug.h>
#include <kurl.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <KWindowSystem>
#include "libmaildir/maildir.h"
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<KMime::Message> MessagePtr;
using namespace Akonadi;
using KPIM::Maildir;
/** Creates a maildir object for the collection @p col, given it has the full ancestor chain set. */
static Maildir maildirForCollection( const Collection &col )
{
if ( col.remoteId().isEmpty() ) {
kWarning() << "Got incomplete ancestor chain:" << col;
return Maildir();
}
if ( col.parentCollection() == Collection::root() ) {
kWarning( col.remoteId() != Settings::self()->path() ) << "RID mismatch, is " << col.remoteId() << " expected " << Settings::self()->path();
return Maildir( col.remoteId(), Settings::self()->topLevelIsContainer() );
}
Maildir parentMd = maildirForCollection( col.parentCollection() );
return parentMd.subFolder( col.remoteId() );
}
MaildirResource::MaildirResource( const QString &id )
:ResourceBase( id )
{
new SettingsAdaptor( Settings::self() );
QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
Settings::self(), QDBusConnection::ExportAdaptors );
connect( this, SIGNAL(reloadConfiguration()), SLOT(ensureDirExists()) );
// We need to enable this here, otherwise we neither get the remote ID of the
// parent collection when a collection changes, nor the full item when an item
// is added.
changeRecorder()->fetchCollection( true );
changeRecorder()->itemFetchScope().fetchFullPayload( true );
changeRecorder()->itemFetchScope().setAncestorRetrieval( ItemFetchScope::All );
changeRecorder()->collectionFetchScope().setAncestorRetrieval( CollectionFetchScope::All );
}
MaildirResource::~ MaildirResource()
{
}
bool MaildirResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
Q_UNUSED( parts );
const Maildir md = maildirForCollection( item.parentCollection() );
if ( !md.isValid() ) {
cancelTask( i18n( "Unable to fetch item: The maildir folder \"%1\" is not valid.",
md.path() ) );
return false;
}
const QByteArray data = md.readEntry( item.remoteId() );
KMime::Message *mail = new KMime::Message();
mail->setContent( KMime::CRLFtoLF( data ) );
mail->parse();
Item i( item );
i.setPayload( MessagePtr( mail ) );
itemRetrieved( i );
return true;
}
void MaildirResource::aboutToQuit()
{
// The settings may not have been saved if e.g. they have been modified via
// DBus instead of the config dialog.
Settings::self()->writeConfig();
}
void MaildirResource::configure( WId windowId )
{
ConfigDialog dlg;
if ( windowId )
KWindowSystem::setMainWindow( &dlg, windowId );
dlg.exec();
ensureDirExists();
synchronizeCollectionTree();
}
void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection )
{
Maildir dir = maildirForCollection( collection );
QString errMsg;
if ( Settings::readOnly() || !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
cancelTask( i18n("Only email messages can be added to the Maildir resource.") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
const QString rid = dir.addEntry( mail->encodedContent() );
Item i( item );
i.setRemoteId( rid );
changeCommitted( i );
}
void MaildirResource::itemChanged( const Akonadi::Item& item, const QSet<QByteArray>& parts )
{
if ( Settings::self()->readOnly() || !parts.contains( MessagePart::Body ) ) {
changeProcessed();
return;
}
Maildir dir = maildirForCollection( item.parentCollection() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
cancelTask( i18n("Only email messages can be added to the Maildir resource.") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.writeEntry( item.remoteId(), mail->encodedContent() );
changeCommitted( item );
}
void MaildirResource::itemRemoved(const Akonadi::Item & item)
{
if ( !Settings::self()->readOnly() ) {
Maildir dir = maildirForCollection( item.parentCollection() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
if ( !dir.removeEntry( item.remoteId() ) ) {
emit error( i18n("Failed to delete item: %1", item.remoteId()) );
}
}
changeProcessed();
}
Collection::List listRecursive( const Collection &root, const Maildir &dir )
{
Collection::List list;
const QStringList mimeTypes = QStringList() << "message/rfc822" << Collection::mimeType();
foreach ( const QString &sub, dir.subFolderList() ) {
Collection c;
c.setName( sub );
c.setRemoteId( sub );
c.setParentCollection( root );
c.setContentMimeTypes( mimeTypes );
const Maildir md = maildirForCollection( c );
if ( !md.isValid() )
continue;
list << c;
list += listRecursive( c, md );
}
return list;
}
void MaildirResource::retrieveCollections()
{
Maildir dir( Settings::self()->path(), Settings::self()->topLevelIsContainer() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
emit error( errMsg );
collectionsRetrieved( Collection::List() );
return;
}
Collection root;
root.setParentCollection( Collection::root() );
root.setRemoteId( Settings::self()->path() );
root.setName( name() );
// FIXME: enable once r1010699 is merged, doesn't build otherwise
// root.setRights( Collection::CanChangeItem | Collection::CanCreateItem | Collection::CanDeleteItem
// | Collection::CanCreateCollection );
QStringList mimeTypes;
mimeTypes << Collection::mimeType();
if ( !Settings::self()->topLevelIsContainer() )
mimeTypes << "message/rfc822";
root.setContentMimeTypes( mimeTypes );
Collection::List list;
list << root;
list += listRecursive( root, dir );
collectionsRetrieved( list );
}
void MaildirResource::retrieveItems( const Akonadi::Collection & col )
{
const Maildir md = maildirForCollection( col );
if ( !md.isValid() ) {
cancelTask( i18n("Maildir '%1' for collection '%2' is invalid.", md.path(), col.remoteId() ) );
return;
}
const QStringList entryList = md.entryList();
Item::List items;
foreach ( const QString &entry, entryList ) {
Item item;
item.setRemoteId( entry );
item.setMimeType( "message/rfc822" );
item.setSize( md.size( entry ) );
KMime::Message *msg = new KMime::Message;
msg->setHead( KMime::CRLFtoLF( md.readEntryHeaders( entry ) ) );
msg->parse();
item.setPayload( MessagePtr( msg ) );
items << item;
}
itemsRetrieved( items );
}
void MaildirResource::collectionAdded(const Collection & collection, const Collection &parent)
{
Maildir md = maildirForCollection( parent );
kDebug( 5254 ) << md.subFolderList() << md.entryList();
if ( Settings::self()->readOnly() || !md.isValid() ) {
changeProcessed();
return;
}
else {
const QString newFolderPath = md.addSubFolder( collection.name() );
if ( newFolderPath.isEmpty() ) {
changeProcessed();
return;
}
kDebug( 5254 ) << md.subFolderList() << md.entryList();
Collection col = collection;
col.setRemoteId( collection.name() );
changeCommitted( col );
}
}
void MaildirResource::collectionChanged(const Collection & collection)
{
if ( collection.remoteId() == collection.name() ) {
changeProcessed();
return;
}
Maildir md = maildirForCollection( collection );
if ( !md.rename( collection.name() ) ) {
emit error( i18n("Unable to rename maildir folder '%1'.", collection.name() ) );
return;
}
Collection c( collection );
c.setRemoteId( collection.name() );
changeCommitted( c );
}
void MaildirResource::collectionRemoved( const Akonadi::Collection &collection )
{
if ( collection.parentCollection() == Collection::root() ) {
emit error( i18n("Cannot delete top-level maildir folder '%1'.", Settings::self()->path() ) );
changeProcessed();
return;
}
Maildir md = maildirForCollection( collection.parentCollection() );
if ( !md.removeSubFolder( collection.remoteId() ) )
emit error( i18n("Failed to delete sub-folder '%1'.", collection.remoteId() ) );
changeProcessed();
}
void MaildirResource::ensureDirExists()
{
Maildir root( Settings::self()->path() );
if ( !root.isValid() ) {
if ( !root.create() )
emit status( Broken, i18n( "Unable to create maildir '%1'.", Settings::self()->path() ) );
}
}
AKONADI_RESOURCE_MAIN( MaildirResource )
#include "maildirresource.moc"
<commit_msg>Handle renaming of the top-level collection correctly and set proper collection rights.<commit_after>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "maildirresource.h"
#include "settings.h"
#include "settingsadaptor.h"
#include "configdialog.h"
#include <QtCore/QDir>
#include <QtDBus/QDBusConnection>
#include <akonadi/kmime/messageparts.h>
#include <akonadi/changerecorder.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collectionfetchscope.h>
#include <kdebug.h>
#include <kurl.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <KWindowSystem>
#include "libmaildir/maildir.h"
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<KMime::Message> MessagePtr;
using namespace Akonadi;
using KPIM::Maildir;
/** Creates a maildir object for the collection @p col, given it has the full ancestor chain set. */
static Maildir maildirForCollection( const Collection &col )
{
if ( col.remoteId().isEmpty() ) {
kWarning() << "Got incomplete ancestor chain:" << col;
return Maildir();
}
if ( col.parentCollection() == Collection::root() ) {
kWarning( col.remoteId() != Settings::self()->path() ) << "RID mismatch, is " << col.remoteId() << " expected " << Settings::self()->path();
return Maildir( col.remoteId(), Settings::self()->topLevelIsContainer() );
}
Maildir parentMd = maildirForCollection( col.parentCollection() );
return parentMd.subFolder( col.remoteId() );
}
MaildirResource::MaildirResource( const QString &id )
:ResourceBase( id )
{
new SettingsAdaptor( Settings::self() );
QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
Settings::self(), QDBusConnection::ExportAdaptors );
connect( this, SIGNAL(reloadConfiguration()), SLOT(ensureDirExists()) );
// We need to enable this here, otherwise we neither get the remote ID of the
// parent collection when a collection changes, nor the full item when an item
// is added.
changeRecorder()->fetchCollection( true );
changeRecorder()->itemFetchScope().fetchFullPayload( true );
changeRecorder()->itemFetchScope().setAncestorRetrieval( ItemFetchScope::All );
changeRecorder()->collectionFetchScope().setAncestorRetrieval( CollectionFetchScope::All );
}
MaildirResource::~ MaildirResource()
{
}
bool MaildirResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
Q_UNUSED( parts );
const Maildir md = maildirForCollection( item.parentCollection() );
if ( !md.isValid() ) {
cancelTask( i18n( "Unable to fetch item: The maildir folder \"%1\" is not valid.",
md.path() ) );
return false;
}
const QByteArray data = md.readEntry( item.remoteId() );
KMime::Message *mail = new KMime::Message();
mail->setContent( KMime::CRLFtoLF( data ) );
mail->parse();
Item i( item );
i.setPayload( MessagePtr( mail ) );
itemRetrieved( i );
return true;
}
void MaildirResource::aboutToQuit()
{
// The settings may not have been saved if e.g. they have been modified via
// DBus instead of the config dialog.
Settings::self()->writeConfig();
}
void MaildirResource::configure( WId windowId )
{
ConfigDialog dlg;
if ( windowId )
KWindowSystem::setMainWindow( &dlg, windowId );
dlg.exec();
ensureDirExists();
synchronizeCollectionTree();
}
void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection )
{
Maildir dir = maildirForCollection( collection );
QString errMsg;
if ( Settings::readOnly() || !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
cancelTask( i18n("Only email messages can be added to the Maildir resource.") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
const QString rid = dir.addEntry( mail->encodedContent() );
Item i( item );
i.setRemoteId( rid );
changeCommitted( i );
}
void MaildirResource::itemChanged( const Akonadi::Item& item, const QSet<QByteArray>& parts )
{
if ( Settings::self()->readOnly() || !parts.contains( MessagePart::Body ) ) {
changeProcessed();
return;
}
Maildir dir = maildirForCollection( item.parentCollection() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
cancelTask( i18n("Only email messages can be added to the Maildir resource.") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.writeEntry( item.remoteId(), mail->encodedContent() );
changeCommitted( item );
}
void MaildirResource::itemRemoved(const Akonadi::Item & item)
{
if ( !Settings::self()->readOnly() ) {
Maildir dir = maildirForCollection( item.parentCollection() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
cancelTask( errMsg );
return;
}
if ( !dir.removeEntry( item.remoteId() ) ) {
emit error( i18n("Failed to delete item: %1", item.remoteId()) );
}
}
changeProcessed();
}
Collection::List listRecursive( const Collection &root, const Maildir &dir )
{
Collection::List list;
const QStringList mimeTypes = QStringList() << "message/rfc822" << Collection::mimeType();
foreach ( const QString &sub, dir.subFolderList() ) {
Collection c;
c.setName( sub );
c.setRemoteId( sub );
c.setParentCollection( root );
c.setContentMimeTypes( mimeTypes );
const Maildir md = maildirForCollection( c );
if ( !md.isValid() )
continue;
list << c;
list += listRecursive( c, md );
}
return list;
}
void MaildirResource::retrieveCollections()
{
Maildir dir( Settings::self()->path(), Settings::self()->topLevelIsContainer() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
emit error( errMsg );
collectionsRetrieved( Collection::List() );
return;
}
Collection root;
root.setParentCollection( Collection::root() );
root.setRemoteId( Settings::self()->path() );
root.setName( name() );
root.setRights( Collection::CanChangeItem | Collection::CanCreateItem | Collection::CanDeleteItem
| Collection::CanCreateCollection );
QStringList mimeTypes;
mimeTypes << Collection::mimeType();
if ( !Settings::self()->topLevelIsContainer() )
mimeTypes << "message/rfc822";
root.setContentMimeTypes( mimeTypes );
Collection::List list;
list << root;
list += listRecursive( root, dir );
collectionsRetrieved( list );
}
void MaildirResource::retrieveItems( const Akonadi::Collection & col )
{
const Maildir md = maildirForCollection( col );
if ( !md.isValid() ) {
cancelTask( i18n("Maildir '%1' for collection '%2' is invalid.", md.path(), col.remoteId() ) );
return;
}
const QStringList entryList = md.entryList();
Item::List items;
foreach ( const QString &entry, entryList ) {
Item item;
item.setRemoteId( entry );
item.setMimeType( "message/rfc822" );
item.setSize( md.size( entry ) );
KMime::Message *msg = new KMime::Message;
msg->setHead( KMime::CRLFtoLF( md.readEntryHeaders( entry ) ) );
msg->parse();
item.setPayload( MessagePtr( msg ) );
items << item;
}
itemsRetrieved( items );
}
void MaildirResource::collectionAdded(const Collection & collection, const Collection &parent)
{
Maildir md = maildirForCollection( parent );
kDebug( 5254 ) << md.subFolderList() << md.entryList();
if ( Settings::self()->readOnly() || !md.isValid() ) {
changeProcessed();
return;
}
else {
const QString newFolderPath = md.addSubFolder( collection.name() );
if ( newFolderPath.isEmpty() ) {
changeProcessed();
return;
}
kDebug( 5254 ) << md.subFolderList() << md.entryList();
Collection col = collection;
col.setRemoteId( collection.name() );
changeCommitted( col );
}
}
void MaildirResource::collectionChanged(const Collection & collection)
{
if ( collection.parentCollection() == Collection::root() ) {
if ( collection.name() != name() )
setName( collection.name() );
changeProcessed();
return;
}
if ( collection.remoteId() == collection.name() ) {
changeProcessed();
return;
}
Maildir md = maildirForCollection( collection );
if ( !md.rename( collection.name() ) ) {
emit error( i18n("Unable to rename maildir folder '%1'.", collection.name() ) );
return;
}
Collection c( collection );
c.setRemoteId( collection.name() );
changeCommitted( c );
}
void MaildirResource::collectionRemoved( const Akonadi::Collection &collection )
{
if ( collection.parentCollection() == Collection::root() ) {
emit error( i18n("Cannot delete top-level maildir folder '%1'.", Settings::self()->path() ) );
changeProcessed();
return;
}
Maildir md = maildirForCollection( collection.parentCollection() );
if ( !md.removeSubFolder( collection.remoteId() ) )
emit error( i18n("Failed to delete sub-folder '%1'.", collection.remoteId() ) );
changeProcessed();
}
void MaildirResource::ensureDirExists()
{
Maildir root( Settings::self()->path() );
if ( !root.isValid() ) {
if ( !root.create() )
emit status( Broken, i18n( "Unable to create maildir '%1'.", Settings::self()->path() ) );
}
}
AKONADI_RESOURCE_MAIN( MaildirResource )
#include "maildirresource.moc"
<|endoftext|>
|
<commit_before>/*
Title: Multi-Threaded Garbage Collector - Mark phase
Copyright (c) 2010-12 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
This is the first, mark, phase of the garbage collector. It detects all
reachable cells in the area being collected. At the end of the phase the
bit-maps associated with the areas will have ones for words belonging to cells
that must be retained and zeros for words that can be reused.
This is now multi-threaded. The mark phase involves setting a bit in the header
of each live cell and then a pass over the memory building the bitmaps and clearing
this bit. It is unfortunate that we cannot use the GC-bit that is used in
forwarding pointers but we may well have forwarded pointers left over from a
partially completed minor GC. Using a bit in the header avoids the need for
locking since at worst it may involve two threads duplicating some marking.
Marking can potentially recurse as deeply as the data structure. Scanaddrs
uses tail recursion on the last pointer in a cell which works well for lists
but does not deal with trees. This code keeps a recursion count and triggers
a rescan on the range of addresses that could not be fully marked.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "processes.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "bitmap.h"
#include "memmgr.h"
#include "diagnostics.h"
#include "gctaskfarm.h"
#include "profiling.h"
// Recursion limit. This needs to be chosen so that the stack will not
// overflow on any platform.
#define RECURSION_LIMIT 3000
class MTGCProcessMarkPointers: public ScanAddress
{
public:
MTGCProcessMarkPointers(uintptr_t depth = 0): recursion(depth) {}
virtual POLYUNSIGNED ScanAddressAt(PolyWord *pt) { return DoScanAddressAt(pt, false); }
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
virtual PolyObject *ScanObjectAddress(PolyObject *base);
POLYUNSIGNED DoScanAddressAt(PolyWord *pt, bool isWeak);
virtual void ScanAddressesInObject(PolyObject *base, POLYUNSIGNED lengthWord);
// Have to redefine this for some reason.
void ScanAddressesInObject(PolyObject *base) { ScanAddressesInObject(base, base->LengthWord()); }
public:
static void MarkPermanentMutableAreaTask(GCTaskId *, void *arg1, void *);
static void MarkPointersTask(GCTaskId *, void *arg1, void *arg2);
private:
uintptr_t recursion;
};
// Task to mark pointers in a permanent mutable area.
void MTGCProcessMarkPointers::MarkPermanentMutableAreaTask(GCTaskId *, void *arg1, void *)
{
MemSpace *space = (MemSpace *)arg1;
MTGCProcessMarkPointers marker;
marker.ScanAddressesInRegion(space->bottom, space->top);
}
// Task to mark pointers.
void MTGCProcessMarkPointers::MarkPointersTask(GCTaskId *, void *arg1, void *arg2)
{
PolyObject *obj = (PolyObject *)arg1;
// This may be a new task or it may be called recursively from
// DoScanAddressAt. For safety assume that it's recursive.
uintptr_t depth = (uintptr_t)arg2;
MTGCProcessMarkPointers marker(depth+1);
marker.ScanAddressesInObject(obj);
}
// Mark all pointers in the heap.
POLYUNSIGNED MTGCProcessMarkPointers::DoScanAddressAt(PolyWord *pt, bool isWeak)
{
if ((*pt).IsTagged())
return 0;
LocalMemSpace *space = gMem.LocalSpaceForAddress((*pt).AsAddress());
if (space == 0)
return 0; // Ignore it if it points to a permanent area
// This could contain a forwarding pointer if it points into an
// allocation area and has been moved by the minor GC.
PolyObject *obj = (*pt).AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
space = gMem.LocalSpaceForAddress((*pt).AsAddress());
obj = (*pt).AsObjPtr();
}
// We shouldn't get code addresses since we handle stacks and code
// segments separately so if this isn't an integer it must be an object address.
POLYUNSIGNED L = obj->LengthWord();
if (L & _OBJ_GC_MARK)
return 0; // Already marked
obj->SetLengthWord(L | _OBJ_GC_MARK); // Mark it
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
ASSERT(obj+n <= (PolyObject*)space->top); // Check the length is sensible
if (debugOptions & DEBUG_GC_DETAIL)
Log("GC: Mark: %p %" POLYUFMT " %u\n", obj, n, GetTypeBits(L));
if (isWeak) // This is a SOME within a weak reference.
return 0;
if (OBJ_IS_BYTE_OBJECT(L))
return 0; // We've done as much as we need
else if (OBJ_IS_CODE_OBJECT(L) || OBJ_IS_WEAKREF_OBJECT(L))
{
// Have to handle these specially.
gpTaskFarm->AddWorkOrRunNow(&MarkPointersTask, obj, (void*)recursion);
return 0; // Already done it.
}
else
return L | _OBJ_GC_MARK;
}
// The initial entry to process the roots. Also used when processing the addresses
// in objects that can't be handled by ScanAddressAt.
PolyObject *MTGCProcessMarkPointers::ScanObjectAddress(PolyObject *obj)
{
PolyWord val = obj;
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsAddress());
if (space == 0)
return obj; // Ignore it if it points to a permanent area
// We may have a forwarding pointer if this has been moved by the
// minor GC.
if (obj->ContainsForwardingPtr())
{
obj = obj->GetForwardingPtr();
val = obj;
space = gMem.LocalSpaceForAddress(val.AsAddress());
}
ASSERT(obj->ContainsNormalLengthWord());
CheckObject (obj);
POLYUNSIGNED L = obj->LengthWord();
if (L & _TOP_BYTE(0x04))
return obj; // Already marked
obj->SetLengthWord(L | _TOP_BYTE(0x04)); // Mark it
if (profileMode == kProfileLiveData || (profileMode == kProfileLiveMutables && obj->IsMutable()))
AddObjectProfile(obj);
if ((PolyWord*)obj <= space->fullGCLowerLimit)
space->fullGCLowerLimit = (PolyWord*)obj-1;
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (debugOptions & DEBUG_GC_DETAIL)
Log("GC: Mark: %p %" POLYUFMT " %u\n", obj, n, GetTypeBits(L));
// Process the addresses in this object. We could short-circuit things
// for word objects by calling ScanAddressesAt directly.
ScanAddressesInObject(obj);
return obj;
}
// These functions are only called with pointers held by the runtime system.
// Weak references can occur in the runtime system, eg. streams and windows.
// Weak references are not marked and so unreferenced streams and windows
// can be detected and closed.
void MTGCProcessMarkPointers::ScanRuntimeAddress(PolyObject **pt, RtsStrength weak)
{
PolyObject *val = *pt;
CheckPointer (val);
if (weak == STRENGTH_WEAK) return;
*pt = ScanObjectAddress(*pt);
}
// This is called both for objects in the local heap and also for mutables
// in the permanent area and, for partial GCs, for mutables in other areas.
void MTGCProcessMarkPointers::ScanAddressesInObject(PolyObject *base, POLYUNSIGNED L)
{
if (recursion >= RECURSION_LIMIT)
{
LocalMemSpace *space = gMem.LocalSpaceForAddress(base);
ASSERT(space != 0);
PLocker lock(&space->spaceLock);
// Have to include this in the range to rescan.
if (space->fullGCRescanStart > ((PolyWord*)base) - 1)
space->fullGCRescanStart = ((PolyWord*)base) - 1;
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (space->fullGCRescanEnd < ((PolyWord*)base) + n)
space->fullGCRescanEnd = ((PolyWord*)base) + n;
ASSERT(base->LengthWord() & _OBJ_GC_MARK); // Should have been marked.
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Recursion limit reached. Rescan for %p\n", base);
return;
}
recursion ++;
if (OBJ_IS_WEAKREF_OBJECT(L))
{
ASSERT(OBJ_IS_MUTABLE_OBJECT(L)); // Should be a mutable.
ASSERT(OBJ_IS_WORD_OBJECT(L)); // Should be a plain object.
// We need to mark the "SOME" values in this object but we don't mark
// the references contained within the "SOME".
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
PolyWord *baseAddr = (PolyWord*)base;
for (POLYUNSIGNED i = 0; i < n; i++)
DoScanAddressAt(baseAddr+i, true);
// Add this to the limits for the containing area.
MemSpace *space = gMem.SpaceForAddress(baseAddr);
PolyWord *startAddr = baseAddr-1; // Must point AT length word.
PolyWord *endObject = baseAddr + n;
if (startAddr < space->lowestWeak) space->lowestWeak = startAddr;
if (endObject > space->highestWeak) space->highestWeak = endObject;
}
else ScanAddress::ScanAddressesInObject(base, L);
recursion--;
}
static void SetBitmaps(LocalMemSpace *space, PolyWord *pt, PolyWord *top)
{
while (pt < top)
{
PolyObject *obj = (PolyObject*)++pt;
// If it has been copied by a minor collection skip it
if (obj->ContainsForwardingPtr())
pt += obj->GetForwardingPtr()->Length();
else
{
POLYUNSIGNED L = obj->LengthWord();
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (L & _OBJ_GC_MARK)
{
obj->SetLengthWord(L & ~(_OBJ_GC_MARK));
POLYUNSIGNED bitno = space->wordNo(pt);
space->bitmap.SetBits(bitno - 1, n + 1);
if (OBJ_IS_MUTABLE_OBJECT(L))
space->m_marked += n + 1;
else
space->i_marked += n + 1;
if ((PolyWord*)obj <= space->fullGCLowerLimit)
space->fullGCLowerLimit = (PolyWord*)obj-1;
}
pt += n;
}
}
}
static void CreateBitmapsTask(GCTaskId *, void *arg1, void *arg2)
{
LocalMemSpace *lSpace = (LocalMemSpace *)arg1;
lSpace->bitmap.ClearBits(0, lSpace->spaceSize());
SetBitmaps(lSpace, lSpace->bottom, lSpace->top);
}
class RescanMarked: public MTGCProcessMarkPointers
{
private:
virtual void ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord);
};
// Called to rescan objects that have already been marked
// before but are within the range of those that were
// skipped because of the recursion limit. We process them
// again in case there are unmarked addresses in them.
void RescanMarked::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)
{
if (lengthWord &_OBJ_GC_MARK)
MTGCProcessMarkPointers::ScanAddressesInObject(obj, lengthWord);
}
void GCMarkPhase(void)
{
mainThreadPhase = MTP_GCPHASEMARK;
// Clear the mark counters and set the rescan limits.
for(unsigned k = 0; k < gMem.nlSpaces; k++)
{
LocalMemSpace *lSpace = gMem.lSpaces[k];
lSpace->i_marked = lSpace->m_marked = 0;
lSpace->fullGCRescanStart = lSpace->top;
lSpace->fullGCRescanEnd = lSpace->bottom;
}
// Do the actual marking
// Scan the permanent mutable areas.
for (unsigned j = 0; j < gMem.npSpaces; j++)
{
PermanentMemSpace *space = gMem.pSpaces[j];
if (space->isMutable && ! space->byteOnly)
gpTaskFarm->AddWorkOrRunNow(&MTGCProcessMarkPointers::MarkPermanentMutableAreaTask, space, 0);
}
MTGCProcessMarkPointers marker;
GCModules(&marker);
gpTaskFarm->WaitForCompletion();
// Do we have to recan?
while (true)
{
bool rescan = false;
RescanMarked rescanner;
for (unsigned m = 0; m < gMem.nlSpaces; m++)
{
LocalMemSpace *lSpace = gMem.lSpaces[m];
if (lSpace->fullGCRescanStart < lSpace->fullGCRescanEnd)
{
PolyWord *start = lSpace->fullGCRescanStart;
PolyWord *end = lSpace->fullGCRescanEnd;
lSpace->fullGCRescanStart = lSpace->top;
lSpace->fullGCRescanEnd = lSpace->bottom;
rescan = true;
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Rescanning from %p to %p\n", start, end);
rescanner.ScanAddressesInRegion(start, end);
}
}
if (! rescan)
break;
}
// Turn the marks into bitmap entries.
for (unsigned i = 0; i < gMem.nlSpaces; i++)
gpTaskFarm->AddWorkOrRunNow(&CreateBitmapsTask, gMem.lSpaces[i], 0);
gpTaskFarm->WaitForCompletion();
POLYUNSIGNED totalLive = 0;
for(unsigned l = 0; l < gMem.nlSpaces; l++)
{
LocalMemSpace *lSpace = gMem.lSpaces[l];
if (! lSpace->isMutable) ASSERT(lSpace->m_marked == 0);
totalLive += lSpace->m_marked + lSpace->i_marked;
if (debugOptions & DEBUG_GC)
Log("GC: Mark: %s space %p: %" POLYUFMT " immutable words marked, %" POLYUFMT " mutable words marked\n",
lSpace->spaceTypeString(), lSpace,
lSpace->i_marked, lSpace->m_marked);
}
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Total live data %" POLYUFMT " words\n", totalLive);
}
<commit_msg>Reduce the marker recursion limit slightly to avoid crashes when debugging in Linux.<commit_after>/*
Title: Multi-Threaded Garbage Collector - Mark phase
Copyright (c) 2010-12 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
This is the first, mark, phase of the garbage collector. It detects all
reachable cells in the area being collected. At the end of the phase the
bit-maps associated with the areas will have ones for words belonging to cells
that must be retained and zeros for words that can be reused.
This is now multi-threaded. The mark phase involves setting a bit in the header
of each live cell and then a pass over the memory building the bitmaps and clearing
this bit. It is unfortunate that we cannot use the GC-bit that is used in
forwarding pointers but we may well have forwarded pointers left over from a
partially completed minor GC. Using a bit in the header avoids the need for
locking since at worst it may involve two threads duplicating some marking.
Marking can potentially recurse as deeply as the data structure. Scanaddrs
uses tail recursion on the last pointer in a cell which works well for lists
but does not deal with trees. This code keeps a recursion count and triggers
a rescan on the range of addresses that could not be fully marked.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "processes.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "bitmap.h"
#include "memmgr.h"
#include "diagnostics.h"
#include "gctaskfarm.h"
#include "profiling.h"
#include "timing.h"
// Recursion limit. This needs to be chosen so that the stack will not
// overflow on any platform.
#define RECURSION_LIMIT 2500
class MTGCProcessMarkPointers: public ScanAddress
{
public:
MTGCProcessMarkPointers(): recursion(0) {}
virtual POLYUNSIGNED ScanAddressAt(PolyWord *pt) { return DoScanAddressAt(pt, false); }
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
virtual PolyObject *ScanObjectAddress(PolyObject *base);
POLYUNSIGNED DoScanAddressAt(PolyWord *pt, bool isWeak);
virtual void ScanAddressesInObject(PolyObject *base, POLYUNSIGNED lengthWord);
// Have to redefine this for some reason.
void ScanAddressesInObject(PolyObject *base) { ScanAddressesInObject(base, base->LengthWord()); }
public:
static void MarkPermanentMutableAreaTask(GCTaskId *, void *arg1, void *);
static void MarkPointersTask(GCTaskId *, void *arg1, void *arg2);
private:
unsigned recursion;
};
// Task to mark pointers in a permanent mutable area.
void MTGCProcessMarkPointers::MarkPermanentMutableAreaTask(GCTaskId *, void *arg1, void *)
{
MemSpace *space = (MemSpace *)arg1;
MTGCProcessMarkPointers marker;
marker.ScanAddressesInRegion(space->bottom, space->top);
}
// Task to mark pointers.
void MTGCProcessMarkPointers::MarkPointersTask(GCTaskId *, void *arg1, void *arg2)
{
PolyObject *obj = (PolyObject *)arg1;
MTGCProcessMarkPointers marker;
marker.ScanAddressesInObject(obj);
}
// Mark all pointers in the heap.
POLYUNSIGNED MTGCProcessMarkPointers::DoScanAddressAt(PolyWord *pt, bool isWeak)
{
if ((*pt).IsTagged())
return 0;
LocalMemSpace *space = gMem.LocalSpaceForAddress((*pt).AsAddress());
if (space == 0)
return 0; // Ignore it if it points to a permanent area
// This could contain a forwarding pointer if it points into an
// allocation area and has been moved by the minor GC.
PolyObject *obj = (*pt).AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
space = gMem.LocalSpaceForAddress((*pt).AsAddress());
obj = (*pt).AsObjPtr();
}
// We shouldn't get code addresses since we handle stacks and code
// segments separately so if this isn't an integer it must be an object address.
POLYUNSIGNED L = obj->LengthWord();
if (L & _OBJ_GC_MARK)
return 0; // Already marked
obj->SetLengthWord(L | _OBJ_GC_MARK); // Mark it
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
ASSERT(obj+n <= (PolyObject*)space->top); // Check the length is sensible
if (debugOptions & DEBUG_GC_DETAIL)
Log("GC: Mark: %p %" POLYUFMT " %u\n", obj, n, GetTypeBits(L));
if (isWeak) // This is a SOME within a weak reference.
return 0;
if (OBJ_IS_BYTE_OBJECT(L))
return 0; // We've done as much as we need
else if (OBJ_IS_CODE_OBJECT(L) || OBJ_IS_WEAKREF_OBJECT(L))
{
// Have to handle these specially. If we can't add it to
// the task queue process it recursively using the current
// recursion count.
if (! gpTaskFarm->AddWork(&MarkPointersTask, obj, 0))
ScanAddressesInObject(obj);
return 0; // Already done it.
}
else
return L | _OBJ_GC_MARK;
}
// The initial entry to process the roots. Also used when processing the addresses
// in objects that can't be handled by ScanAddressAt.
PolyObject *MTGCProcessMarkPointers::ScanObjectAddress(PolyObject *obj)
{
PolyWord val = obj;
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsAddress());
if (space == 0)
return obj; // Ignore it if it points to a permanent area
// We may have a forwarding pointer if this has been moved by the
// minor GC.
if (obj->ContainsForwardingPtr())
{
obj = obj->GetForwardingPtr();
val = obj;
space = gMem.LocalSpaceForAddress(val.AsAddress());
}
ASSERT(obj->ContainsNormalLengthWord());
CheckObject (obj);
POLYUNSIGNED L = obj->LengthWord();
if (L & _TOP_BYTE(0x04))
return obj; // Already marked
obj->SetLengthWord(L | _TOP_BYTE(0x04)); // Mark it
if (profileMode == kProfileLiveData || (profileMode == kProfileLiveMutables && obj->IsMutable()))
AddObjectProfile(obj);
if ((PolyWord*)obj <= space->fullGCLowerLimit)
space->fullGCLowerLimit = (PolyWord*)obj-1;
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (debugOptions & DEBUG_GC_DETAIL)
Log("GC: Mark: %p %" POLYUFMT " %u\n", obj, n, GetTypeBits(L));
// Process the addresses in this object. We could short-circuit things
// for word objects by calling ScanAddressesAt directly.
ScanAddressesInObject(obj);
return obj;
}
// These functions are only called with pointers held by the runtime system.
// Weak references can occur in the runtime system, eg. streams and windows.
// Weak references are not marked and so unreferenced streams and windows
// can be detected and closed.
void MTGCProcessMarkPointers::ScanRuntimeAddress(PolyObject **pt, RtsStrength weak)
{
PolyObject *val = *pt;
CheckPointer (val);
if (weak == STRENGTH_WEAK) return;
*pt = ScanObjectAddress(*pt);
}
// This is called both for objects in the local heap and also for mutables
// in the permanent area and, for partial GCs, for mutables in other areas.
void MTGCProcessMarkPointers::ScanAddressesInObject(PolyObject *base, POLYUNSIGNED L)
{
if (recursion >= RECURSION_LIMIT)
{
LocalMemSpace *space = gMem.LocalSpaceForAddress(base);
ASSERT(space != 0);
PLocker lock(&space->spaceLock);
// Have to include this in the range to rescan.
if (space->fullGCRescanStart > ((PolyWord*)base) - 1)
space->fullGCRescanStart = ((PolyWord*)base) - 1;
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (space->fullGCRescanEnd < ((PolyWord*)base) + n)
space->fullGCRescanEnd = ((PolyWord*)base) + n;
ASSERT(base->LengthWord() & _OBJ_GC_MARK); // Should have been marked.
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Recursion limit reached. Rescan for %p\n", base);
return;
}
recursion ++;
if (OBJ_IS_WEAKREF_OBJECT(L))
{
ASSERT(OBJ_IS_MUTABLE_OBJECT(L)); // Should be a mutable.
ASSERT(OBJ_IS_WORD_OBJECT(L)); // Should be a plain object.
// We need to mark the "SOME" values in this object but we don't mark
// the references contained within the "SOME".
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
PolyWord *baseAddr = (PolyWord*)base;
for (POLYUNSIGNED i = 0; i < n; i++)
DoScanAddressAt(baseAddr+i, true);
// Add this to the limits for the containing area.
MemSpace *space = gMem.SpaceForAddress(baseAddr);
PolyWord *startAddr = baseAddr-1; // Must point AT length word.
PolyWord *endObject = baseAddr + n;
if (startAddr < space->lowestWeak) space->lowestWeak = startAddr;
if (endObject > space->highestWeak) space->highestWeak = endObject;
}
else ScanAddress::ScanAddressesInObject(base, L);
recursion--;
}
static void SetBitmaps(LocalMemSpace *space, PolyWord *pt, PolyWord *top)
{
while (pt < top)
{
PolyObject *obj = (PolyObject*)++pt;
// If it has been copied by a minor collection skip it
if (obj->ContainsForwardingPtr())
pt += obj->GetForwardingPtr()->Length();
else
{
POLYUNSIGNED L = obj->LengthWord();
POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L);
if (L & _OBJ_GC_MARK)
{
obj->SetLengthWord(L & ~(_OBJ_GC_MARK));
POLYUNSIGNED bitno = space->wordNo(pt);
space->bitmap.SetBits(bitno - 1, n + 1);
if (OBJ_IS_MUTABLE_OBJECT(L))
space->m_marked += n + 1;
else
space->i_marked += n + 1;
if ((PolyWord*)obj <= space->fullGCLowerLimit)
space->fullGCLowerLimit = (PolyWord*)obj-1;
}
pt += n;
}
}
}
static void CreateBitmapsTask(GCTaskId *, void *arg1, void *arg2)
{
LocalMemSpace *lSpace = (LocalMemSpace *)arg1;
lSpace->bitmap.ClearBits(0, lSpace->spaceSize());
SetBitmaps(lSpace, lSpace->bottom, lSpace->top);
}
class RescanMarked: public MTGCProcessMarkPointers
{
private:
virtual void ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord);
};
// Called to rescan objects that have already been marked
// before but are within the range of those that were
// skipped because of the recursion limit. We process them
// again in case there are unmarked addresses in them.
void RescanMarked::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)
{
if (lengthWord &_OBJ_GC_MARK)
MTGCProcessMarkPointers::ScanAddressesInObject(obj, lengthWord);
}
void GCMarkPhase(void)
{
mainThreadPhase = MTP_GCPHASEMARK;
// Clear the mark counters and set the rescan limits.
for(unsigned k = 0; k < gMem.nlSpaces; k++)
{
LocalMemSpace *lSpace = gMem.lSpaces[k];
lSpace->i_marked = lSpace->m_marked = 0;
lSpace->fullGCRescanStart = lSpace->top;
lSpace->fullGCRescanEnd = lSpace->bottom;
}
// Do the actual marking
// Scan the permanent mutable areas.
for (unsigned j = 0; j < gMem.npSpaces; j++)
{
PermanentMemSpace *space = gMem.pSpaces[j];
if (space->isMutable && ! space->byteOnly)
gpTaskFarm->AddWorkOrRunNow(&MTGCProcessMarkPointers::MarkPermanentMutableAreaTask, space, 0);
}
MTGCProcessMarkPointers marker;
GCModules(&marker);
gpTaskFarm->WaitForCompletion();
// Do we have to recan?
while (true)
{
bool rescan = false;
RescanMarked rescanner;
for (unsigned m = 0; m < gMem.nlSpaces; m++)
{
LocalMemSpace *lSpace = gMem.lSpaces[m];
if (lSpace->fullGCRescanStart < lSpace->fullGCRescanEnd)
{
PolyWord *start = lSpace->fullGCRescanStart;
PolyWord *end = lSpace->fullGCRescanEnd;
lSpace->fullGCRescanStart = lSpace->top;
lSpace->fullGCRescanEnd = lSpace->bottom;
rescan = true;
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Rescanning from %p to %p\n", start, end);
rescanner.ScanAddressesInRegion(start, end);
}
}
if (! rescan)
break;
}
gcTimeData.RecordGCTime(GcTimeData::GCTimeIntermediate, "Mark");
// Turn the marks into bitmap entries.
for (unsigned i = 0; i < gMem.nlSpaces; i++)
gpTaskFarm->AddWorkOrRunNow(&CreateBitmapsTask, gMem.lSpaces[i], 0);
gpTaskFarm->WaitForCompletion();
gcTimeData.RecordGCTime(GcTimeData::GCTimeIntermediate, "Bitmap");
POLYUNSIGNED totalLive = 0;
for(unsigned l = 0; l < gMem.nlSpaces; l++)
{
LocalMemSpace *lSpace = gMem.lSpaces[l];
if (! lSpace->isMutable) ASSERT(lSpace->m_marked == 0);
totalLive += lSpace->m_marked + lSpace->i_marked;
if (debugOptions & DEBUG_GC)
Log("GC: Mark: %s space %p: %" POLYUFMT " immutable words marked, %" POLYUFMT " mutable words marked\n",
lSpace->spaceTypeString(), lSpace,
lSpace->i_marked, lSpace->m_marked);
}
if (debugOptions & DEBUG_GC)
Log("GC: Mark: Total live data %" POLYUFMT " words\n", totalLive);
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "strategy.h"
#include "consistenthash.h"
#include "util.h"
#include <cinttypes>
#include <string>
#include <algorithm>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include <cstring>
#include <sys/stat.h>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include "tscore/HashSip.h"
#include "tscore/ConsistentHash.h"
#include "tscore/ink_assert.h"
#include "ts/ts.h"
#include "ts/remap.h"
#include "ts/parentselectdefs.h"
#include "consistenthash_config.h"
void loadConfigFile(const std::string &fileName, std::stringstream &doc, std::unordered_set<std::string> &include_once);
// createStrategy creates and initializes a Consistent Hash strategy from the given YAML node.
// Caller takes ownership of the returned pointer, and must call delete on it.
TSNextHopSelectionStrategy *
createStrategy(const std::string &name, const YAML::Node &node)
{
TSDebug(PLUGIN_NAME, "createStrategy %s calling.", name.c_str());
PLNextHopConsistentHash *st = new PLNextHopConsistentHash(name);
TSDebug(PLUGIN_NAME, "createStrategy %s newed %p.", name.c_str(), (void *)st);
if (!st->Init(node)) {
TSDebug(PLUGIN_NAME, "createStrategy %s init failed, returning nullptr.", name.c_str());
return nullptr;
}
TSDebug(PLUGIN_NAME, "createStrategy %s init succeeded, returning obj.", name.c_str());
return st;
}
// Caller takes ownership of the returned pointers in the map, and must call delete on them.
// TODO change to only call createStrategy for the one we need, for efficiency.
strategies_map
createStrategiesFromFile(const char *file)
{
TSDebug(PLUGIN_NAME, "createStrategiesFromFile plugin createStrategiesFromFile file '%s'", file);
// return strategies_map(); // debug
YAML::Node config;
YAML::Node strategies;
std::stringstream doc;
std::unordered_set<std::string> include_once;
std::string_view fn = file;
// strategy policy
constexpr std::string_view consistent_hash = "consistent_hash";
const char *basename = fn.substr(fn.find_last_of('/') + 1).data();
try {
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s loading ...", basename);
loadConfigFile(fn.data(), doc, include_once);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s loaded.", basename);
config = YAML::Load(doc);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s yaml loaded.", basename);
if (config.IsNull()) {
TSDebug(PLUGIN_NAME, "createStrategiesFromFile No NextHop strategy configs were loaded.");
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s checked null.", basename);
strategies = config["strategies"];
if (strategies.Type() != YAML::NodeType::Sequence) {
TSError("[%s] malformed %s file, expected a 'strategies' sequence", PLUGIN_NAME, basename);
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s checked strategies member.", basename);
// std::map<std::string, TSNextHopSelectionStrategy*, std::less<>>
strategies_map strategiesMap;
for (auto &&strategy : strategies) {
auto name = strategy["strategy"].as<std::string>();
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s.", basename, name.c_str());
auto policy = strategy["policy"];
if (!policy) {
TSError("[%s] no policy is defined for the strategy named '%s'.", PLUGIN_NAME, name.c_str());
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s checked policy.", basename, name.c_str());
const auto &policy_value = policy.Scalar();
if (policy_value != consistent_hash) {
TSError("[%s] strategy named '%s' has unsupported policy '%s'.", PLUGIN_NAME, name.c_str(), policy_value.c_str());
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s creating strategy.", basename, name.c_str());
TSNextHopSelectionStrategy *tsStrategy = createStrategy(name, strategy);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s created strategy.", basename, name.c_str());
if (tsStrategy == nullptr) {
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s checked strategy null.", basename, name.c_str());
strategiesMap.emplace(name, std::unique_ptr<TSNextHopSelectionStrategy>(tsStrategy));
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s emplaced.", basename, name.c_str());
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s returning strategies created.", basename);
return strategiesMap;
} catch (std::exception &ex) {
TSError("[%s] creating strategies from file %s threw '%s'.", PLUGIN_NAME, file, ex.what());
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s returning error.", basename);
return strategies_map();
}
/*
* loads the contents of a file into a std::stringstream document. If the file has a '#include file'
* directive, that 'file' is read into the document beginning at the the point where the
* '#include' was found. This allows the 'strategy' and 'hosts' yaml files to be separate. The
* 'strategy' yaml file would then normally have the '#include hosts.yml' in it's beginning.
*/
void
loadConfigFile(const std::string &fileName, std::stringstream &doc, std::unordered_set<std::string> &include_once)
{
const char *sep = " \t";
char *tok, *last;
struct stat buf;
std::string line;
if (stat(fileName.c_str(), &buf) == -1) {
std::string err_msg = strerror(errno);
throw std::invalid_argument("Unable to stat '" + fileName + "': " + err_msg);
}
// if fileName is a directory, concatenate all '.yaml' files alphanumerically
// into a single document stream. No #include is supported.
if (S_ISDIR(buf.st_mode)) {
DIR *dir = nullptr;
struct dirent *dir_ent = nullptr;
std::vector<std::string_view> files;
TSDebug(PLUGIN_NAME, "loading strategy YAML files from the directory %s", fileName.c_str());
if ((dir = opendir(fileName.c_str())) == nullptr) {
std::string err_msg = strerror(errno);
throw std::invalid_argument("Unable to open the directory '" + fileName + "': " + err_msg);
} else {
while ((dir_ent = readdir(dir)) != nullptr) {
// filename should be greater that 6 characters to have a '.yaml' suffix.
if (strlen(dir_ent->d_name) < 6) {
continue;
}
std::string_view sv = dir_ent->d_name;
if (sv.find(".yaml", sv.size() - 5) == sv.size() - 5) {
files.push_back(sv);
}
}
// sort the files alphanumerically
std::sort(files.begin(), files.end(),
[](const std::string_view lhs, const std::string_view rhs) { return lhs.compare(rhs) < 0; });
for (auto &f : files) {
std::ifstream file(fileName + "/" + f.data());
if (file.is_open()) {
while (std::getline(file, line)) {
if (line[0] == '#') {
// continue;
}
doc << line << "\n";
}
file.close();
} else {
throw std::invalid_argument("Unable to open and read '" + fileName + "/" + f.data() + "'");
}
}
}
} else {
std::ifstream file(fileName);
if (file.is_open()) {
while (std::getline(file, line)) {
if (line[0] == '#') {
tok = strtok_r(const_cast<char *>(line.c_str()), sep, &last);
if (tok != nullptr && strcmp(tok, "#include") == 0) {
std::string f = strtok_r(nullptr, sep, &last);
if (include_once.find(f) == include_once.end()) {
include_once.insert(f);
// try to load included file.
try {
loadConfigFile(f, doc, include_once);
} catch (std::exception &ex) {
throw std::invalid_argument("Unable to open included file '" + f + "' from '" + fileName + "'");
}
}
}
} else {
doc << line << "\n";
}
}
file.close();
} else {
throw std::invalid_argument("Unable to open and read '" + fileName + "'");
}
}
}
<commit_msg>Port #6816 from core strategy to plugin (#8570)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "strategy.h"
#include "consistenthash.h"
#include "util.h"
#include <cinttypes>
#include <string>
#include <algorithm>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include <cstring>
#include <sys/stat.h>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include "tscore/HashSip.h"
#include "tscore/ConsistentHash.h"
#include "tscore/ink_assert.h"
#include "ts/ts.h"
#include "ts/remap.h"
#include "ts/parentselectdefs.h"
#include "consistenthash_config.h"
void loadConfigFile(const std::string &fileName, std::stringstream &doc, std::unordered_set<std::string> &include_once);
// createStrategy creates and initializes a Consistent Hash strategy from the given YAML node.
// Caller takes ownership of the returned pointer, and must call delete on it.
TSNextHopSelectionStrategy *
createStrategy(const std::string &name, const YAML::Node &node)
{
TSDebug(PLUGIN_NAME, "createStrategy %s calling.", name.c_str());
PLNextHopConsistentHash *st = new PLNextHopConsistentHash(name);
TSDebug(PLUGIN_NAME, "createStrategy %s newed %p.", name.c_str(), (void *)st);
if (!st->Init(node)) {
TSDebug(PLUGIN_NAME, "createStrategy %s init failed, returning nullptr.", name.c_str());
return nullptr;
}
TSDebug(PLUGIN_NAME, "createStrategy %s init succeeded, returning obj.", name.c_str());
return st;
}
// Caller takes ownership of the returned pointers in the map, and must call delete on them.
// TODO change to only call createStrategy for the one we need, for efficiency.
strategies_map
createStrategiesFromFile(const char *file)
{
TSDebug(PLUGIN_NAME, "createStrategiesFromFile plugin createStrategiesFromFile file '%s'", file);
// return strategies_map(); // debug
YAML::Node config;
YAML::Node strategies;
std::stringstream doc;
std::unordered_set<std::string> include_once;
std::string_view fn = file;
// strategy policy
constexpr std::string_view consistent_hash = "consistent_hash";
const char *basename = fn.substr(fn.find_last_of('/') + 1).data();
try {
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s loading ...", basename);
loadConfigFile(fn.data(), doc, include_once);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s loaded.", basename);
config = YAML::Load(doc);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s yaml loaded.", basename);
if (config.IsNull()) {
TSDebug(PLUGIN_NAME, "createStrategiesFromFile No NextHop strategy configs were loaded.");
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s checked null.", basename);
strategies = config["strategies"];
if (strategies.Type() != YAML::NodeType::Sequence) {
TSError("[%s] malformed %s file, expected a 'strategies' sequence", PLUGIN_NAME, basename);
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s checked strategies member.", basename);
// std::map<std::string, TSNextHopSelectionStrategy*, std::less<>>
strategies_map strategiesMap;
for (auto &&strategy : strategies) {
auto name = strategy["strategy"].as<std::string>();
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s.", basename, name.c_str());
auto policy = strategy["policy"];
if (!policy) {
TSError("[%s] no policy is defined for the strategy named '%s'.", PLUGIN_NAME, name.c_str());
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s checked policy.", basename, name.c_str());
const auto &policy_value = policy.Scalar();
if (policy_value != consistent_hash) {
TSError("[%s] strategy named '%s' has unsupported policy '%s'.", PLUGIN_NAME, name.c_str(), policy_value.c_str());
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s creating strategy.", basename, name.c_str());
TSNextHopSelectionStrategy *tsStrategy = createStrategy(name, strategy);
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s created strategy.", basename, name.c_str());
if (tsStrategy == nullptr) {
return strategies_map();
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s checked strategy null.", basename, name.c_str());
strategiesMap.emplace(name, std::unique_ptr<TSNextHopSelectionStrategy>(tsStrategy));
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s got strategy %s emplaced.", basename, name.c_str());
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s returning strategies created.", basename);
return strategiesMap;
} catch (std::exception &ex) {
TSError("[%s] creating strategies from file %s threw '%s'.", PLUGIN_NAME, file, ex.what());
}
TSDebug(PLUGIN_NAME, "createStrategiesFromFile filename %s returning error.", basename);
return strategies_map();
}
/*
* loads the contents of a file into a std::stringstream document. If the file has a '#include file'
* directive, that 'file' is read into the document beginning at the the point where the
* '#include' was found. This allows the 'strategy' and 'hosts' yaml files to be separate. The
* 'strategy' yaml file would then normally have the '#include hosts.yml' in it's beginning.
*/
void
loadConfigFile(const std::string &fileName, std::stringstream &doc, std::unordered_set<std::string> &include_once)
{
const char *sep = " \t";
char *tok, *last;
struct stat buf;
std::string line;
if (stat(fileName.c_str(), &buf) == -1) {
std::string err_msg = strerror(errno);
throw std::invalid_argument("Unable to stat '" + fileName + "': " + err_msg);
}
// if fileName is a directory, concatenate all '.yaml' files alphanumerically
// into a single document stream. No #include is supported.
if (S_ISDIR(buf.st_mode)) {
DIR *dir = nullptr;
struct dirent *dir_ent = nullptr;
std::vector<std::string_view> files;
TSDebug(PLUGIN_NAME, "loading strategy YAML files from the directory %s", fileName.c_str());
if ((dir = opendir(fileName.c_str())) == nullptr) {
std::string err_msg = strerror(errno);
throw std::invalid_argument("Unable to open the directory '" + fileName + "': " + err_msg);
} else {
while ((dir_ent = readdir(dir)) != nullptr) {
// filename should be greater that 6 characters to have a '.yaml' suffix.
if (strlen(dir_ent->d_name) < 6) {
continue;
}
std::string_view sv = dir_ent->d_name;
if (sv.find(".yaml", sv.size() - 5) == sv.size() - 5) {
files.push_back(sv);
}
}
// sort the files alphanumerically
std::sort(files.begin(), files.end(),
[](const std::string_view lhs, const std::string_view rhs) { return lhs.compare(rhs) < 0; });
for (auto &f : files) {
std::ifstream file(fileName + "/" + f.data());
if (file.is_open()) {
while (std::getline(file, line)) {
if (line[0] == '#') {
// continue;
}
doc << line << "\n";
}
file.close();
} else {
throw std::invalid_argument("Unable to open and read '" + fileName + "/" + f.data() + "'");
}
}
}
closedir(dir);
} else {
std::ifstream file(fileName);
if (file.is_open()) {
while (std::getline(file, line)) {
if (line[0] == '#') {
tok = strtok_r(const_cast<char *>(line.c_str()), sep, &last);
if (tok != nullptr && strcmp(tok, "#include") == 0) {
std::string f = strtok_r(nullptr, sep, &last);
if (include_once.find(f) == include_once.end()) {
include_once.insert(f);
// try to load included file.
try {
loadConfigFile(f, doc, include_once);
} catch (std::exception &ex) {
throw std::invalid_argument("Unable to open included file '" + f + "' from '" + fileName + "'");
}
}
}
} else {
doc << line << "\n";
}
}
file.close();
} else {
throw std::invalid_argument("Unable to open and read '" + fileName + "'");
}
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
#include "stdafx.h"
// Test the functions and objects in Connector/SynchronousCalls.cpp
#ifdef _M_CEE
#ifdef _UNICODE
#define GetMessage GetMessageW
#else
#define GetMessage GetMessageA
#endif /* ifdef _UNICODE */
#endif /* ifdef _M_CEE */
#include "Connector/SynchronousCalls.h"
#include <Util/Thread.h>
LOGGING (com.opengamma.language.connector.SynchronousCallsTest);
#define TIMEOUT_MESSAGE 1000
#define TIMEOUT_THREAD 3000
static void AllocateAndRelease () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *apSlot[20];
int i, j;
for (i = 0; i < 10; i++) {
apSlot[i] = oCalls.Acquire ();
ASSERT (apSlot[i]);
for (j = 0; j < i; j++) {
ASSERT (apSlot[j] != apSlot[i]);
ASSERT (apSlot[j]->GetIdentifier () != apSlot[i]->GetIdentifier ());
ASSERT (apSlot[j]->GetHandle () != apSlot[i]->GetHandle ());
}
ASSERT (apSlot[i]->GetSequence () == 1);
LOGDEBUG (TEXT ("Acquired slot ") << apSlot[i]->GetIdentifier () << TEXT (", handle=") << apSlot[i]->GetHandle ());
}
for (i = 0; i < 10; i += 2) {
apSlot[i]->Release ();
LOGDEBUG (TEXT ("Released slot ") << apSlot[i]->GetIdentifier ());
apSlot[i] = NULL;
}
for (i = 10; i < 20; i++) {
apSlot[i] = oCalls.Acquire ();
ASSERT (apSlot[i]);
if (i < 15) {
ASSERT (apSlot[i]->GetSequence () == 2);
} else {
ASSERT (apSlot[i]->GetSequence () == 1);
}
LOGDEBUG (TEXT ("Acquired slot ") << apSlot[i]->GetIdentifier () << TEXT (", handle=" ) << apSlot[i]->GetHandle ());
}
for (i = 0; i < 20; i++) {
if (apSlot[i]) {
apSlot[i]->Release ();
LOGDEBUG (TEXT ("Released slot ") << apSlot[i]->GetIdentifier ());
}
}
}
class CPostMessageThread : public CThread {
private:
FudgeMsg m_msg1, m_msg2;
fudge_i32 m_nHandle1, m_nHandle2;
CSynchronousCalls *m_poCalls;
public:
CPostMessageThread (FudgeMsg msg1, fudge_i32 nHandle1, FudgeMsg msg2, fudge_i32 nHandle2, CSynchronousCalls *poCalls) : CThread () {
FudgeMsg_retain (msg1);
FudgeMsg_retain (msg1);
m_msg1 = msg1;
m_nHandle1 = nHandle1;
FudgeMsg_retain (msg2);
FudgeMsg_retain (msg2);
m_msg2 = msg2;
m_nHandle2 = nHandle2;
m_poCalls = poCalls;
ASSERT (Start ());
}
void Run () {
LOGDEBUG (TEXT ("Sending first message"));
m_poCalls->PostAndRelease (m_nHandle1, m_msg1);
LOGDEBUG (TEXT ("Sending duplicate first message"));
m_poCalls->PostAndRelease (m_nHandle1, m_msg1);
LOGDEBUG (TEXT ("Sending second message"));
m_poCalls->PostAndRelease (m_nHandle2, m_msg2);
LOGDEBUG (TEXT ("Sending duplicate second message"));
m_poCalls->PostAndRelease (m_nHandle2, m_msg2);
}
};
static void PostAndWait () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *poSlot = oCalls.Acquire ();
ASSERT (poSlot);
int nIdentifier = poSlot->GetIdentifier ();
FudgeMsg msgA, msgB;
ASSERT (FudgeMsg_create (&msgA) == FUDGE_OK);
ASSERT (FudgeMsg_create (&msgB) == FUDGE_OK);
FudgeMsg msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (!msg);
fudge_i32 nHandle1 = poSlot->GetHandle ();
poSlot->Release ();
poSlot = oCalls.Acquire ();
ASSERT (poSlot && (poSlot->GetIdentifier () == nIdentifier));
fudge_i32 nHandle2 = poSlot->GetHandle ();
ASSERT (nHandle1 != nHandle2);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (!msg);
CThread *poSender = new CPostMessageThread (msgA, nHandle2, msgB, nHandle1, &oCalls);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (msg);
ASSERT (msg == msgA);
FudgeMsg_release (msg);
ASSERT (CThread::WaitAndRelease (poSender, TIMEOUT_THREAD));
poSlot->Release ();
poSlot = oCalls.Acquire ();
ASSERT (poSlot && (poSlot->GetIdentifier () == nIdentifier));
nHandle1 = poSlot->GetHandle ();
ASSERT (nHandle1 != nHandle2);
poSender = new CPostMessageThread (msgA, nHandle2, msgB, nHandle1, &oCalls);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (msg);
ASSERT (msg == msgB);
ASSERT (CThread::WaitAndRelease (poSender, TIMEOUT_THREAD));
poSlot->Release ();
FudgeMsg_release (msgA);
FudgeMsg_release (msgB);
}
class CRapidPostThread : public CThread {
private:
FudgeMsg m_msg;
CSynchronousCallSlot *m_poSlot;
CSynchronousCalls *m_poCalls;
CSemaphore m_oSignal;
volatile bool m_bPoison;
public:
CRapidPostThread (FudgeMsg msg, CSynchronousCallSlot *poSlot, CSynchronousCalls *poCalls)
: CThread (), m_oSignal (0, 1) {
FudgeMsg_retain (msg);
m_msg = msg;
m_poSlot = poSlot;
m_poCalls = poCalls;
ASSERT (Start ());
}
~CRapidPostThread () {
FudgeMsg_release (m_msg);
}
void Run () {
LOGDEBUG (TEXT ("Starting posting thread"));
m_oSignal.Signal ();
while (!m_bPoison) {
int nHandle = m_poSlot->GetHandle ();
CThread::Sleep (TIMEOUT_MESSAGE / 10);
LOGINFO (TEXT ("Posting handle ") << nHandle);
FudgeMsg_retain (m_msg);
m_poCalls->PostAndRelease (nHandle, m_msg);
}
}
void WaitForStart () {
ASSERT (m_oSignal.Wait (TIMEOUT_THREAD));
}
void Stop () {
m_bPoison = true;
}
};
static void RapidCalls () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *poSlot = oCalls.Acquire ();
ASSERT (poSlot);
FudgeMsg msg;
ASSERT (FudgeMsg_create (&msg) == FUDGE_OK);
CRapidPostThread *poPoster = new CRapidPostThread (msg, poSlot, &oCalls);
LOGDEBUG (TEXT ("Waiting for posting thread"));
poPoster->WaitForStart ();
LOGDEBUG (TEXT ("Reading messages"));
int i, nGot = 0;
for (i = 0; i < 30; i++) {
FudgeMsg msg2 = poSlot->GetMessage ((TIMEOUT_MESSAGE / 100) * i);
if (msg2) {
LOGINFO (TEXT ("Got message ") << (i + 1));
nGot++;
} else {
LOGINFO (TEXT ("No message ") << (i + 1));
}
poSlot->Release ();
poSlot = oCalls.Acquire ();
}
poPoster->Stop ();
poSlot->Release ();
ASSERT (CThread::WaitAndRelease (poPoster, TIMEOUT_THREAD));
FudgeMsg_release (msg);
LOGINFO (TEXT ("Got ") << nGot << TEXT (" of 30"));
/* Assuming 1000ms for TIMEOUT_MESSAGE; possible run is
*
* Time Get Send
* 0 Fail 1
* 10 Fail 2
* 30 Fail 3
* 60 Fail 4
* 100 Fail 5 Fail 1
* 150 Fail 6
* 200 Fail 5 or 6
* 210 Fail 7
* 280 Fail 8
* 300 Fail 7
* 360 Fail 9
* 400 Fail 9
* 450 Fail 10
* 500 Fail 11 Fail 10
* 600 Poss 11,12
* 610 Poss 12
* 700 Fail 12
* 730 Fail 13
* 800 Fail 13
* 900 Done 14
* 860 Get 14
* 1000 Fail 15 Fail 14
* 1150 Fail 16
* 1200 Fail 15 or 16
* 1300 Done 17
* 1310 Get 17
* 1400 Fail 17
* 1480 Fail 18
* 1500 Fail 18
* 1600 Done 19
* 1660 Get 19
* 1700 Fail 19
* 1800 Done 20
* 1850 Get 20
* 1900 Fail 20
* 2000 Done 21
* 2050 Get 21
* 2100 Fail 21
* 2200 Done 22
* 2260 Get 22
* 2300 Fail 22
* 2400 Done 23
* 2480 Get 23
* 2500 Fail 23
* 2600 Done 24
* 2700 Fail 24
* 2710 Get 24
* 2800 Fail 24
* 2900 Done 25
* 2950 Get 25
* 3000 Fail 25
* 3100 Done 26
* 3200 Get 26 Fail 26
* 3300 Done 27
* 3400 Fail 27
* 3460 Get 27
* 3500 Fail 27
* 3600 Done 28
* 3700 Fail 28
* 3730 Get 28
* 3800 Fail 28
* 3900 Fail 29
* 4000 Fail 29
* 4010 Get 29
* 4100 Fail 29
* 4200 Done 30
* 4300 Get 30 Fail 30
*/
// Expect to miss all of the first ten, but get all of the last ten. Those in
// the middle are a bit hit or miss. Perhaps we might expect around 14 (e.g. above)
// but it's all dependent on scheduling.
ASSERT (nGot > 10);
}
BEGIN_TESTS (SynchronousCallsTest)
TEST (AllocateAndRelease)
TEST (PostAndWait)
TEST (RapidCalls)
END_TESTS
<commit_msg>Set initial value of m_bPoison to false.<commit_after>/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
#include "stdafx.h"
// Test the functions and objects in Connector/SynchronousCalls.cpp
#ifdef _M_CEE
#ifdef _UNICODE
#define GetMessage GetMessageW
#else
#define GetMessage GetMessageA
#endif /* ifdef _UNICODE */
#endif /* ifdef _M_CEE */
#include "Connector/SynchronousCalls.h"
#include <Util/Thread.h>
LOGGING (com.opengamma.language.connector.SynchronousCallsTest);
#define TIMEOUT_MESSAGE 1000
#define TIMEOUT_THREAD 3000
static void AllocateAndRelease () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *apSlot[20];
int i, j;
for (i = 0; i < 10; i++) {
apSlot[i] = oCalls.Acquire ();
ASSERT (apSlot[i]);
for (j = 0; j < i; j++) {
ASSERT (apSlot[j] != apSlot[i]);
ASSERT (apSlot[j]->GetIdentifier () != apSlot[i]->GetIdentifier ());
ASSERT (apSlot[j]->GetHandle () != apSlot[i]->GetHandle ());
}
ASSERT (apSlot[i]->GetSequence () == 1);
LOGDEBUG (TEXT ("Acquired slot ") << apSlot[i]->GetIdentifier () << TEXT (", handle=") << apSlot[i]->GetHandle ());
}
for (i = 0; i < 10; i += 2) {
apSlot[i]->Release ();
LOGDEBUG (TEXT ("Released slot ") << apSlot[i]->GetIdentifier ());
apSlot[i] = NULL;
}
for (i = 10; i < 20; i++) {
apSlot[i] = oCalls.Acquire ();
ASSERT (apSlot[i]);
if (i < 15) {
ASSERT (apSlot[i]->GetSequence () == 2);
} else {
ASSERT (apSlot[i]->GetSequence () == 1);
}
LOGDEBUG (TEXT ("Acquired slot ") << apSlot[i]->GetIdentifier () << TEXT (", handle=" ) << apSlot[i]->GetHandle ());
}
for (i = 0; i < 20; i++) {
if (apSlot[i]) {
apSlot[i]->Release ();
LOGDEBUG (TEXT ("Released slot ") << apSlot[i]->GetIdentifier ());
}
}
}
class CPostMessageThread : public CThread {
private:
FudgeMsg m_msg1, m_msg2;
fudge_i32 m_nHandle1, m_nHandle2;
CSynchronousCalls *m_poCalls;
public:
CPostMessageThread (FudgeMsg msg1, fudge_i32 nHandle1, FudgeMsg msg2, fudge_i32 nHandle2, CSynchronousCalls *poCalls) : CThread () {
FudgeMsg_retain (msg1);
FudgeMsg_retain (msg1);
m_msg1 = msg1;
m_nHandle1 = nHandle1;
FudgeMsg_retain (msg2);
FudgeMsg_retain (msg2);
m_msg2 = msg2;
m_nHandle2 = nHandle2;
m_poCalls = poCalls;
ASSERT (Start ());
}
void Run () {
LOGDEBUG (TEXT ("Sending first message"));
m_poCalls->PostAndRelease (m_nHandle1, m_msg1);
LOGDEBUG (TEXT ("Sending duplicate first message"));
m_poCalls->PostAndRelease (m_nHandle1, m_msg1);
LOGDEBUG (TEXT ("Sending second message"));
m_poCalls->PostAndRelease (m_nHandle2, m_msg2);
LOGDEBUG (TEXT ("Sending duplicate second message"));
m_poCalls->PostAndRelease (m_nHandle2, m_msg2);
}
};
static void PostAndWait () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *poSlot = oCalls.Acquire ();
ASSERT (poSlot);
int nIdentifier = poSlot->GetIdentifier ();
FudgeMsg msgA, msgB;
ASSERT (FudgeMsg_create (&msgA) == FUDGE_OK);
ASSERT (FudgeMsg_create (&msgB) == FUDGE_OK);
FudgeMsg msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (!msg);
fudge_i32 nHandle1 = poSlot->GetHandle ();
poSlot->Release ();
poSlot = oCalls.Acquire ();
ASSERT (poSlot && (poSlot->GetIdentifier () == nIdentifier));
fudge_i32 nHandle2 = poSlot->GetHandle ();
ASSERT (nHandle1 != nHandle2);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (!msg);
CThread *poSender = new CPostMessageThread (msgA, nHandle2, msgB, nHandle1, &oCalls);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (msg);
ASSERT (msg == msgA);
FudgeMsg_release (msg);
ASSERT (CThread::WaitAndRelease (poSender, TIMEOUT_THREAD));
poSlot->Release ();
poSlot = oCalls.Acquire ();
ASSERT (poSlot && (poSlot->GetIdentifier () == nIdentifier));
nHandle1 = poSlot->GetHandle ();
ASSERT (nHandle1 != nHandle2);
poSender = new CPostMessageThread (msgA, nHandle2, msgB, nHandle1, &oCalls);
msg = poSlot->GetMessage (TIMEOUT_MESSAGE);
ASSERT (msg);
ASSERT (msg == msgB);
ASSERT (CThread::WaitAndRelease (poSender, TIMEOUT_THREAD));
poSlot->Release ();
FudgeMsg_release (msgA);
FudgeMsg_release (msgB);
}
class CRapidPostThread : public CThread {
private:
FudgeMsg m_msg;
CSynchronousCallSlot *m_poSlot;
CSynchronousCalls *m_poCalls;
CSemaphore m_oSignal;
volatile bool m_bPoison;
public:
CRapidPostThread (FudgeMsg msg, CSynchronousCallSlot *poSlot, CSynchronousCalls *poCalls)
: CThread (), m_oSignal (0, 1) {
FudgeMsg_retain (msg);
m_msg = msg;
m_poSlot = poSlot;
m_poCalls = poCalls;
m_bPoison = false;
ASSERT (Start ());
}
~CRapidPostThread () {
FudgeMsg_release (m_msg);
}
void Run () {
LOGDEBUG (TEXT ("Starting posting thread"));
m_oSignal.Signal ();
while (!m_bPoison) {
int nHandle = m_poSlot->GetHandle ();
CThread::Sleep (TIMEOUT_MESSAGE / 10);
LOGINFO (TEXT ("Posting handle ") << nHandle);
FudgeMsg_retain (m_msg);
m_poCalls->PostAndRelease (nHandle, m_msg);
}
}
void WaitForStart () {
ASSERT (m_oSignal.Wait (TIMEOUT_THREAD));
}
void Stop () {
m_bPoison = true;
}
};
static void RapidCalls () {
CSynchronousCalls oCalls;
CSynchronousCallSlot *poSlot = oCalls.Acquire ();
ASSERT (poSlot);
FudgeMsg msg;
ASSERT (FudgeMsg_create (&msg) == FUDGE_OK);
CRapidPostThread *poPoster = new CRapidPostThread (msg, poSlot, &oCalls);
LOGDEBUG (TEXT ("Waiting for posting thread"));
poPoster->WaitForStart ();
LOGDEBUG (TEXT ("Reading messages"));
int i, nGot = 0;
for (i = 0; i < 30; i++) {
FudgeMsg msg2 = poSlot->GetMessage ((TIMEOUT_MESSAGE / 100) * i);
if (msg2) {
LOGINFO (TEXT ("Got message ") << (i + 1));
nGot++;
} else {
LOGINFO (TEXT ("No message ") << (i + 1));
}
poSlot->Release ();
poSlot = oCalls.Acquire ();
}
poPoster->Stop ();
poSlot->Release ();
ASSERT (CThread::WaitAndRelease (poPoster, TIMEOUT_THREAD));
FudgeMsg_release (msg);
LOGINFO (TEXT ("Got ") << nGot << TEXT (" of 30"));
/* Assuming 1000ms for TIMEOUT_MESSAGE; possible run is
*
* Time Get Send
* 0 Fail 1
* 10 Fail 2
* 30 Fail 3
* 60 Fail 4
* 100 Fail 5 Fail 1
* 150 Fail 6
* 200 Fail 5 or 6
* 210 Fail 7
* 280 Fail 8
* 300 Fail 7
* 360 Fail 9
* 400 Fail 9
* 450 Fail 10
* 500 Fail 11 Fail 10
* 600 Poss 11,12
* 610 Poss 12
* 700 Fail 12
* 730 Fail 13
* 800 Fail 13
* 900 Done 14
* 860 Get 14
* 1000 Fail 15 Fail 14
* 1150 Fail 16
* 1200 Fail 15 or 16
* 1300 Done 17
* 1310 Get 17
* 1400 Fail 17
* 1480 Fail 18
* 1500 Fail 18
* 1600 Done 19
* 1660 Get 19
* 1700 Fail 19
* 1800 Done 20
* 1850 Get 20
* 1900 Fail 20
* 2000 Done 21
* 2050 Get 21
* 2100 Fail 21
* 2200 Done 22
* 2260 Get 22
* 2300 Fail 22
* 2400 Done 23
* 2480 Get 23
* 2500 Fail 23
* 2600 Done 24
* 2700 Fail 24
* 2710 Get 24
* 2800 Fail 24
* 2900 Done 25
* 2950 Get 25
* 3000 Fail 25
* 3100 Done 26
* 3200 Get 26 Fail 26
* 3300 Done 27
* 3400 Fail 27
* 3460 Get 27
* 3500 Fail 27
* 3600 Done 28
* 3700 Fail 28
* 3730 Get 28
* 3800 Fail 28
* 3900 Fail 29
* 4000 Fail 29
* 4010 Get 29
* 4100 Fail 29
* 4200 Done 30
* 4300 Get 30 Fail 30
*/
// Expect to miss all of the first ten, but get all of the last ten. Those in
// the middle are a bit hit or miss. Perhaps we might expect around 14 (e.g. above)
// but it's all dependent on scheduling.
ASSERT (nGot > 10);
}
BEGIN_TESTS (SynchronousCallsTest)
TEST (AllocateAndRelease)
TEST (PostAndWait)
TEST (RapidCalls)
END_TESTS
<|endoftext|>
|
<commit_before>
#include <libclientserver.h>
ServerManager::ServerManager(IServerHandler *Handler)
{
m_handler = Handler;
}
ServerManager::~ServerManager()
{
ServerRemoveAll();
}
void ServerManager::ServerAdd(IServer *Server)
{
ScopedLock lock(&m_ServersMutex);
m_Servers.push_back(Server);
Server->Start(this);
}
void ServerManager::ServerRemove(IServer *Server)
{
ScopedLock lock(&m_ServersMutex);
Server->Stop();
std::list<IServer *>::iterator it;
for(it = m_Servers.begin(); it != m_Servers.end(); it++)
{
if (*it == Server)
{
m_Servers.erase(it);
return;
}
}
}
void ServerManager::ServerRemoveAll()
{
ScopedLock lock(&m_ServersMutex);
while(m_Servers.size() > 0)
{
ServerRemove(m_Servers.front());
}
}
bool ServerManager::ProcessLine(IServerConnection *Connection, const std::string *line)
{
std::string command = "";
std::string args = "";
if (String::SplitOne(line, &command, &args, " ") == false)
{
RaiseBadLine(Connection, line);
return false;
}
if (command == "REQUEST")
{
Request request;
Request response;
if (request.Decode(&args) == false)
{
RaiseBadLine(Connection, line);
return false;
}
m_TotalRequests++;
try
{
int retvalue = RaiseRequest(Connection, &request, &response);
response.SetArg("_ERRNO", retvalue);
response.SetArg("_ERROR", strerror(retvalue));
}
catch(ServerException &e)
{
Request tmp;
tmp.SetArg("_ERRNO", Encoder::ToStr(e.GetErrorNo()));
tmp.SetArg("_ERROR", e.GetErrorMessage());
response = tmp;
}
catch(std::exception &e)
{
Request tmp;
std::string msg = e.what();
tmp.SetArg("_EXCEPTION", msg);
response = tmp;
}
response.SetCommand(request.GetCommand());
response.SetID(request.GetID());
std::string ResponseStr = "RESPONSE " + response.Encode() + "\n";
return Connection->SendLine(&ResponseStr);
}
if (command == "COMMAND")
{
Request request;
if (request.Decode(&args) == false)
{
RaiseBadLine(Connection, line);
return false;
}
m_TotalCommands++;
return RaiseCommand(Connection, &request);
}
RaiseBadLine(Connection, line);
return false;
}
void ServerManager::RaisePreNewConnection()
{
m_handler->OnPreNewConnection();
}
void ServerManager::RaisePostNewConnection(IServerConnection *Connection)
{
m_handler->OnPostNewConnection(Connection);
}
void ServerManager::RaiseDisconnect(IServerConnection *Connection)
{
m_handler->OnDisconnect(Connection);
}
void ServerManager::RaiseBadLine(IServerConnection *Connection, const std::string *line)
{
m_handler->OnBadLine(Connection, line);
}
int ServerManager::RaiseRequest(IServerConnection *Connection, Request *request, Request *response)
{
return m_handler->OnRequest(Connection, request, response);
}
int ServerManager::RaiseCommand(IServerConnection *Connection, Request *request)
{
return m_handler->OnCommand(Connection, request);
}
void ServerManager::SendEvent(Request *event)
{
ScopedLock lock(&m_ServersMutex);
std::list<IServer *>::iterator it;
for(it = m_Servers.begin(); it != m_Servers.end(); it++)
{
(*it)->SendEvent(event);
}
}
<commit_msg>Prevent a copy of return request<commit_after>
#include <libclientserver.h>
ServerManager::ServerManager(IServerHandler *Handler)
{
m_handler = Handler;
}
ServerManager::~ServerManager()
{
ServerRemoveAll();
}
void ServerManager::ServerAdd(IServer *Server)
{
ScopedLock lock(&m_ServersMutex);
m_Servers.push_back(Server);
Server->Start(this);
}
void ServerManager::ServerRemove(IServer *Server)
{
ScopedLock lock(&m_ServersMutex);
Server->Stop();
std::list<IServer *>::iterator it;
for(it = m_Servers.begin(); it != m_Servers.end(); it++)
{
if (*it == Server)
{
m_Servers.erase(it);
return;
}
}
}
void ServerManager::ServerRemoveAll()
{
ScopedLock lock(&m_ServersMutex);
while(m_Servers.size() > 0)
{
ServerRemove(m_Servers.front());
}
}
bool ServerManager::ProcessLine(IServerConnection *Connection, const std::string *line)
{
std::string command = "";
std::string args = "";
if (String::SplitOne(line, &command, &args, " ") == false)
{
RaiseBadLine(Connection, line);
return false;
}
if (command == "REQUEST")
{
Request request;
Request response;
if (request.Decode(&args) == false)
{
RaiseBadLine(Connection, line);
return false;
}
m_TotalRequests++;
try
{
int retvalue = RaiseRequest(Connection, &request, &response);
response.SetArg("_ERRNO", retvalue);
response.SetArg("_ERROR", strerror(retvalue));
}
catch(ServerException &e)
{
response.SetArg("_ERRNO", Encoder::ToStr(e.GetErrorNo()));
response.SetArg("_ERROR", e.GetErrorMessage());
std::string msg = e.what();
response.SetArg("_EXCEPTION", msg);
}
catch(std::exception &e)
{
std::string msg = e.what();
response.SetArg("_EXCEPTION", msg);
}
response.SetCommand(request.GetCommand());
response.SetID(request.GetID());
std::string ResponseStr = "RESPONSE " + response.Encode() + "\n";
return Connection->SendLine(&ResponseStr);
}
if (command == "COMMAND")
{
Request request;
if (request.Decode(&args) == false)
{
RaiseBadLine(Connection, line);
return false;
}
m_TotalCommands++;
return RaiseCommand(Connection, &request);
}
RaiseBadLine(Connection, line);
return false;
}
void ServerManager::RaisePreNewConnection()
{
m_handler->OnPreNewConnection();
}
void ServerManager::RaisePostNewConnection(IServerConnection *Connection)
{
m_handler->OnPostNewConnection(Connection);
}
void ServerManager::RaiseDisconnect(IServerConnection *Connection)
{
m_handler->OnDisconnect(Connection);
}
void ServerManager::RaiseBadLine(IServerConnection *Connection, const std::string *line)
{
m_handler->OnBadLine(Connection, line);
}
int ServerManager::RaiseRequest(IServerConnection *Connection, Request *request, Request *response)
{
return m_handler->OnRequest(Connection, request, response);
}
int ServerManager::RaiseCommand(IServerConnection *Connection, Request *request)
{
return m_handler->OnCommand(Connection, request);
}
void ServerManager::SendEvent(Request *event)
{
ScopedLock lock(&m_ServersMutex);
std::list<IServer *>::iterator it;
for(it = m_Servers.begin(); it != m_Servers.end(); it++)
{
(*it)->SendEvent(event);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>
using namespace bb::cascades;
static ApplicationUI *s_btApp = NULL;
ApplicationUI::ApplicationUI(Application *app)
: QObject(app)
, _pathToFilesDirectory(QDir::currentPath().append("/app/public/files"))
, _downloadFolderWatcher(new QFileSystemWatcher(this))
{
s_btApp = this;
_translator = new QTranslator(this);
_localeHandler = new LocaleHandler(this);
bool res = QObject::connect(_localeHandler, SIGNAL(systemLanguageChanged()),
this, SLOT(onSystemLanguageChanged()));
Q_ASSERT(res);
Q_UNUSED(res);
onSystemLanguageChanged();
_qml = QmlDocument::create("asset:///main.qml").parent(this);
_root = _qml->createRootObject<AbstractPane>();
_mainPage = _root->findChild<QObject*>("mainPage");
_downloadFolderWatcher->addPath(QDir::currentPath().append("/shared/downloads"));
// ============== Watch the downloads directory
QObject::connect(_downloadFolderWatcher, SIGNAL(directoryChanged(const QString &)),
this, SLOT(onDirectoryChanged(const QString &)));
// ============== Message to be sent to page
QObject::connect( this, SIGNAL(message(QVariant)),
_mainPage, SLOT(message(QVariant)));
// ============== Hook up buttons
// ============== Connection state to page
Application::instance()->setScene(_root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(_translator);
QString locale_string = QLocale().name();
QString file_name = QString("testopp_%1").arg(locale_string);
if (_translator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(_translator);
}
}
void ApplicationUI::onDirectoryChanged(const QString &path)
{
qDebug() << "XXXX Directory changed" << path << endl;
QDir downloads(path);
QStringList nameFilters;
nameFilters << "*.zip";
QDir::Filters fileFilters = (QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
QDir::SortFlags sortOrder = (QDir::Time | QDir::Reversed);
QFileInfoList candidateFiles = downloads.entryInfoList(nameFilters, fileFilters, sortOrder);
for (int i = 0; i < candidateFiles.count(); i++) {
QString fileName = candidateFiles[i].fileName();
QString filePath = candidateFiles[i].filePath();
QFile receivedFile(filePath);
emit message(QString("Received file %1").arg(fileName));
QString program = "unzip";
QStringList arguments;
arguments << "-l";
arguments << filePath;
QProcess *unzip = new QProcess(this);
unzip->setReadChannel(QProcess::StandardOutput);
unzip->start(program, arguments);
if (unzip->waitForStarted()) { // TODO: not a good idea on a GUI thread but this is a test for PoC
if (unzip->waitForFinished()) { // TODO: not a good idea on a GUI thread but this is a test for PoC
QByteArray result = unzip->readAllStandardOutput();
QString unzipOutput(result);
qDebug() << "XXXX Unzip Command completed\n" << unzipOutput << endl;
emit message(unzipOutput);
} else {
qDebug() << "XXXX Unzip Command did not finish" << endl;
}
} else {
qDebug() << "XXXX Unzip Command did not start" << endl;
}
if (receivedFile.remove()) {
emit message(QString("Processed file %1").arg(fileName));
} else {
emit message(QString("Error removing file %1").arg(fileName));
}
}
}
<commit_msg>checkpoint<commit_after>/*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>
using namespace bb::cascades;
static ApplicationUI *s_btApp = NULL;
ApplicationUI::ApplicationUI(Application *app)
: QObject(app)
, _pathToFilesDirectory(QDir::currentPath().append("/app/public/files"))
, _downloadFolderWatcher(new QFileSystemWatcher(this))
{
s_btApp = this;
_translator = new QTranslator(this);
_localeHandler = new LocaleHandler(this);
bool res = QObject::connect(_localeHandler, SIGNAL(systemLanguageChanged()),
this, SLOT(onSystemLanguageChanged()));
Q_ASSERT(res);
Q_UNUSED(res);
onSystemLanguageChanged();
_qml = QmlDocument::create("asset:///main.qml").parent(this);
_root = _qml->createRootObject<AbstractPane>();
_mainPage = _root->findChild<QObject*>("mainPage");
_downloadFolderWatcher->addPath(QDir::currentPath().append("/shared/downloads"));
// ============== Watch the downloads directory
QObject::connect(_downloadFolderWatcher, SIGNAL(directoryChanged(const QString &)),
this, SLOT(onDirectoryChanged(const QString &)));
// ============== Message to be sent to page
QObject::connect( this, SIGNAL(message(QVariant)),
_mainPage, SLOT(message(QVariant)));
// ============== Hook up buttons
// ============== Connection state to page
Application::instance()->setScene(_root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(_translator);
QString locale_string = QLocale().name();
QString file_name = QString("testopp_%1").arg(locale_string);
if (_translator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(_translator);
}
}
void ApplicationUI::onDirectoryChanged(const QString &path)
{
qDebug() << "XXXX Directory changed" << path << endl;
QDir downloads(path);
QStringList nameFilters;
nameFilters << "*.zip";
QDir::Filters fileFilters = (QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
QDir::SortFlags sortOrder = (QDir::Time | QDir::Reversed);
QFileInfoList candidateFiles = downloads.entryInfoList(nameFilters, fileFilters, sortOrder);
for (int i = 0; i < candidateFiles.count(); i++) {
QString fileName = candidateFiles[i].fileName();
QString filePath = candidateFiles[i].filePath();
QFile receivedFile(filePath);
emit message(QString("Received file %1").arg(fileName));
QString program = "unzip";
QStringList arguments;
arguments << "-l";
arguments << filePath;
QProcess *unzip = new QProcess(this);
unzip->setReadChannel(QProcess::StandardOutput);
unzip->start(program, arguments);
if (unzip->waitForStarted()) { // TODO: not a good idea on a GUI thread but this is a test for PoC
if (unzip->waitForFinished()) { // TODO: not a good idea on a GUI thread but this is a test for PoC
QByteArray result = unzip->readAllStandardOutput();
QString unzipOutput(result);
qDebug() << "XXXX Unzip Command completed\n" << unzipOutput << endl;
emit message(unzipOutput);
} else {
qDebug() << "XXXX Unzip Command did not finish" << endl;
}
} else {
qDebug() << "XXXX Unzip Command did not start" << endl;
}
delete unzip;
if (receivedFile.remove()) {
emit message(QString("Processed file %1").arg(fileName));
} else {
emit message(QString("Error removing file %1").arg(fileName));
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/cpuid.hh"
#include "base/bitfield.hh"
#include "cpu/thread_context.hh"
namespace X86ISA {
enum StandardCpuidFunction {
VendorAndLargestStdFunc,
FamilyModelStepping,
NumStandardCpuidFuncs
};
enum ExtendedCpuidFunctions {
VendorAndLargestExtFunc,
FamilyModelSteppingBrandFeatures,
NameString1,
NameString2,
NameString3,
L1CacheAndTLB,
L2L3CacheAndL2TLB,
APMInfo,
LongModeAddressSize,
/*
* The following are defined by the spec but not yet implemented
*/
/* // Function 9 is reserved
SVMInfo = 10,
// Functions 11-24 are reserved
TLB1GBPageInfo = 25,
PerformanceInfo,*/
NumExtendedCpuidFuncs
};
static const int vendorStringSize = 13;
static const char vendorString[vendorStringSize] = "M5 Simulator";
static const int nameStringSize = 48;
static const char nameString[nameStringSize] = "Fake M5 x86_64 CPU";
uint64_t
stringToRegister(const char *str)
{
uint64_t reg = 0;
for (int pos = 3; pos >=0; pos--) {
reg <<= 8;
reg |= str[pos];
}
return reg;
}
bool
doCpuid(ThreadContext * tc, uint32_t function,
uint32_t index, CpuidResult &result)
{
uint16_t family = bits(function, 31, 16);
uint16_t funcNum = bits(function, 15, 0);
if (family == 0x8000) {
// The extended functions
switch (funcNum) {
case VendorAndLargestExtFunc:
assert(vendorStringSize >= 12);
result = CpuidResult(
0x80000000 + NumExtendedCpuidFuncs - 1,
stringToRegister(vendorString),
stringToRegister(vendorString + 4),
stringToRegister(vendorString + 8));
break;
case FamilyModelSteppingBrandFeatures:
result = CpuidResult(0x00020f51, 0x00000405,
0xe3d3fbff, 0x00000001);
break;
case NameString1:
case NameString2:
case NameString3:
{
// Zero fill anything beyond the end of the string. This
// should go away once the string is a vetted parameter.
char cleanName[nameStringSize];
memset(cleanName, '\0', nameStringSize);
strncpy(cleanName, nameString, nameStringSize);
int offset = (funcNum - NameString1) * 16;
assert(nameStringSize >= offset + 16);
result = CpuidResult(
stringToRegister(cleanName + offset + 0),
stringToRegister(cleanName + offset + 4),
stringToRegister(cleanName + offset + 12),
stringToRegister(cleanName + offset + 8));
}
break;
case L1CacheAndTLB:
result = CpuidResult(0xff08ff08, 0xff20ff20,
0x40020140, 0x40020140);
break;
case L2L3CacheAndL2TLB:
result = CpuidResult(0x00000000, 0x42004200,
0x00000000, 0x04008140);
break;
case APMInfo:
result = CpuidResult(0x80000018, 0x68747541,
0x69746e65, 0x444d4163);
break;
case LongModeAddressSize:
result = CpuidResult(0x0000ffff, 0x00000000,
0x00000000, 0x00000000);
break;
/* case SVMInfo:
case TLB1GBPageInfo:
case PerformanceInfo:*/
default:
warn("x86 cpuid: unimplemented function %u", funcNum);
return false;
}
} else if(family == 0x0000) {
// The standard functions
switch (funcNum) {
case VendorAndLargestStdFunc:
assert(vendorStringSize >= 12);
result = CpuidResult(
NumStandardCpuidFuncs - 1,
stringToRegister(vendorString),
stringToRegister(vendorString + 4),
stringToRegister(vendorString + 8));
break;
case FamilyModelStepping:
result = CpuidResult(0x00020f51, 0x00000805,
0xe7dbfbff, 0x00000001);
break;
default:
warn("x86 cpuid: unimplemented function %u", funcNum);
return false;
}
} else {
warn("x86 cpuid: unknown family %#x", family);
return false;
}
return true;
}
} // namespace X86ISA
<commit_msg>x86: Fix the CPUID Long Mode Address Size function.<commit_after>/*
* Copyright (c) 2008 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/cpuid.hh"
#include "base/bitfield.hh"
#include "cpu/thread_context.hh"
namespace X86ISA {
enum StandardCpuidFunction {
VendorAndLargestStdFunc,
FamilyModelStepping,
NumStandardCpuidFuncs
};
enum ExtendedCpuidFunctions {
VendorAndLargestExtFunc,
FamilyModelSteppingBrandFeatures,
NameString1,
NameString2,
NameString3,
L1CacheAndTLB,
L2L3CacheAndL2TLB,
APMInfo,
LongModeAddressSize,
/*
* The following are defined by the spec but not yet implemented
*/
/* // Function 9 is reserved
SVMInfo = 10,
// Functions 11-24 are reserved
TLB1GBPageInfo = 25,
PerformanceInfo,*/
NumExtendedCpuidFuncs
};
static const int vendorStringSize = 13;
static const char vendorString[vendorStringSize] = "M5 Simulator";
static const int nameStringSize = 48;
static const char nameString[nameStringSize] = "Fake M5 x86_64 CPU";
uint64_t
stringToRegister(const char *str)
{
uint64_t reg = 0;
for (int pos = 3; pos >=0; pos--) {
reg <<= 8;
reg |= str[pos];
}
return reg;
}
bool
doCpuid(ThreadContext * tc, uint32_t function,
uint32_t index, CpuidResult &result)
{
uint16_t family = bits(function, 31, 16);
uint16_t funcNum = bits(function, 15, 0);
if (family == 0x8000) {
// The extended functions
switch (funcNum) {
case VendorAndLargestExtFunc:
assert(vendorStringSize >= 12);
result = CpuidResult(
0x80000000 + NumExtendedCpuidFuncs - 1,
stringToRegister(vendorString),
stringToRegister(vendorString + 4),
stringToRegister(vendorString + 8));
break;
case FamilyModelSteppingBrandFeatures:
result = CpuidResult(0x00020f51, 0x00000405,
0xe3d3fbff, 0x00000001);
break;
case NameString1:
case NameString2:
case NameString3:
{
// Zero fill anything beyond the end of the string. This
// should go away once the string is a vetted parameter.
char cleanName[nameStringSize];
memset(cleanName, '\0', nameStringSize);
strncpy(cleanName, nameString, nameStringSize);
int offset = (funcNum - NameString1) * 16;
assert(nameStringSize >= offset + 16);
result = CpuidResult(
stringToRegister(cleanName + offset + 0),
stringToRegister(cleanName + offset + 4),
stringToRegister(cleanName + offset + 12),
stringToRegister(cleanName + offset + 8));
}
break;
case L1CacheAndTLB:
result = CpuidResult(0xff08ff08, 0xff20ff20,
0x40020140, 0x40020140);
break;
case L2L3CacheAndL2TLB:
result = CpuidResult(0x00000000, 0x42004200,
0x00000000, 0x04008140);
break;
case APMInfo:
result = CpuidResult(0x80000018, 0x68747541,
0x69746e65, 0x444d4163);
break;
case LongModeAddressSize:
result = CpuidResult(0x00003030, 0x00000000,
0x00000000, 0x00000000);
break;
/* case SVMInfo:
case TLB1GBPageInfo:
case PerformanceInfo:*/
default:
warn("x86 cpuid: unimplemented function %u", funcNum);
return false;
}
} else if(family == 0x0000) {
// The standard functions
switch (funcNum) {
case VendorAndLargestStdFunc:
assert(vendorStringSize >= 12);
result = CpuidResult(
NumStandardCpuidFuncs - 1,
stringToRegister(vendorString),
stringToRegister(vendorString + 4),
stringToRegister(vendorString + 8));
break;
case FamilyModelStepping:
result = CpuidResult(0x00020f51, 0x00000805,
0xe7dbfbff, 0x00000001);
break;
default:
warn("x86 cpuid: unimplemented function %u", funcNum);
return false;
}
} else {
warn("x86 cpuid: unknown family %#x", family);
return false;
}
return true;
}
} // namespace X86ISA
<|endoftext|>
|
<commit_before>/*
* Jamoma RampLib Base Class
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#ifdef WIN_VERSION
#pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION
#include "RampLib.h"
#include "ext.h"
#define thisTTClass RampUnit
RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
: TTObject(kTTValNONE), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
callback = aCallbackMethod;
baton = aBaton;
setNumValues(1);
currentValue[0] = 0.0;
targetValue[0] = 0.0;
startValue[0] = 0.0;
addAttributeWithSetter(Function, kTypeSymbol);
setAttributeValue(TT("Function"), TT("linear"));
}
RampUnit::~RampUnit()
{
TTObjectRelease(&functionUnit);
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
TTUInt32 i;
stop();
setNumValues(newNumValues);
for (i=0; i<newNumValues; i++)
currentValue[i] = newValues[i];
}
TTErr RampUnit::setFunction(const TTValue& functionName)
{
TTErr err;
TTSymbolPtr newFunctionName = NULL;
functionName.get(0, &newFunctionName);
if (newFunctionName == TT("none"))
newFunctionName = TT("linear");
if (newFunctionName == mFunction)
return kTTErrNone;
mFunction = newFunctionName;
err = FunctionLib::createUnit(mFunction, (TTObject**)&functionUnit);
if (err)
logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
return err;
}
TTErr RampUnit::getFunctionParameterNames(TTValue& names)
{
functionUnit->getAttributeNames(names);
return kTTErrNone;
}
TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, TTValue& newValue)
{
functionUnit->setAttributeValue(parameterName, newValue);
return kTTErrNone;
}
TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
functionUnit->getAttributeValue(parameterName, value);
return kTTErrNone;
}
void RampUnit::setNumValues(TTUInt32 newNumValues)
{
if (newNumValues != numValues) {
if (numValues != 0) {
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
currentValue = new TTFloat64[newNumValues];
targetValue = new TTFloat64[newNumValues];
startValue = new TTFloat64[newNumValues];
numValues = newNumValues;
}
sendMessage(TT("numValuesChanged")); // Notify sub-classes (if they respond to this message)
}
/***************************************************************************
RampLib
***************************************************************************/
#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"
JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
if (*unit)
delete *unit;
// These should be alphabetized
if (unitName == TT("async"))
*unit = (RampUnit*) new AsyncRamp(callback, baton);
else if (unitName == TT("none"))
*unit = (RampUnit*) new NoneRamp(callback, baton);
else if (unitName == TT("queue"))
*unit = (RampUnit*) new QueueRamp(callback, baton);
else if (unitName == TT("scheduler"))
*unit = (RampUnit*) new SchedulerRamp(callback, baton);
else {
// Invalid function specified default to linear
// TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
error("puke");
*unit = (RampUnit*) new NoneRamp(callback, baton);
}
return JAMOMA_ERR_NONE;
}
void RampLib::getUnitNames(TTValue& unitNames)
{
unitNames.clear();
unitNames.append(TT("async"));
unitNames.append(TT("none"));
unitNames.append(TT("queue"));
unitNames.append(TT("scheduler"));
}
<commit_msg>RampLib: replacing the 'puke' error message with something a bit more descriptive :-)<commit_after>/*
* Jamoma RampLib Base Class
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#ifdef WIN_VERSION
#pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION
#include "RampLib.h"
#include "ext.h"
#define thisTTClass RampUnit
RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
: TTObject(kTTValNONE), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
callback = aCallbackMethod;
baton = aBaton;
setNumValues(1);
currentValue[0] = 0.0;
targetValue[0] = 0.0;
startValue[0] = 0.0;
addAttributeWithSetter(Function, kTypeSymbol);
setAttributeValue(TT("Function"), TT("linear"));
}
RampUnit::~RampUnit()
{
TTObjectRelease(&functionUnit);
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
TTUInt32 i;
stop();
setNumValues(newNumValues);
for (i=0; i<newNumValues; i++)
currentValue[i] = newValues[i];
}
TTErr RampUnit::setFunction(const TTValue& functionName)
{
TTErr err;
TTSymbolPtr newFunctionName = NULL;
functionName.get(0, &newFunctionName);
if (newFunctionName == TT("none"))
newFunctionName = TT("linear");
if (newFunctionName == mFunction)
return kTTErrNone;
mFunction = newFunctionName;
err = FunctionLib::createUnit(mFunction, (TTObject**)&functionUnit);
if (err)
logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
return err;
}
TTErr RampUnit::getFunctionParameterNames(TTValue& names)
{
functionUnit->getAttributeNames(names);
return kTTErrNone;
}
TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, TTValue& newValue)
{
functionUnit->setAttributeValue(parameterName, newValue);
return kTTErrNone;
}
TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
functionUnit->getAttributeValue(parameterName, value);
return kTTErrNone;
}
void RampUnit::setNumValues(TTUInt32 newNumValues)
{
if (newNumValues != numValues) {
if (numValues != 0) {
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
currentValue = new TTFloat64[newNumValues];
targetValue = new TTFloat64[newNumValues];
startValue = new TTFloat64[newNumValues];
numValues = newNumValues;
}
sendMessage(TT("numValuesChanged")); // Notify sub-classes (if they respond to this message)
}
/***************************************************************************
RampLib
***************************************************************************/
#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"
JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
if (*unit)
delete *unit;
// These should be alphabetized
if (unitName == TT("async"))
*unit = (RampUnit*) new AsyncRamp(callback, baton);
else if (unitName == TT("none"))
*unit = (RampUnit*) new NoneRamp(callback, baton);
else if (unitName == TT("queue"))
*unit = (RampUnit*) new QueueRamp(callback, baton);
else if (unitName == TT("scheduler"))
*unit = (RampUnit*) new SchedulerRamp(callback, baton);
else {
// Invalid function specified default to linear
error("Jamoma RampLib: Invalid RampUnit ( %s ) specified", (char*)unitName);
*unit = (RampUnit*) new NoneRamp(callback, baton);
}
return JAMOMA_ERR_NONE;
}
void RampLib::getUnitNames(TTValue& unitNames)
{
unitNames.clear();
unitNames.append(TT("async"));
unitNames.append(TT("none"));
unitNames.append(TT("queue"));
unitNames.append(TT("scheduler"));
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: VCoordinateSystem.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: bm $ $Date: 2004-01-26 09:13:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "VCoordinateSystem.hxx"
#include "VCartesianCoordinateSystem.hxx"
#include "VPolarCoordinateSystem.hxx"
#include "ScaleAutomatism.hxx"
#include "VSeriesPlotter.hxx"
#include "ShapeFactory.hxx"
#include "servicenames_coosystems.hxx"
// header for define DBG_ASSERT
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
//static
VCoordinateSystem* VCoordinateSystem::createCoordinateSystem( const uno::Reference<
XBoundedCoordinateSystem >& xCooSysModel )
{
rtl::OUString aViewServiceName = xCooSysModel->getViewServiceName();
//@todo: in future the coordinatesystems should be instanciated via service factory
VCoordinateSystem* pRet=NULL;
if( aViewServiceName.equals( CHART2_COOSYSTEM_CARTESIAN_VIEW_SERVICE_NAME ) )
pRet = new VCartesianCoordinateSystem(xCooSysModel);
else if( aViewServiceName.equals( CHART2_COOSYSTEM_POLAR_VIEW_SERVICE_NAME ) )
pRet = new VPolarCoordinateSystem(xCooSysModel);
if(!pRet)
pRet = new VCoordinateSystem(xCooSysModel);
return pRet;
}
VCoordinateSystem::VCoordinateSystem( const uno::Reference< XBoundedCoordinateSystem >& xCooSys )
: m_xCooSysModel(xCooSys)
, m_xAxis0(NULL)
, m_xAxis1(NULL)
, m_xAxis2(NULL)
, m_xGridList0()
, m_xGridList1()
, m_xGridList2()
, m_aExplicitScales(3)
, m_aExplicitIncrements(3)
, m_xLogicTargetForGrids(0)
, m_xLogicTargetForAxes(0)
, m_xFinalTarget(0)
, m_xShapeFactory(0)
, m_aMatrixSceneToScreen()
{
}
VCoordinateSystem::~VCoordinateSystem()
{
}
void SAL_CALL VCoordinateSystem::initPlottingTargets( const uno::Reference< drawing::XShapes >& xLogicTarget
, const uno::Reference< drawing::XShapes >& xFinalTarget
, const uno::Reference< lang::XMultiServiceFactory >& xShapeFactory )
throw (uno::RuntimeException)
{
DBG_ASSERT(xLogicTarget.is()&&xFinalTarget.is()&&xShapeFactory.is(),"no proper initialization parameters");
//is only allowed to be called once
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
//create group shape for grids first thus axes are always painted above grids
ShapeFactory aShapeFactory(xShapeFactory);
if(nDimensionCount==2)
{
//create and add to target
m_xLogicTargetForGrids = aShapeFactory.createGroup2D( xLogicTarget );
m_xLogicTargetForAxes = aShapeFactory.createGroup2D( xLogicTarget );
}
else
{
//create and added to target
m_xLogicTargetForGrids = aShapeFactory.createGroup3D( xLogicTarget );
m_xLogicTargetForAxes = aShapeFactory.createGroup3D( xLogicTarget );
}
m_xFinalTarget = xFinalTarget;
m_xShapeFactory = xShapeFactory;
}
void VCoordinateSystem::setOrigin( double* fCoordinateOrigin )
{
m_fCoordinateOrigin[0]=fCoordinateOrigin[0];
m_fCoordinateOrigin[1]=fCoordinateOrigin[1];
m_fCoordinateOrigin[2]=fCoordinateOrigin[2];
}
void VCoordinateSystem::setTransformationSceneToScreen(
const drawing::HomogenMatrix& rMatrix )
{
m_aMatrixSceneToScreen = rMatrix;
}
uno::Reference< XBoundedCoordinateSystem > VCoordinateSystem::getModel() const
{
return m_xCooSysModel;
}
void VCoordinateSystem::addAxis( const uno::Reference< XAxis >& xAxis )
{
if(!xAxis.is())
return;
sal_Int32 nDim = xAxis->getRepresentedDimension();
if(0==nDim)
m_xAxis0 = xAxis;
else if(1==nDim)
m_xAxis1 = xAxis;
else if(2==nDim)
m_xAxis2 = xAxis;
}
uno::Sequence< uno::Reference< XGrid > >& VCoordinateSystem::getGridListByDimension( sal_Int32 nDim )
{
if( 0==nDim )
return m_xGridList0;
if( 1==nDim )
return m_xGridList1;
return m_xGridList2;
}
void VCoordinateSystem::addGrid( const uno::Reference< XGrid >& xGrid )
{
if(!xGrid.is())
return;
sal_Int32 nDim = xGrid->getRepresentedDimension();
uno::Sequence< uno::Reference< XGrid > >& rGridList
= getGridListByDimension( nDim );
rGridList.realloc(rGridList.getLength()+1);
rGridList[rGridList.getLength()-1] = xGrid;
}
uno::Reference< XAxis > VCoordinateSystem::getAxisByDimension( sal_Int32 nDim ) const
{
uno::Reference< XAxis > xAxis(NULL);
if(0==nDim)
xAxis = m_xAxis0;
else if(1==nDim)
xAxis = m_xAxis1;
else if(2==nDim)
xAxis = m_xAxis2;
return xAxis;
}
void setExplicitScaleToDefault( ExplicitScaleData& rExplicitScale )
{
rExplicitScale.Minimum = -0.5;
rExplicitScale.Maximum = 0.5;
rExplicitScale.Orientation = AxisOrientation_MATHEMATICAL;
//rExplicitScale.Scaling = ;
//rExplicitScale.Breaks = ;
}
void VCoordinateSystem::doAutoScale( MinimumAndMaximumSupplier* pMinMaxSupplier )
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
for( sal_Int32 nDim = 0; nDim < nDimensionCount; nDim++ )
{
uno::Reference< XScale > xScale(
m_xCooSysModel->getScaleByDimension( nDim ),
uno::UNO_QUERY );
if( ! xScale.is() )
continue;
ScaleAutomatism aScaleAutomatism( xScale->getScaleData() );
uno::Reference< XAxis > xAxis( this->getAxisByDimension(nDim) );
if(xAxis.is())
{
uno::Reference< XIncrement > xInc( xAxis->getIncrement() );
if( xInc.is() )
{
aScaleAutomatism.m_aSourceIncrement = xInc->getIncrementData();
aScaleAutomatism.m_aSourceSubIncrementList = xInc->getSubIncrements();
}
}
if(0==nDim)
{
if(pMinMaxSupplier)
{
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumX();
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumX();
}
}
else if(1==nDim)
{
if(pMinMaxSupplier)
{
const ExplicitScaleData& rScale = m_aExplicitScales[0];
//@todo iterate through all xSlots which belong to coordinate system dimension in this plotter
//and iterate through all plotter for this coordinate system dimension
sal_Int32 nXSlotIndex = 0;
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumYInRange(rScale.Minimum,rScale.Maximum);
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumYInRange(rScale.Minimum,rScale.Maximum);
}
}
else if(2==nDim)
{
if(pMinMaxSupplier)
{
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumZ();
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumZ();
}
}
aScaleAutomatism.calculateExplicitScaleAndIncrement(
m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
}
if(nDimensionCount<3)
setExplicitScaleToDefault(m_aExplicitScales[2]);
}
void VCoordinateSystem::createGridShapes()
{
}
void VCoordinateSystem::createAxesShapes( const ::com::sun::star::awt::Size& rReferenceSize, NumberFormatterWrapper* pNumberFormatterWrapper )
{
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.110); FILE MERGED 2005/09/05 18:43:40 rt 1.5.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VCoordinateSystem.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:39:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "VCoordinateSystem.hxx"
#include "VCartesianCoordinateSystem.hxx"
#include "VPolarCoordinateSystem.hxx"
#include "ScaleAutomatism.hxx"
#include "VSeriesPlotter.hxx"
#include "ShapeFactory.hxx"
#include "servicenames_coosystems.hxx"
// header for define DBG_ASSERT
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
//static
VCoordinateSystem* VCoordinateSystem::createCoordinateSystem( const uno::Reference<
XBoundedCoordinateSystem >& xCooSysModel )
{
rtl::OUString aViewServiceName = xCooSysModel->getViewServiceName();
//@todo: in future the coordinatesystems should be instanciated via service factory
VCoordinateSystem* pRet=NULL;
if( aViewServiceName.equals( CHART2_COOSYSTEM_CARTESIAN_VIEW_SERVICE_NAME ) )
pRet = new VCartesianCoordinateSystem(xCooSysModel);
else if( aViewServiceName.equals( CHART2_COOSYSTEM_POLAR_VIEW_SERVICE_NAME ) )
pRet = new VPolarCoordinateSystem(xCooSysModel);
if(!pRet)
pRet = new VCoordinateSystem(xCooSysModel);
return pRet;
}
VCoordinateSystem::VCoordinateSystem( const uno::Reference< XBoundedCoordinateSystem >& xCooSys )
: m_xCooSysModel(xCooSys)
, m_xAxis0(NULL)
, m_xAxis1(NULL)
, m_xAxis2(NULL)
, m_xGridList0()
, m_xGridList1()
, m_xGridList2()
, m_aExplicitScales(3)
, m_aExplicitIncrements(3)
, m_xLogicTargetForGrids(0)
, m_xLogicTargetForAxes(0)
, m_xFinalTarget(0)
, m_xShapeFactory(0)
, m_aMatrixSceneToScreen()
{
}
VCoordinateSystem::~VCoordinateSystem()
{
}
void SAL_CALL VCoordinateSystem::initPlottingTargets( const uno::Reference< drawing::XShapes >& xLogicTarget
, const uno::Reference< drawing::XShapes >& xFinalTarget
, const uno::Reference< lang::XMultiServiceFactory >& xShapeFactory )
throw (uno::RuntimeException)
{
DBG_ASSERT(xLogicTarget.is()&&xFinalTarget.is()&&xShapeFactory.is(),"no proper initialization parameters");
//is only allowed to be called once
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
//create group shape for grids first thus axes are always painted above grids
ShapeFactory aShapeFactory(xShapeFactory);
if(nDimensionCount==2)
{
//create and add to target
m_xLogicTargetForGrids = aShapeFactory.createGroup2D( xLogicTarget );
m_xLogicTargetForAxes = aShapeFactory.createGroup2D( xLogicTarget );
}
else
{
//create and added to target
m_xLogicTargetForGrids = aShapeFactory.createGroup3D( xLogicTarget );
m_xLogicTargetForAxes = aShapeFactory.createGroup3D( xLogicTarget );
}
m_xFinalTarget = xFinalTarget;
m_xShapeFactory = xShapeFactory;
}
void VCoordinateSystem::setOrigin( double* fCoordinateOrigin )
{
m_fCoordinateOrigin[0]=fCoordinateOrigin[0];
m_fCoordinateOrigin[1]=fCoordinateOrigin[1];
m_fCoordinateOrigin[2]=fCoordinateOrigin[2];
}
void VCoordinateSystem::setTransformationSceneToScreen(
const drawing::HomogenMatrix& rMatrix )
{
m_aMatrixSceneToScreen = rMatrix;
}
uno::Reference< XBoundedCoordinateSystem > VCoordinateSystem::getModel() const
{
return m_xCooSysModel;
}
void VCoordinateSystem::addAxis( const uno::Reference< XAxis >& xAxis )
{
if(!xAxis.is())
return;
sal_Int32 nDim = xAxis->getRepresentedDimension();
if(0==nDim)
m_xAxis0 = xAxis;
else if(1==nDim)
m_xAxis1 = xAxis;
else if(2==nDim)
m_xAxis2 = xAxis;
}
uno::Sequence< uno::Reference< XGrid > >& VCoordinateSystem::getGridListByDimension( sal_Int32 nDim )
{
if( 0==nDim )
return m_xGridList0;
if( 1==nDim )
return m_xGridList1;
return m_xGridList2;
}
void VCoordinateSystem::addGrid( const uno::Reference< XGrid >& xGrid )
{
if(!xGrid.is())
return;
sal_Int32 nDim = xGrid->getRepresentedDimension();
uno::Sequence< uno::Reference< XGrid > >& rGridList
= getGridListByDimension( nDim );
rGridList.realloc(rGridList.getLength()+1);
rGridList[rGridList.getLength()-1] = xGrid;
}
uno::Reference< XAxis > VCoordinateSystem::getAxisByDimension( sal_Int32 nDim ) const
{
uno::Reference< XAxis > xAxis(NULL);
if(0==nDim)
xAxis = m_xAxis0;
else if(1==nDim)
xAxis = m_xAxis1;
else if(2==nDim)
xAxis = m_xAxis2;
return xAxis;
}
void setExplicitScaleToDefault( ExplicitScaleData& rExplicitScale )
{
rExplicitScale.Minimum = -0.5;
rExplicitScale.Maximum = 0.5;
rExplicitScale.Orientation = AxisOrientation_MATHEMATICAL;
//rExplicitScale.Scaling = ;
//rExplicitScale.Breaks = ;
}
void VCoordinateSystem::doAutoScale( MinimumAndMaximumSupplier* pMinMaxSupplier )
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
for( sal_Int32 nDim = 0; nDim < nDimensionCount; nDim++ )
{
uno::Reference< XScale > xScale(
m_xCooSysModel->getScaleByDimension( nDim ),
uno::UNO_QUERY );
if( ! xScale.is() )
continue;
ScaleAutomatism aScaleAutomatism( xScale->getScaleData() );
uno::Reference< XAxis > xAxis( this->getAxisByDimension(nDim) );
if(xAxis.is())
{
uno::Reference< XIncrement > xInc( xAxis->getIncrement() );
if( xInc.is() )
{
aScaleAutomatism.m_aSourceIncrement = xInc->getIncrementData();
aScaleAutomatism.m_aSourceSubIncrementList = xInc->getSubIncrements();
}
}
if(0==nDim)
{
if(pMinMaxSupplier)
{
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumX();
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumX();
}
}
else if(1==nDim)
{
if(pMinMaxSupplier)
{
const ExplicitScaleData& rScale = m_aExplicitScales[0];
//@todo iterate through all xSlots which belong to coordinate system dimension in this plotter
//and iterate through all plotter for this coordinate system dimension
sal_Int32 nXSlotIndex = 0;
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumYInRange(rScale.Minimum,rScale.Maximum);
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumYInRange(rScale.Minimum,rScale.Maximum);
}
}
else if(2==nDim)
{
if(pMinMaxSupplier)
{
aScaleAutomatism.m_fValueMinimum = pMinMaxSupplier->getMinimumZ();
aScaleAutomatism.m_fValueMaximum = pMinMaxSupplier->getMaximumZ();
}
}
aScaleAutomatism.calculateExplicitScaleAndIncrement(
m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
}
if(nDimensionCount<3)
setExplicitScaleToDefault(m_aExplicitScales[2]);
}
void VCoordinateSystem::createGridShapes()
{
}
void VCoordinateSystem::createAxesShapes( const ::com::sun::star::awt::Size& rReferenceSize, NumberFormatterWrapper* pNumberFormatterWrapper )
{
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>
|
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <mrpt/config/CConfigFile.h>
#include <mrpt/io/CFileGZInputStream.h>
#include <mrpt/maps/CMultiMetricMap.h>
#include <mrpt/maps/COccupancyGridMap2D.h>
#include <mrpt/maps/CSimpleMap.h>
#include <mrpt/random.h>
#include <mrpt/ros1bridge/map.h>
#include <mrpt/ros1bridge/pose.h>
#include <mrpt/serialization/CArchive.h>
#include <mrpt/system/filesystem.h> // for fileExists()
#include <mrpt/system/string_utils.h> // for lowerCase()
#include <mrpt/version.h>
#include <nav_msgs/OccupancyGrid.h>
#include <ros/console.h>
using namespace mrpt::config;
using namespace mrpt::io;
using mrpt::maps::CLogOddsGridMapLUT;
using mrpt::maps::CMultiMetricMap;
using mrpt::maps::COccupancyGridMap2D;
using mrpt::maps::CSimpleMap;
#ifndef INT8_MAX // avoid duplicated #define's
#define INT8_MAX 0x7f
#define INT8_MIN (-INT8_MAX - 1)
#define INT16_MAX 0x7fff
#define INT16_MIN (-INT16_MAX - 1)
#endif // INT8_MAX
namespace mrpt::ros1bridge
{
MapHdl::MapHdl()
{
// MRPT -> ROS LUT:
CLogOddsGridMapLUT<COccupancyGridMap2D::cellType> table;
#ifdef OCCUPANCY_GRIDMAP_CELL_SIZE_8BITS
const int i_min = INT8_MIN, i_max = INT8_MAX;
#else
const int i_min = INT16_MIN, i_max = INT16_MAX;
#endif
for (int i = i_min; i <= i_max; i++)
{
int8_t ros_val;
if (i == 0)
{
// Unknown cell (no evidence data):
ros_val = -1;
}
else
{
float p = 1.0 - table.l2p(i);
ros_val = round(p * 100.);
// printf("- cell -> ros = %4i -> %4i, p=%4.3f\n", i, ros_val, p);
}
lut_cellmrpt2ros[static_cast<int>(i) - i_min] = ros_val;
}
// ROS -> MRPT: [0,100] ->
for (int i = 0; i <= 100; i++)
{
const float p = 1.0 - (i / 100.0);
lut_cellros2mrpt[i] = table.p2l(p);
// printf("- ros->cell=%4i->%4i p=%4.3f\n",i, lut_cellros2mrpt[i], p);
}
}
MapHdl* MapHdl::instance()
{
static MapHdl m; // singeleton instance
return &m;
}
bool fromROS(const nav_msgs::OccupancyGrid& src, COccupancyGridMap2D& des)
{
MRPT_START
if ((src.info.origin.orientation.x != 0) ||
(src.info.origin.orientation.y != 0) ||
(src.info.origin.orientation.z != 0) ||
(src.info.origin.orientation.w != 1))
{
std::cerr << "[fromROS] Rotated maps are not supported!\n";
return false;
}
float xmin = src.info.origin.position.x;
float ymin = src.info.origin.position.y;
float xmax = xmin + src.info.width * src.info.resolution;
float ymax = ymin + src.info.height * src.info.resolution;
des.setSize(xmin, xmax, ymin, ymax, src.info.resolution);
auto inst = MapHdl::instance();
for (unsigned int h = 0; h < src.info.height; h++)
{
COccupancyGridMap2D::cellType* pDes = des.getRow(h);
const int8_t* pSrc = &src.data[h * src.info.width];
for (unsigned int w = 0; w < src.info.width; w++)
*pDes++ = inst->cellRos2Mrpt(*pSrc++);
}
return true;
MRPT_END
}
bool toROS(
const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des,
const std_msgs::Header& header)
{
des.header = header;
return toROS(src, des);
}
bool toROS(const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des)
{
des.info.width = src.getSizeX();
des.info.height = src.getSizeY();
des.info.resolution = src.getResolution();
des.info.origin.position.x = src.getXMin();
des.info.origin.position.y = src.getYMin();
des.info.origin.position.z = 0;
des.info.origin.orientation.x = 0;
des.info.origin.orientation.y = 0;
des.info.origin.orientation.z = 0;
des.info.origin.orientation.w = 1;
// I hope the data is always aligned
des.data.resize(des.info.width * des.info.height);
for (unsigned int h = 0; h < des.info.height; h++)
{
const COccupancyGridMap2D::cellType* pSrc = src.getRow(h);
int8_t* pDes = &des.data[h * des.info.width];
for (unsigned int w = 0; w < des.info.width; w++)
{
*pDes++ = MapHdl::instance()->cellMrpt2Ros(*pSrc++);
}
}
return true;
}
bool MapHdl::loadMap(
CMultiMetricMap& _metric_map, const CConfigFileBase& _config_file,
const std::string& _map_file, const std::string& _section_name, bool _debug)
{
using namespace mrpt::maps;
TSetOfMetricMapInitializers mapInitializers;
mapInitializers.loadFromConfigFile(_config_file, _section_name);
CSimpleMap simpleMap;
// Load the set of metric maps to consider in the experiments:
_metric_map.setListOfMaps(mapInitializers);
if (_debug) mapInitializers.dumpToConsole();
#if MRPT_VERSION >= 0x199
auto& r = mrpt::random::getRandomGenerator();
#else
auto& r = mrpt::random::randomGenerator;
#endif
r.randomize();
if (_debug)
printf(
"%s, _map_file.size() = %zu\n", _map_file.c_str(),
_map_file.size());
// Load the map (if any):
if (_map_file.size() < 3)
{
if (_debug) printf("No mrpt map file!\n");
return false;
}
else
{
ASSERT_(mrpt::system::fileExists(_map_file));
// Detect file extension:
std::string mapExt =
mrpt::system::lowerCase(mrpt::system::extractFileExtension(
_map_file, true)); // Ignore possible .gz extensions
if (!mapExt.compare("simplemap"))
{
// It's a ".simplemap":
if (_debug) printf("Loading '.simplemap' file...");
CFileGZInputStream f(_map_file);
#if MRPT_VERSION >= 0x199
mrpt::serialization::archiveFrom(f) >> simpleMap;
#else
f >> simpleMap;
#endif
printf("Ok\n");
ASSERTMSG_(
simpleMap.size() > 0,
"Simplemap was aparently loaded OK, but it is empty!");
// Build metric map:
if (_debug) printf("Building metric map(s) from '.simplemap'...");
_metric_map.loadFromSimpleMap(simpleMap);
if (_debug) printf("Ok\n");
}
else if (!mapExt.compare("gridmap"))
{
// It's a ".gridmap":
if (_debug) printf("Loading gridmap from '.gridmap'...");
ASSERTMSG_(
#if MRPT_VERSION >= 0x199
_metric_map.countMapsByClass<COccupancyGridMap2D>() == 1,
#else
_metric_map.m_gridMaps.size() == 1,
#endif
"Error: Trying to load a gridmap into a multi-metric map "
"requires 1 gridmap member.");
CFileGZInputStream fm(_map_file);
#if MRPT_VERSION >= 0x199
mrpt::serialization::archiveFrom(fm) >>
(*_metric_map.mapByClass<COccupancyGridMap2D>());
#else
fm >> (*_metric_map.m_gridMaps[0]);
#endif
if (_debug) printf("Ok\n");
}
else
{
THROW_EXCEPTION(mrpt::format(
"Map file has unknown extension: '%s'", mapExt.c_str()));
return false;
}
}
return true;
}
} // namespace mrpt::ros1bridge
<commit_msg>remove useless code<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <mrpt/config/CConfigFile.h>
#include <mrpt/io/CFileGZInputStream.h>
#include <mrpt/maps/CMultiMetricMap.h>
#include <mrpt/maps/COccupancyGridMap2D.h>
#include <mrpt/maps/CSimpleMap.h>
#include <mrpt/ros1bridge/map.h>
#include <mrpt/ros1bridge/pose.h>
#include <mrpt/serialization/CArchive.h>
#include <mrpt/system/filesystem.h> // for fileExists()
#include <mrpt/system/string_utils.h> // for lowerCase()
#include <mrpt/version.h>
#include <nav_msgs/OccupancyGrid.h>
#include <ros/console.h>
using namespace mrpt::config;
using namespace mrpt::io;
using mrpt::maps::CLogOddsGridMapLUT;
using mrpt::maps::CMultiMetricMap;
using mrpt::maps::COccupancyGridMap2D;
using mrpt::maps::CSimpleMap;
#ifndef INT8_MAX // avoid duplicated #define's
#define INT8_MAX 0x7f
#define INT8_MIN (-INT8_MAX - 1)
#define INT16_MAX 0x7fff
#define INT16_MIN (-INT16_MAX - 1)
#endif // INT8_MAX
namespace mrpt::ros1bridge
{
MapHdl::MapHdl()
{
// MRPT -> ROS LUT:
CLogOddsGridMapLUT<COccupancyGridMap2D::cellType> table;
#ifdef OCCUPANCY_GRIDMAP_CELL_SIZE_8BITS
const int i_min = INT8_MIN, i_max = INT8_MAX;
#else
const int i_min = INT16_MIN, i_max = INT16_MAX;
#endif
for (int i = i_min; i <= i_max; i++)
{
int8_t ros_val;
if (i == 0)
{
// Unknown cell (no evidence data):
ros_val = -1;
}
else
{
float p = 1.0 - table.l2p(i);
ros_val = round(p * 100.);
// printf("- cell -> ros = %4i -> %4i, p=%4.3f\n", i, ros_val, p);
}
lut_cellmrpt2ros[static_cast<int>(i) - i_min] = ros_val;
}
// ROS -> MRPT: [0,100] ->
for (int i = 0; i <= 100; i++)
{
const float p = 1.0 - (i / 100.0);
lut_cellros2mrpt[i] = table.p2l(p);
// printf("- ros->cell=%4i->%4i p=%4.3f\n",i, lut_cellros2mrpt[i], p);
}
}
MapHdl* MapHdl::instance()
{
static MapHdl m; // singeleton instance
return &m;
}
bool fromROS(const nav_msgs::OccupancyGrid& src, COccupancyGridMap2D& des)
{
MRPT_START
if ((src.info.origin.orientation.x != 0) ||
(src.info.origin.orientation.y != 0) ||
(src.info.origin.orientation.z != 0) ||
(src.info.origin.orientation.w != 1))
{
std::cerr << "[fromROS] Rotated maps are not supported!\n";
return false;
}
float xmin = src.info.origin.position.x;
float ymin = src.info.origin.position.y;
float xmax = xmin + src.info.width * src.info.resolution;
float ymax = ymin + src.info.height * src.info.resolution;
des.setSize(xmin, xmax, ymin, ymax, src.info.resolution);
auto inst = MapHdl::instance();
for (unsigned int h = 0; h < src.info.height; h++)
{
COccupancyGridMap2D::cellType* pDes = des.getRow(h);
const int8_t* pSrc = &src.data[h * src.info.width];
for (unsigned int w = 0; w < src.info.width; w++)
*pDes++ = inst->cellRos2Mrpt(*pSrc++);
}
return true;
MRPT_END
}
bool toROS(
const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des,
const std_msgs::Header& header)
{
des.header = header;
return toROS(src, des);
}
bool toROS(const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des)
{
des.info.width = src.getSizeX();
des.info.height = src.getSizeY();
des.info.resolution = src.getResolution();
des.info.origin.position.x = src.getXMin();
des.info.origin.position.y = src.getYMin();
des.info.origin.position.z = 0;
des.info.origin.orientation.x = 0;
des.info.origin.orientation.y = 0;
des.info.origin.orientation.z = 0;
des.info.origin.orientation.w = 1;
// I hope the data is always aligned
des.data.resize(des.info.width * des.info.height);
for (unsigned int h = 0; h < des.info.height; h++)
{
const COccupancyGridMap2D::cellType* pSrc = src.getRow(h);
int8_t* pDes = &des.data[h * des.info.width];
for (unsigned int w = 0; w < des.info.width; w++)
{
*pDes++ = MapHdl::instance()->cellMrpt2Ros(*pSrc++);
}
}
return true;
}
bool MapHdl::loadMap(
CMultiMetricMap& _metric_map, const CConfigFileBase& _config_file,
const std::string& _map_file, const std::string& _section_name, bool _debug)
{
using namespace mrpt::maps;
TSetOfMetricMapInitializers mapInitializers;
mapInitializers.loadFromConfigFile(_config_file, _section_name);
CSimpleMap simpleMap;
// Load the set of metric maps to consider in the experiments:
_metric_map.setListOfMaps(mapInitializers);
if (_debug) mapInitializers.dumpToConsole();
if (_debug)
printf(
"%s, _map_file.size() = %zu\n", _map_file.c_str(),
_map_file.size());
// Load the map (if any):
if (_map_file.size() < 3)
{
if (_debug) printf("No mrpt map file!\n");
return false;
}
else
{
ASSERT_(mrpt::system::fileExists(_map_file));
// Detect file extension:
std::string mapExt =
mrpt::system::lowerCase(mrpt::system::extractFileExtension(
_map_file, true)); // Ignore possible .gz extensions
if (!mapExt.compare("simplemap"))
{
// It's a ".simplemap":
if (_debug) printf("Loading '.simplemap' file...");
CFileGZInputStream f(_map_file);
#if MRPT_VERSION >= 0x199
mrpt::serialization::archiveFrom(f) >> simpleMap;
#else
f >> simpleMap;
#endif
printf("Ok\n");
ASSERTMSG_(
simpleMap.size() > 0,
"Simplemap was aparently loaded OK, but it is empty!");
// Build metric map:
if (_debug) printf("Building metric map(s) from '.simplemap'...");
_metric_map.loadFromSimpleMap(simpleMap);
if (_debug) printf("Ok\n");
}
else if (!mapExt.compare("gridmap"))
{
// It's a ".gridmap":
if (_debug) printf("Loading gridmap from '.gridmap'...");
ASSERTMSG_(
#if MRPT_VERSION >= 0x199
_metric_map.countMapsByClass<COccupancyGridMap2D>() == 1,
#else
_metric_map.m_gridMaps.size() == 1,
#endif
"Error: Trying to load a gridmap into a multi-metric map "
"requires 1 gridmap member.");
CFileGZInputStream fm(_map_file);
#if MRPT_VERSION >= 0x199
mrpt::serialization::archiveFrom(fm) >>
(*_metric_map.mapByClass<COccupancyGridMap2D>());
#else
fm >> (*_metric_map.m_gridMaps[0]);
#endif
if (_debug) printf("Ok\n");
}
else
{
THROW_EXCEPTION(mrpt::format(
"Map file has unknown extension: '%s'", mapExt.c_str()));
return false;
}
}
return true;
}
} // namespace mrpt::ros1bridge
<|endoftext|>
|
<commit_before>#include <mantella_bits/helper/assert.hpp>
// C++ standard library
#include <cstdlib>
namespace mant {
void verify(
const bool expression,
const std::string& errorMessage) {
if(!expression) {
throw std::logic_error(errorMessage);
}
}
bool isRotationMatrix(
const arma::Mat<double>& rotationMatrixCandidate) {
// Is the rotation matrix square?
if (!rotationMatrixCandidate.is_square()) {
return false;
}
// Is its determinant either 1 or -1?
if(std::abs(std::abs(arma::det(rotationMatrixCandidate)) - 1.0) > 1.0e-12) {
return false;
}
// Is its transpose also its inverse?
// For (nearly) singular matrices, the inversion might throw an exception.
try {
if(arma::any(arma::vectorise(arma::abs(parameter.i() - parameter.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(parameter))))))) {
return false;
}
} catch (...) {
return false;
}
return true;
}
bool isPermutation(
const arma::Col<arma::uword>& permutationCandidate,
const arma::uword numberOfPermutations,
const arma::uword numberOfElements) {
// Are there as many permutations as expected?
if (permutationCandidate.n_elem != numberOfPermutations) {
return false;
}
// Are all elements within [0, numberOfElements - 1]?
if (arma::any(permutationCandidate < 0) || arma::any(permutationCandidate > numberOfElements - 1)) {
return false;
}
// Are all elements unique?
if (static_cast<arma::Col<arma::uword>>(arma::unique(permutationCandidate)).n_elem != permutationCandidate.n_elem) {
return false;
}
return true;
}
bool isDimensionallyConsistent(
const std::unordered_map<arma::Col<double>, double, Hash, IsEqual>& samples) {
const arma::uword numberOfDimensions = samples.cbegin()->first.n_elem;
for (const auto& sample : samples) {
if (sample.first.n_elem != numberOfDimensions) {
return false;
}
}
return true;
}
}
<commit_msg>Added (redundant) precheck, to improve some corner cases<commit_after>#include <mantella_bits/helper/assert.hpp>
// C++ standard library
#include <cstdlib>
namespace mant {
void verify(
const bool expression,
const std::string& errorMessage) {
if(!expression) {
throw std::logic_error(errorMessage);
}
}
bool isRotationMatrix(
const arma::Mat<double>& rotationMatrixCandidate) {
// Is the rotation matrix square?
if (!rotationMatrixCandidate.is_square()) {
return false;
}
// Is its determinant either 1 or -1?
if(std::abs(std::abs(arma::det(rotationMatrixCandidate)) - 1.0) > 1.0e-12) {
return false;
}
// Is its transpose also its inverse?
// For (nearly) singular matrices, the inversion might throw an exception.
try {
if(arma::any(arma::vectorise(arma::abs(parameter.i() - parameter.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(parameter))))))) {
return false;
}
} catch (...) {
return false;
}
return true;
}
bool isPermutation(
const arma::Col<arma::uword>& permutationCandidate,
const arma::uword numberOfPermutations,
const arma::uword numberOfElements) {
// Are there as more permutations than elements?
if (numberOfPermutations > numberOfElements) {
return false;
}
// Are there as many permutations as expected?
if (permutationCandidate.n_elem != numberOfPermutations) {
return false;
}
// Are all elements within [0, numberOfElements - 1]?
if (arma::any(permutationCandidate < 0) || arma::any(permutationCandidate > numberOfElements - 1)) {
return false;
}
// Are all elements unique?
if (static_cast<arma::Col<arma::uword>>(arma::unique(permutationCandidate)).n_elem != permutationCandidate.n_elem) {
return false;
}
return true;
}
bool isDimensionallyConsistent(
const std::unordered_map<arma::Col<double>, double, Hash, IsEqual>& samples) {
const arma::uword numberOfDimensions = samples.cbegin()->first.n_elem;
for (const auto& sample : samples) {
if (sample.first.n_elem != numberOfDimensions) {
return false;
}
}
return true;
}
}
<|endoftext|>
|
<commit_before>#include "renderer/pose.h"
#include "engine/math.h"
#include "engine/profiler.h"
#include "engine/math.h"
#include "renderer/model.h"
namespace Lumix
{
Pose::Pose(IAllocator& allocator)
: allocator(allocator)
{
positions = nullptr;
rotations = nullptr;
count = 0;
is_absolute = false;
}
Pose::~Pose()
{
allocator.deallocate(positions);
allocator.deallocate(rotations);
}
void Pose::blend(Pose& rhs, float weight)
{
ASSERT(count == rhs.count);
if (weight <= 0.001f) return;
weight = clamp(weight, 0.0f, 1.0f);
float inv = 1.0f - weight;
for (int i = 0, c = count; i < c; ++i)
{
positions[i] = positions[i] * inv + rhs.positions[i] * weight;
rotations[i] = nlerp(rotations[i], rhs.rotations[i], weight);
}
}
void Pose::resize(int count)
{
is_absolute = false;
allocator.deallocate(positions);
allocator.deallocate(rotations);
this->count = count;
if (count)
{
positions = static_cast<Vec3*>(allocator.allocate(sizeof(Vec3) * count));
rotations = static_cast<Quat*>(allocator.allocate(sizeof(Quat) * count));
}
else
{
positions = nullptr;
rotations = nullptr;
}
}
void Pose::computeAbsolute(Model& model)
{
if (is_absolute) return;
for (u32 i = model.getFirstNonrootBoneIndex(); i < count; ++i)
{
int parent = model.getBone(i).parent_idx;
positions[i] = rotations[parent].rotate(positions[i]) + positions[parent];
rotations[i] = rotations[parent] * rotations[i];
}
is_absolute = true;
}
void Pose::computeRelative(Model& model)
{
if (!is_absolute) return;
for (int i = count - 1; i >= model.getFirstNonrootBoneIndex(); --i)
{
int parent = model.getBone(i).parent_idx;
positions[i] = -rotations[parent].conjugated().rotate(positions[i] - positions[parent]);
rotations[i] = rotations[parent].conjugated() * rotations[i];
}
is_absolute = false;
}
} // namespace Lumix
<commit_msg>forgotten minus<commit_after>#include "renderer/pose.h"
#include "engine/math.h"
#include "engine/profiler.h"
#include "engine/math.h"
#include "renderer/model.h"
namespace Lumix
{
Pose::Pose(IAllocator& allocator)
: allocator(allocator)
{
positions = nullptr;
rotations = nullptr;
count = 0;
is_absolute = false;
}
Pose::~Pose()
{
allocator.deallocate(positions);
allocator.deallocate(rotations);
}
void Pose::blend(Pose& rhs, float weight)
{
ASSERT(count == rhs.count);
if (weight <= 0.001f) return;
weight = clamp(weight, 0.0f, 1.0f);
float inv = 1.0f - weight;
for (int i = 0, c = count; i < c; ++i)
{
positions[i] = positions[i] * inv + rhs.positions[i] * weight;
rotations[i] = nlerp(rotations[i], rhs.rotations[i], weight);
}
}
void Pose::resize(int count)
{
is_absolute = false;
allocator.deallocate(positions);
allocator.deallocate(rotations);
this->count = count;
if (count)
{
positions = static_cast<Vec3*>(allocator.allocate(sizeof(Vec3) * count));
rotations = static_cast<Quat*>(allocator.allocate(sizeof(Quat) * count));
}
else
{
positions = nullptr;
rotations = nullptr;
}
}
void Pose::computeAbsolute(Model& model)
{
if (is_absolute) return;
for (u32 i = model.getFirstNonrootBoneIndex(); i < count; ++i)
{
int parent = model.getBone(i).parent_idx;
positions[i] = rotations[parent].rotate(positions[i]) + positions[parent];
rotations[i] = rotations[parent] * rotations[i];
}
is_absolute = true;
}
void Pose::computeRelative(Model& model)
{
if (!is_absolute) return;
for (int i = count - 1; i >= model.getFirstNonrootBoneIndex(); --i)
{
int parent = model.getBone(i).parent_idx;
positions[i] = rotations[parent].conjugated().rotate(positions[i] - positions[parent]);
rotations[i] = rotations[parent].conjugated() * rotations[i];
}
is_absolute = false;
}
} // namespace Lumix
<|endoftext|>
|
<commit_before>#include "test_compiler.hpp"
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
#include <regex>
#include <sstream>
#include <thread>
#include <mettle/driver/scoped_pipe.hpp>
#include <mettle/output.hpp>
#include "paths.hpp"
namespace caliber {
namespace {
constexpr int err_timeout = 64;
}
std::unique_ptr<char *[]>
make_argv(const std::vector<std::string> &argv) {
auto real_argv = std::make_unique<char *[]>(argv.size() + 1);
for(size_t i = 0; i != argv.size(); i++)
real_argv[i] = const_cast<char*>(argv[i].c_str());
return real_argv;
}
inline std::string err_string(int errnum) {
char buf[256];
#ifdef _GNU_SOURCE
return strerror_r(errnum, buf, sizeof(buf));
#else
if(strerror_r(errnum, buf, sizeof(buf)) < 0)
return "";
return buf;
#endif
}
inline mettle::test_result parent_failed() {
return { false, err_string(errno) };
}
[[noreturn]] inline void child_failed() {
_exit(128);
}
std::string tool::tool_name(const std::string &filename) {
std::unique_ptr<char, void (*)(void*)> linkname(
realpath(which(filename).c_str(), nullptr),
std::free
);
if(!linkname)
throw std::system_error(errno, std::system_category());
return leafname(linkname.get());
}
bool is_cxx(const std::string &file) {
static std::regex cxx_re("\\.(cc|cp|cxx|cpp|CPP|c\\+\\+|C|ii|mm|M|mii)$");
return std::regex_search(file, cxx_re);
}
std::vector<std::string>
translate_args(const compiler_args &args, const std::string &path) {
// XXX: This will eventually need to support different compiler front-ends.
std::vector<std::string> result;
for(const auto &arg : args){
if(arg.string_key == "std") {
result.push_back("-std=" + arg.value.front());
}
else if(arg.string_key == "-I") {
result.push_back("-I");
result.push_back(path + arg.value.front());
}
else {
result.push_back(arg.string_key);
result.insert(result.end(), arg.value.begin(), arg.value.end());
}
}
return result;
}
mettle::test_result
test_compiler::operator ()(
const std::string &file, const compiler_args &args, bool expect_fail,
mettle::log::test_output &output
) const {
mettle::scoped_pipe stdout_pipe, stderr_pipe;
if(stdout_pipe.open() < 0 ||
stderr_pipe.open() < 0)
return parent_failed();
fflush(nullptr);
std::string dir = parent_path(file);
const auto &compiler = is_cxx(file) ? cxx_ : cc_;
std::vector<std::string> final_args = {
compiler.path.c_str(), "-fsyntax-only", file
};
for(auto &&tok : translate_args(args, dir))
final_args.push_back(std::move(tok));
pid_t pid;
if((pid = fork()) < 0)
return parent_failed();
if(pid == 0) {
if(timeout_)
fork_watcher(*timeout_);
// Make a new process group so we can kill the test and all its children
// as a group.
setpgid(0, 0);
if(timeout_)
kill(getppid(), SIGUSR1);
if(stdout_pipe.close_read() < 0 ||
stderr_pipe.close_read() < 0)
child_failed();
if(stdout_pipe.write_fd != STDOUT_FILENO) {
if(dup2(stdout_pipe.write_fd, STDOUT_FILENO) < 0)
child_failed();
if(stdout_pipe.close_write() < 0)
child_failed();
}
if(stderr_pipe.write_fd != STDERR_FILENO) {
if(dup2(stderr_pipe.write_fd, STDERR_FILENO) < 0)
child_failed();
if(stderr_pipe.close_write() < 0)
child_failed();
}
execvp(compiler.path.c_str(), make_argv(final_args).get());
child_failed();
}
else {
if(stdout_pipe.close_write() < 0 ||
stderr_pipe.close_write() < 0)
return parent_failed();
ssize_t size;
char buf[BUFSIZ];
// Read from the piped stdout and stderr.
int rv;
pollfd fds[2] = { {stdout_pipe.read_fd, POLLIN, 0},
{stderr_pipe.read_fd, POLLIN, 0} };
std::string *dests[] = {&output.stdout, &output.stderr};
int open_fds = 2;
while(open_fds && (rv = poll(fds, 2, -1)) > 0) {
for(size_t i = 0; i < 2; i++) {
if(fds[i].revents & POLLIN) {
if((size = read(fds[i].fd, buf, sizeof(buf))) < 0)
return parent_failed();
dests[i]->append(buf, size);
}
if(fds[i].revents & POLLHUP) {
fds[i].fd = -fds[i].fd;
open_fds--;
}
}
}
if(rv < 0) // poll() failed!
return parent_failed();
int status;
if(waitpid(pid, &status, 0) < 0)
return parent_failed();
if(WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
if(exit_code == err_timeout) {
std::ostringstream ss;
ss << "Timed out after " << timeout_->count() << " ms";
return { false, ss.str() };
}
else if(bool(exit_code) == expect_fail) {
return { true, "" };
}
else if(exit_code) {
return { false, "Compilation failed" };
}
else {
return { false, "Compilation successful" };
}
}
else if(WIFSIGNALED(status)) {
return { false, strsignal(WTERMSIG(status)) };
}
else { // WIFSTOPPED
kill(pid, SIGKILL);
return { false, strsignal(WSTOPSIG(status)) };
}
}
}
void test_compiler::fork_watcher(std::chrono::milliseconds timeout) {
pid_t watcher_pid;
if((watcher_pid = fork()) < 0)
child_failed();
if(watcher_pid == 0) {
std::this_thread::sleep_for(timeout);
_exit(err_timeout);
}
// The test process will signal us when it's ok to proceed (i.e. once it's
// created a new process group). Set up a signal mask to wait for it.
sigset_t mask, oldmask;
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_BLOCK, &mask, &oldmask);
pid_t test_pid;
if((test_pid = fork()) < 0) {
kill(watcher_pid, SIGKILL);
child_failed();
}
if(test_pid != 0) {
// Wait for the first child process (the watcher or the test) to finish,
// then kill and wait for the other one.
int status;
pid_t exited_pid = wait(&status);
if(exited_pid == test_pid) {
kill(watcher_pid, SIGKILL);
}
else {
// Wait until the test process has created its process group.
int sig;
sigwait(&mask, &sig);
kill(-test_pid, SIGKILL);
}
wait(nullptr);
if(WIFEXITED(status)) {
_exit(WEXITSTATUS(status));
}
else if(WIFSIGNALED(status)) {
raise(WTERMSIG(status));
}
else { // WIFSTOPPED
kill(exited_pid, SIGKILL);
raise(WSTOPSIG(status));
}
}
else {
sigprocmask(SIG_SETMASK, &oldmask, nullptr);
}
}
} // namespace caliber
<commit_msg>Use the new scoped_pipe::move_write function for dup2-and-closing an fd<commit_after>#include "test_compiler.hpp"
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
#include <regex>
#include <sstream>
#include <thread>
#include <mettle/driver/scoped_pipe.hpp>
#include <mettle/output.hpp>
#include "paths.hpp"
namespace caliber {
namespace {
constexpr int err_timeout = 64;
}
std::unique_ptr<char *[]>
make_argv(const std::vector<std::string> &argv) {
auto real_argv = std::make_unique<char *[]>(argv.size() + 1);
for(size_t i = 0; i != argv.size(); i++)
real_argv[i] = const_cast<char*>(argv[i].c_str());
return real_argv;
}
inline std::string err_string(int errnum) {
char buf[256];
#ifdef _GNU_SOURCE
return strerror_r(errnum, buf, sizeof(buf));
#else
if(strerror_r(errnum, buf, sizeof(buf)) < 0)
return "";
return buf;
#endif
}
inline mettle::test_result parent_failed() {
return { false, err_string(errno) };
}
[[noreturn]] inline void child_failed() {
_exit(128);
}
std::string tool::tool_name(const std::string &filename) {
std::unique_ptr<char, void (*)(void*)> linkname(
realpath(which(filename).c_str(), nullptr),
std::free
);
if(!linkname)
throw std::system_error(errno, std::system_category());
return leafname(linkname.get());
}
bool is_cxx(const std::string &file) {
static std::regex cxx_re("\\.(cc|cp|cxx|cpp|CPP|c\\+\\+|C|ii|mm|M|mii)$");
return std::regex_search(file, cxx_re);
}
std::vector<std::string>
translate_args(const compiler_args &args, const std::string &path) {
// XXX: This will eventually need to support different compiler front-ends.
std::vector<std::string> result;
for(const auto &arg : args){
if(arg.string_key == "std") {
result.push_back("-std=" + arg.value.front());
}
else if(arg.string_key == "-I") {
result.push_back("-I");
result.push_back(path + arg.value.front());
}
else {
result.push_back(arg.string_key);
result.insert(result.end(), arg.value.begin(), arg.value.end());
}
}
return result;
}
mettle::test_result
test_compiler::operator ()(
const std::string &file, const compiler_args &args, bool expect_fail,
mettle::log::test_output &output
) const {
mettle::scoped_pipe stdout_pipe, stderr_pipe;
if(stdout_pipe.open() < 0 ||
stderr_pipe.open() < 0)
return parent_failed();
fflush(nullptr);
std::string dir = parent_path(file);
const auto &compiler = is_cxx(file) ? cxx_ : cc_;
std::vector<std::string> final_args = {
compiler.path.c_str(), "-fsyntax-only", file
};
for(auto &&tok : translate_args(args, dir))
final_args.push_back(std::move(tok));
pid_t pid;
if((pid = fork()) < 0)
return parent_failed();
if(pid == 0) {
if(timeout_)
fork_watcher(*timeout_);
// Make a new process group so we can kill the test and all its children
// as a group.
setpgid(0, 0);
if(timeout_)
kill(getppid(), SIGUSR1);
if(stdout_pipe.close_read() < 0 ||
stderr_pipe.close_read() < 0)
child_failed();
if(stdout_pipe.move_write(STDOUT_FILENO) < 0 ||
stderr_pipe.move_write(STDERR_FILENO) < 0)
child_failed();
execvp(compiler.path.c_str(), make_argv(final_args).get());
child_failed();
}
else {
if(stdout_pipe.close_write() < 0 ||
stderr_pipe.close_write() < 0)
return parent_failed();
ssize_t size;
char buf[BUFSIZ];
// Read from the piped stdout and stderr.
int rv;
pollfd fds[2] = { {stdout_pipe.read_fd, POLLIN, 0},
{stderr_pipe.read_fd, POLLIN, 0} };
std::string *dests[] = {&output.stdout, &output.stderr};
int open_fds = 2;
while(open_fds && (rv = poll(fds, 2, -1)) > 0) {
for(size_t i = 0; i < 2; i++) {
if(fds[i].revents & POLLIN) {
if((size = read(fds[i].fd, buf, sizeof(buf))) < 0)
return parent_failed();
dests[i]->append(buf, size);
}
if(fds[i].revents & POLLHUP) {
fds[i].fd = -fds[i].fd;
open_fds--;
}
}
}
if(rv < 0) // poll() failed!
return parent_failed();
int status;
if(waitpid(pid, &status, 0) < 0)
return parent_failed();
if(WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
if(exit_code == err_timeout) {
std::ostringstream ss;
ss << "Timed out after " << timeout_->count() << " ms";
return { false, ss.str() };
}
else if(bool(exit_code) == expect_fail) {
return { true, "" };
}
else if(exit_code) {
return { false, "Compilation failed" };
}
else {
return { false, "Compilation successful" };
}
}
else if(WIFSIGNALED(status)) {
return { false, strsignal(WTERMSIG(status)) };
}
else { // WIFSTOPPED
kill(pid, SIGKILL);
return { false, strsignal(WSTOPSIG(status)) };
}
}
}
void test_compiler::fork_watcher(std::chrono::milliseconds timeout) {
pid_t watcher_pid;
if((watcher_pid = fork()) < 0)
child_failed();
if(watcher_pid == 0) {
std::this_thread::sleep_for(timeout);
_exit(err_timeout);
}
// The test process will signal us when it's ok to proceed (i.e. once it's
// created a new process group). Set up a signal mask to wait for it.
sigset_t mask, oldmask;
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_BLOCK, &mask, &oldmask);
pid_t test_pid;
if((test_pid = fork()) < 0) {
kill(watcher_pid, SIGKILL);
child_failed();
}
if(test_pid != 0) {
// Wait for the first child process (the watcher or the test) to finish,
// then kill and wait for the other one.
int status;
pid_t exited_pid = wait(&status);
if(exited_pid == test_pid) {
kill(watcher_pid, SIGKILL);
}
else {
// Wait until the test process has created its process group.
int sig;
sigwait(&mask, &sig);
kill(-test_pid, SIGKILL);
}
wait(nullptr);
if(WIFEXITED(status)) {
_exit(WEXITSTATUS(status));
}
else if(WIFSIGNALED(status)) {
raise(WTERMSIG(status));
}
else { // WIFSTOPPED
kill(exited_pid, SIGKILL);
raise(WSTOPSIG(status));
}
}
else {
sigprocmask(SIG_SETMASK, &oldmask, nullptr);
}
}
} // namespace caliber
<|endoftext|>
|
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE state
#include <arpa/inet.h>
#include <boost/test/unit_test.hpp>
#include <sys/uio.h>
#include "peer.h"
#include "router.h"
#include "state.h"
static char send_buffer[100000];
extern "C" {
int send_message(struct peer *p, const char *rendered, size_t len)
{
memcpy(send_buffer, rendered, len);
return 0;
}
int add_io(struct peer *p)
{
return 0;
}
void remove_io(const struct peer *p)
{
return;
}
}
static cJSON *parse_send_buffer(void)
{
char *read_ptr = send_buffer;
const char *end_parse;
cJSON *root = cJSON_ParseWithOpts(read_ptr, &end_parse, 0);
return root;
}
static cJSON *create_response_from_message(cJSON *routed_message)
{
cJSON *id = cJSON_GetObjectItem(routed_message, "id");
cJSON *duplicated_id = cJSON_Duplicate(id, 1);
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(response, "id", duplicated_id);
cJSON *result = cJSON_CreateString("");
cJSON_AddItemToObject(response, "result", result);
return response;
}
static cJSON *get_result_from_response(cJSON *response)
{
cJSON *result = cJSON_GetObjectItem(response, "result");
if (result != NULL) {
return result;
}
cJSON *error = cJSON_GetObjectItem(response, "error");
if (error != NULL) {
return result;
}
return NULL;
}
struct F {
F()
{
create_state_hashtable();
p = alloc_peer(-1);
}
~F()
{
free_peer(p);
delete_state_hashtable();
}
struct peer *p;
};
static void check_invalid_params(cJSON *error)
{
cJSON *code = cJSON_GetObjectItem(error, "code");
BOOST_REQUIRE(code != NULL);
BOOST_CHECK(code->type == cJSON_Number);
BOOST_CHECK(code->valueint == -32602);
cJSON *message = cJSON_GetObjectItem(error, "message");
BOOST_REQUIRE(message != NULL);
BOOST_CHECK(message->type == cJSON_String);
BOOST_CHECK(strcmp(message->valuestring, "Invalid params") == 0);
}
BOOST_FIXTURE_TEST_CASE(add_state, F)
{
const char *path = "/foo/bar/";
int state_value = 12345;
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
struct state *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
}
BOOST_FIXTURE_TEST_CASE(add_duplicate_state, F)
{
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_CHECK(error == NULL);
error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_REQUIRE(error != NULL);
check_invalid_params(error);
cJSON_Delete(error);
cJSON_Delete(value);
}
BOOST_FIXTURE_TEST_CASE(delete_single_state, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == 0);
}
BOOST_FIXTURE_TEST_CASE(delete_nonexisting_state, F)
{
const char path[] = "/foo/bar/";
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == -1);
}
BOOST_FIXTURE_TEST_CASE(double_free_state, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == 0);
ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == -1);
}
BOOST_FIXTURE_TEST_CASE(change, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, path, new_value);
BOOST_CHECK(error == NULL);
cJSON_Delete(new_value);
struct state *s = get_state(path);
BOOST_CHECK(s->value->valueint == 4321);
}
BOOST_FIXTURE_TEST_CASE(change_wrong_path, F)
{
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, "/bar/foo/", new_value);
BOOST_CHECK(error != NULL);
cJSON_Delete(new_value);
check_invalid_params(error);
cJSON_Delete(error);
}
BOOST_FIXTURE_TEST_CASE(set, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
struct peer *set_peer = alloc_peer(-1);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "id", "request1");
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
cJSON *routed_message = parse_send_buffer();
cJSON *response = create_response_from_message(routed_message);
cJSON *result = get_result_from_response(response);
int ret = handle_routing_response(response, result, p);
BOOST_CHECK(ret == 0);
cJSON_Delete(routed_message);
cJSON_Delete(response);
free_peer(set_peer);
}
BOOST_FIXTURE_TEST_CASE(set_without_id_without_response, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
struct peer *set_peer = alloc_peer(-1);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
free_peer(set_peer);
}
BOOST_FIXTURE_TEST_CASE(set_without_id_with_response, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
struct peer *set_peer = alloc_peer(-1);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
cJSON *routed_message = parse_send_buffer();
cJSON *response = create_response_from_message(routed_message);
cJSON *result = get_result_from_response(response);
int ret = handle_routing_response(response, result, p);
BOOST_CHECK(ret == 0);
cJSON_Delete(routed_message);
cJSON_Delete(response);
free_peer(set_peer);
}
<commit_msg>Put set-peer allocation into fixture.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE state
#include <arpa/inet.h>
#include <boost/test/unit_test.hpp>
#include <sys/uio.h>
#include "peer.h"
#include "router.h"
#include "state.h"
static char send_buffer[100000];
extern "C" {
int send_message(struct peer *p, const char *rendered, size_t len)
{
memcpy(send_buffer, rendered, len);
return 0;
}
int add_io(struct peer *p)
{
return 0;
}
void remove_io(const struct peer *p)
{
return;
}
}
static cJSON *parse_send_buffer(void)
{
char *read_ptr = send_buffer;
const char *end_parse;
cJSON *root = cJSON_ParseWithOpts(read_ptr, &end_parse, 0);
return root;
}
static cJSON *create_response_from_message(cJSON *routed_message)
{
cJSON *id = cJSON_GetObjectItem(routed_message, "id");
cJSON *duplicated_id = cJSON_Duplicate(id, 1);
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(response, "id", duplicated_id);
cJSON *result = cJSON_CreateString("");
cJSON_AddItemToObject(response, "result", result);
return response;
}
static cJSON *get_result_from_response(cJSON *response)
{
cJSON *result = cJSON_GetObjectItem(response, "result");
if (result != NULL) {
return result;
}
cJSON *error = cJSON_GetObjectItem(response, "error");
if (error != NULL) {
return result;
}
return NULL;
}
struct F {
F()
{
create_state_hashtable();
p = alloc_peer(-1);
set_peer = alloc_peer(-1);
}
~F()
{
free_peer(set_peer);
free_peer(p);
delete_state_hashtable();
}
struct peer *p;
struct peer *set_peer;
};
static void check_invalid_params(cJSON *error)
{
cJSON *code = cJSON_GetObjectItem(error, "code");
BOOST_REQUIRE(code != NULL);
BOOST_CHECK(code->type == cJSON_Number);
BOOST_CHECK(code->valueint == -32602);
cJSON *message = cJSON_GetObjectItem(error, "message");
BOOST_REQUIRE(message != NULL);
BOOST_CHECK(message->type == cJSON_String);
BOOST_CHECK(strcmp(message->valuestring, "Invalid params") == 0);
}
BOOST_FIXTURE_TEST_CASE(add_state, F)
{
const char *path = "/foo/bar/";
int state_value = 12345;
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
struct state *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
}
BOOST_FIXTURE_TEST_CASE(add_duplicate_state, F)
{
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_CHECK(error == NULL);
error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_REQUIRE(error != NULL);
check_invalid_params(error);
cJSON_Delete(error);
cJSON_Delete(value);
}
BOOST_FIXTURE_TEST_CASE(delete_single_state, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == 0);
}
BOOST_FIXTURE_TEST_CASE(delete_nonexisting_state, F)
{
const char path[] = "/foo/bar/";
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == -1);
}
BOOST_FIXTURE_TEST_CASE(double_free_state, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
int ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == 0);
ret = remove_state_from_peer(p, path);
BOOST_CHECK(ret == -1);
}
BOOST_FIXTURE_TEST_CASE(change, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, path, new_value);
BOOST_CHECK(error == NULL);
cJSON_Delete(new_value);
struct state *s = get_state(path);
BOOST_CHECK(s->value->valueint == 4321);
}
BOOST_FIXTURE_TEST_CASE(change_wrong_path, F)
{
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, "/foo/bar/", value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, "/bar/foo/", new_value);
BOOST_CHECK(error != NULL);
cJSON_Delete(new_value);
check_invalid_params(error);
cJSON_Delete(error);
}
BOOST_FIXTURE_TEST_CASE(set, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "id", "request1");
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
cJSON *routed_message = parse_send_buffer();
cJSON *response = create_response_from_message(routed_message);
cJSON *result = get_result_from_response(response);
int ret = handle_routing_response(response, result, p);
BOOST_CHECK(ret == 0);
cJSON_Delete(routed_message);
cJSON_Delete(response);
}
BOOST_FIXTURE_TEST_CASE(set_without_id_without_response, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
}
BOOST_FIXTURE_TEST_CASE(set_without_id_with_response, F)
{
const char path[] = "/foo/bar/";
cJSON *value = cJSON_CreateNumber(1234);
cJSON *error = add_state_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
cJSON *set_request = cJSON_CreateObject();
cJSON_AddStringToObject(set_request, "method", "set");
cJSON *params = cJSON_CreateObject();
cJSON_AddStringToObject(params, "path", "/foo/bar/");
cJSON *new_value = cJSON_CreateNumber(4321);
cJSON_AddItemToObject(params, "value", new_value);
cJSON_AddItemToObject(set_request, "params", params);
error = set_state(set_peer, path, new_value, set_request);
cJSON_Delete(set_request);
BOOST_CHECK(error == (cJSON *)ROUTED_MESSAGE);
cJSON *routed_message = parse_send_buffer();
cJSON *response = create_response_from_message(routed_message);
cJSON *result = get_result_from_response(response);
int ret = handle_routing_response(response, result, p);
BOOST_CHECK(ret == 0);
cJSON_Delete(routed_message);
cJSON_Delete(response);
}
<|endoftext|>
|
<commit_before>/*
* (C) copyright 2011, Ismael Garcia, (U.Girona/ViRVIG, Spain & INRIA/ALICE, France)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/iterator/iterator_traits.h>
#include <thrust/distance.h>
#include <thrust/functional.h>
#include <thrust/find.h>
#include <libh/hash.h>
#include <libh/detail/backend/hash.h>
namespace libh
{
///////////////
// Key hashs //
///////////////
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
libhu::U32 &max_age)
{
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
bool constrained_hash_access,
T_HASH_FUNCTOR hf)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access,
libhu::U32 &max_age)
{
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
/////////////////////
// Key-Value hashs //
/////////////////////
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
bool constrained_hash_access = true;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
libhu::U32 &max_age)
{
bool constrained_hash_access = true;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access,
libhu::U32 &max_age)
{
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
} // end namespace libh
<commit_msg>Fix error constrained_hash_access<commit_after>/*
* (C) copyright 2011, Ismael Garcia, (U.Girona/ViRVIG, Spain & INRIA/ALICE, France)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/iterator/iterator_traits.h>
#include <thrust/distance.h>
#include <thrust/functional.h>
#include <thrust/find.h>
#include <libh/hash.h>
#include <libh/detail/backend/hash.h>
namespace libh
{
///////////////
// Key hashs //
///////////////
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
libhu::U32 &max_age)
{
bool constrained_hash_access = true;
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
bool constrained_hash_access,
T_HASH_FUNCTOR hf)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_HASH_FUNCTOR>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 hash_table_begin,
T_RAND_ACCESS_ITERATOR2 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access,
libhu::U32 &max_age)
{
libh::detail::backend::hash(keys_begin, keys_end, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
/////////////////////
// Key-Value hashs //
/////////////////////
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
bool constrained_hash_access = true;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
libhu::U32 &max_age)
{
bool constrained_hash_access = true;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access)
{
libhu::U32 max_age = hf.KEY_TYPE_MAX_AGE;
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
template<typename T_RAND_ACCESS_ITERATOR1,
typename T_RAND_ACCESS_ITERATOR2,
typename T_RAND_ACCESS_ITERATOR3,
typename T_HASH_FUNCTOR>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
T_RAND_ACCESS_ITERATOR1 keys_end,
T_RAND_ACCESS_ITERATOR2 values_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_begin,
T_RAND_ACCESS_ITERATOR3 hash_table_end,
T_HASH_FUNCTOR hf,
bool constrained_hash_access,
libhu::U32 &max_age)
{
libh::detail::backend::hash_by_key(keys_begin, keys_end, values_begin, hash_table_begin, hash_table_end, hf, constrained_hash_access, max_age);
}
} // end namespace libh
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "AstPrintDocs.h"
#include "AstToText.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "docs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// Open the directory to store the docs
// This is the final location for the output format (e.g. the html files.).
std::string docsOutputDir = (strlen(fDocsFolder) > 0) ? fDocsFolder : "docs";
// Root of the sphinx project and generated rst files. If
// --docs-save-sphinx is not specified, it will be a temp dir.
std::string docsTempDir = "";
std::string docsSphinxDir;
if (strlen(fDocsSphinxDir) > 0) {
docsSphinxDir = fDocsSphinxDir;
} else {
docsTempDir = makeTempDir("chpldoc-");
docsSphinxDir = docsTempDir;
}
// The location of intermediate rst files.
std::string docsRstDir;
if (fDocsTextOnly) {
// For text-only mode, the output and working location is the same.
docsRstDir = docsOutputDir;
} else {
// For rst mode, the working location is somewhere inside the temp dir.
docsRstDir = generateSphinxProject(docsSphinxDir);
}
// TODO: Check for errors here... (thomasvandoren, 2015-02-25)
mkdir(docsRstDir.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
mkdir(docsOutputDir.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsRstDir);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsSphinxDir, docsOutputDir);
}
if (docsTempDir.length() > 0) {
deleteDir(docsTempDir.c_str());
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
mkdir(otherHalf.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// Create the output dir under the docs output dir.
const char * sphinxDir = dirpath.c_str();
// Ensure output directory exists.
const char * mkdirCmd = astr("mkdir -p ", sphinxDir);
mysystem(mkdirCmd, "creating docs output dir");
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", sphinxDir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(sphinxDir, "/source/modules");
return std::string(moddir);
}
/*
* Invoke sphinx-build using sphinxDir to find conf.py and rst sources, and
* outputDir for generated html files.
*/
void generateSphinxOutput(std::string sphinxDir, std::string outputDir) {
// The virtualenv active and sphinx-build scripts are in:
// $CHPL_HOME/third-party/chpldoc-venv/install/$CHPL_TARGET_PLATFORM/chpldoc-virtualenv/bin/
const char * venvBinDir = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpdoc-virtualenv/bin/");
const char * activate = astr(venvBinDir, "activate");
const char * sphinxBuild = astr(venvBinDir, "sphinx-build");
// Run:
// . $activate &&
// sphinx-build -b html
// -d $sphinxDir/build/doctrees -W
// $sphinxDir/source $outputDir
const char * cmdPrefix = astr(". ", activate, " && ");
const char * cmd = astr(
cmdPrefix,
sphinxBuild, " -b html -d ",
sphinxDir.c_str(), "/build/doctrees -W ",
sphinxDir.c_str(), "/source ", outputDir.c_str());
mysystem(cmd, "building html output from chpldoc sphinx project");
printf("HTML files are at: %s\n", outputDir.c_str());
printf("Begin by opening index.html in a browser.\n");
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsWorkDir + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = filenameFromMod(mod, docsWorkDir);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<commit_msg>Improve messaging around chpldoc html output files.<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "AstPrintDocs.h"
#include "AstToText.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "docs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// Open the directory to store the docs
// This is the final location for the output format (e.g. the html files.).
std::string docsOutputDir;
if (strlen(fDocsFolder) > 0) {
docsOutputDir = fDocsFolder;
} else {
docsOutputDir = astr(getCwd(), "/docs");
}
// Root of the sphinx project and generated rst files. If
// --docs-save-sphinx is not specified, it will be a temp dir.
std::string docsTempDir = "";
std::string docsSphinxDir;
if (strlen(fDocsSphinxDir) > 0) {
docsSphinxDir = fDocsSphinxDir;
} else {
docsTempDir = makeTempDir("chpldoc-");
docsSphinxDir = docsTempDir;
}
// The location of intermediate rst files.
std::string docsRstDir;
if (fDocsTextOnly) {
// For text-only mode, the output and working location is the same.
docsRstDir = docsOutputDir;
} else {
// For rst mode, the working location is somewhere inside the temp dir.
docsRstDir = generateSphinxProject(docsSphinxDir);
}
// TODO: Check for errors here... (thomasvandoren, 2015-02-25)
mkdir(docsRstDir.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
mkdir(docsOutputDir.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsRstDir);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsSphinxDir, docsOutputDir);
}
if (docsTempDir.length() > 0) {
deleteDir(docsTempDir.c_str());
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
mkdir(otherHalf.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// Create the output dir under the docs output dir.
const char * sphinxDir = dirpath.c_str();
// Ensure output directory exists.
const char * mkdirCmd = astr("mkdir -p ", sphinxDir);
mysystem(mkdirCmd, "creating docs output dir");
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", sphinxDir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(sphinxDir, "/source/modules");
return std::string(moddir);
}
/*
* Invoke sphinx-build using sphinxDir to find conf.py and rst sources, and
* outputDir for generated html files.
*/
void generateSphinxOutput(std::string sphinxDir, std::string outputDir) {
// The virtualenv active and sphinx-build scripts are in:
// $CHPL_HOME/third-party/chpldoc-venv/install/$CHPL_TARGET_PLATFORM/chpldoc-virtualenv/bin/
const char * venvBinDir = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpdoc-virtualenv/bin/");
const char * activate = astr(venvBinDir, "activate");
const char * sphinxBuild = astr(venvBinDir, "sphinx-build");
// Run:
// . $activate &&
// sphinx-build -b html
// -d $sphinxDir/build/doctrees -W
// $sphinxDir/source $outputDir
const char * cmdPrefix = astr(". ", activate, " && ");
const char * cmd = astr(
cmdPrefix,
sphinxBuild, " -b html -d ",
sphinxDir.c_str(), "/build/doctrees -W ",
sphinxDir.c_str(), "/source ", outputDir.c_str());
mysystem(cmd, "building html output from chpldoc sphinx project");
printf("HTML files are at: %s\n", outputDir.c_str());
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsWorkDir + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = filenameFromMod(mod, docsWorkDir);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<|endoftext|>
|
<commit_before>// @(#)root/cont:$Name: $:$Id: TCollection.cxx,v 1.6 2000/09/08 16:11:03 rdm Exp $
// Author: Fons Rademakers 13/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Collection abstract base class. This class describes the base //
// protocol all collection classes have to implement. The ROOT //
// collection classes always store pointers to objects that inherit //
// from TObject. They never adopt the objects. Therefore, it is the //
// user's responsability to take care of deleting the actual objects //
// once they are not needed anymore. In exceptional cases, when the //
// user is 100% sure nothing else is referencing the objects in the //
// collection, one can delete all objects and the collection at the //
// same time using the Delete() function. //
// //
// Collections can be iterated using an iterator object (see //
// TIterator). Depending on the concrete collection class there may be //
// some additional methods of iterating. See the repective classes. //
// //
// TCollection inherits from TObject since we want to be able to have //
// collections of collections. //
// //
// In a later release the collections may become templatized. //
// //
//Begin_Html
/*
<img src="gif/tcollection_classtree.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
#include "TCollection.h"
#include "TClass.h"
#include "TROOT.h"
#include "TBrowser.h"
#include "TObjectTable.h"
TCollection *TCollection::fgCurrentCollection = 0;
TObjectTable *TCollection::fgGarbageCollection = 0;
Bool_t TCollection::fgEmptyingGarbage = kFALSE;
Int_t TCollection::fgGarbageStack = 0;
ClassImp(TCollection)
ClassImp(TIter)
//______________________________________________________________________________
void TCollection::AddAll(TCollection *col)
{
// Add all objects from collection col to this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Add(obj);
}
//______________________________________________________________________________
void TCollection::AddVector(TObject *va_(obj1), ...)
{
// Add all arguments to this collection.
va_list ap;
va_start(ap, va_(obj1));
TObject *obj;
Add(va_(obj1));
while ((obj = va_arg(ap, TObject *)))
Add(obj);
va_end(ap);
}
//______________________________________________________________________________
Bool_t TCollection::AssertClass(TClass *cl) const
{
// Make sure all objects in this collection inherit from class cl.
TObject *obj;
TIter next(this);
Bool_t error = kFALSE;
if (!cl) {
Error("AssertClass", "class == 0");
return kTRUE;
}
for (int i = 0; (obj = next()); i++)
if (!obj->InheritsFrom(cl)) {
Error("AssertClass", "element %d is not an instance of class %s (%s)",
i, cl->GetName(), obj->ClassName());
error = kTRUE;
}
return error;
}
//______________________________________________________________________________
void TCollection::Browse(TBrowser *b)
{
// Browse this collection (called by TBrowser).
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
TIter next(this);
TObject *obj;
if (b)
while ((obj = next())) b->Add(obj);
else
TObject::Browse(b);
}
//______________________________________________________________________________
void TCollection::Draw(Option_t *option)
{
// Draw all objects in this collection.
this->ForEach(TObject,Draw)(option);
}
//______________________________________________________________________________
void TCollection::Dump()
{
// Dump all objects in this collection.
this->ForEach(TObject,Dump)();
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const char *name) const
{
// Find an object in this collection using its name. Requires a sequential
// scan till the object has been found. Returns 0 if object with specified
// name is not found.
TIter next(this);
TObject *obj;
while ((obj = next()))
if (!strcmp(name, obj->GetName())) return obj;
return 0;
}
//______________________________________________________________________________
TObject *TCollection::operator()(const char *name) const
{
// Find an object in this collection by name.
return FindObject(name);
}
//______________________________________________________________________________
TObject *TCollection::FindObject(TObject *obj) const
{
// Find an object in this collection using the object's IsEqual()
// member function. Requires a sequential scan till the object has
// been found. Returns 0 if object is not found.
// Typically this function is overridden by a more efficient version
// in concrete collection classes (e.g. THashTable).
TIter next(this);
TObject *ob;
while ((ob = next()))
if (ob->IsEqual(obj)) return ob;
return 0;
}
//______________________________________________________________________________
Int_t TCollection::GrowBy(Int_t delta) const
{
// Increase the collection's capacity by delta slots.
if (delta < 0) {
Error("GrowBy", "delta < 0");
delta = Capacity();
}
return Capacity() + TMath::Range(2, kMaxInt - Capacity(), delta);
}
//______________________________________________________________________________
Bool_t TCollection::IsArgNull(const char *where, TObject *obj) const
{
// Returns true if object is a null pointer.
return obj ? kFALSE : (Error(where, "argument is a null pointer"), kTRUE);
}
//______________________________________________________________________________
void TCollection::ls(Option_t *option)
{
// List (ls) all objects in this collection.
this->ForEach(TObject,ls)(option);
}
//______________________________________________________________________________
void TCollection::Paint(Option_t *option)
{
// Paint all objects in this collection.
// this->ForEach(TObject,Paint)((Option_t *)TObjectPaint_nxt.GetOption());
this->ForEach(TObject,Paint)(option);
}
//______________________________________________________________________________
void TCollection::Print(Option_t *option)
{
// Print all objects in this collection.
this->ForEach(TObject,Print)(option);
}
//______________________________________________________________________________
void TCollection::RecursiveRemove(TObject *obj)
{
// Remove object from this collection and recursively remove the object
// from all other objects (and collections).
if (!obj) return;
// Scan list and remove obj in the list itself
while (Remove(obj))
;
// Scan again the list and invoke RecursiveRemove for all objects
TIter next(this);
TObject *object;
while ((object = next())) {
if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TCollection::RemoveAll(TCollection *col)
{
// Remove all objects in collection col from this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Remove(obj);
}
//_______________________________________________________________________
void TCollection::Streamer(TBuffer &b)
{
// Stream all objects in the collection to or from the I/O buffer.
Int_t nobjects;
TObject *obj;
if (b.IsReading()) {
Version_t v = b.ReadVersion();
if (v > 2)
TObject::Streamer(b);
if (v > 1)
fName.Streamer(b);
b >> nobjects;
for (Int_t i = 0; i < nobjects; i++) {
b >> obj;
Add(obj);
}
} else {
b.WriteVersion(TCollection::IsA());
TObject::Streamer(b);
fName.Streamer(b);
nobjects = GetSize();
b << nobjects;
TIter next(this);
while ((obj = next())) {
b << obj;
}
}
}
//______________________________________________________________________________
Int_t TCollection::Write(const char *name, Int_t option, Int_t bsize)
{
// Write all objects in this collection. By default all objects in
// the collection are written individually (each object gets its
// own key). Note, this is not recursive, collections in the collection
// are written with a single key. To write all objects using a single
// key specify a name and set option to TObject::kSingleKey (i.e. 1).
if ((option & kSingleKey)) {
return TObject::Write(name, option, bsize);
} else {
option &= ~kSingleKey;
Int_t nbytes = 0;
TIter next(this);
TObject *obj;
while ((obj = next())) {
nbytes += obj->Write(name, option, bsize);
}
return nbytes;
}
}
// -------------------- Static data members access -----------------------------
//______________________________________________________________________________
TCollection *TCollection::GetCurrentCollection()
{
return fgCurrentCollection;
}
//______________________________________________________________________________
void TCollection::SetCurrentCollection()
{
fgCurrentCollection = this;
}
//______________________________________________________________________________
void TCollection::StartGarbageCollection()
{
if (!fgGarbageCollection) {
fgGarbageCollection = new TObjectTable;
fgEmptyingGarbage = kFALSE;
fgGarbageStack = 0;
}
fgGarbageStack++;
}
//______________________________________________________________________________
void TCollection::EmptyGarbageCollection()
{
if (fgGarbageStack > 0) fgGarbageStack--;
if (fgGarbageCollection && fgGarbageStack == 0 && fgEmptyingGarbage == kFALSE) {
fgEmptyingGarbage = kTRUE;
fgGarbageCollection->Delete();
fgEmptyingGarbage = kFALSE;
SafeDelete(fgGarbageCollection);
}
}
//______________________________________________________________________________
void TCollection::GarbageCollect(TObject *obj)
{
if (fgGarbageCollection && !fgEmptyingGarbage) {
fgGarbageCollection->Add(obj);
} else
delete obj;
}
//______________________________________________________________________________
TIter::TIter(const TIter &iter)
{
// Copy a TIter. This involves allocating a new TIterator of the right
// sub class and assigning it with the original.
if (iter.fIterator) {
fIterator = iter.GetCollection()->MakeIterator();
fIterator->operator=(*iter.fIterator);
} else
fIterator = 0;
}
//______________________________________________________________________________
TIter &TIter::operator=(const TIter &rhs)
{
// Assigning an TIter to another. This involves allocatiing a new TIterator
// of the right sub class and assigning it with the original.
if (this != &rhs) {
if (rhs.fIterator) {
delete fIterator;
fIterator = rhs.GetCollection()->MakeIterator();
fIterator->operator=(*rhs.fIterator);
}
}
return *this;
}
<commit_msg>Use ByteCount option in TCollection::Streamer<commit_after>// @(#)root/cont:$Name: $:$Id: TCollection.cxx,v 1.7 2000/10/14 09:41:27 rdm Exp $
// Author: Fons Rademakers 13/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Collection abstract base class. This class describes the base //
// protocol all collection classes have to implement. The ROOT //
// collection classes always store pointers to objects that inherit //
// from TObject. They never adopt the objects. Therefore, it is the //
// user's responsability to take care of deleting the actual objects //
// once they are not needed anymore. In exceptional cases, when the //
// user is 100% sure nothing else is referencing the objects in the //
// collection, one can delete all objects and the collection at the //
// same time using the Delete() function. //
// //
// Collections can be iterated using an iterator object (see //
// TIterator). Depending on the concrete collection class there may be //
// some additional methods of iterating. See the repective classes. //
// //
// TCollection inherits from TObject since we want to be able to have //
// collections of collections. //
// //
// In a later release the collections may become templatized. //
// //
//Begin_Html
/*
<img src="gif/tcollection_classtree.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
#include "TCollection.h"
#include "TClass.h"
#include "TROOT.h"
#include "TBrowser.h"
#include "TObjectTable.h"
TCollection *TCollection::fgCurrentCollection = 0;
TObjectTable *TCollection::fgGarbageCollection = 0;
Bool_t TCollection::fgEmptyingGarbage = kFALSE;
Int_t TCollection::fgGarbageStack = 0;
ClassImp(TCollection)
ClassImp(TIter)
//______________________________________________________________________________
void TCollection::AddAll(TCollection *col)
{
// Add all objects from collection col to this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Add(obj);
}
//______________________________________________________________________________
void TCollection::AddVector(TObject *va_(obj1), ...)
{
// Add all arguments to this collection.
va_list ap;
va_start(ap, va_(obj1));
TObject *obj;
Add(va_(obj1));
while ((obj = va_arg(ap, TObject *)))
Add(obj);
va_end(ap);
}
//______________________________________________________________________________
Bool_t TCollection::AssertClass(TClass *cl) const
{
// Make sure all objects in this collection inherit from class cl.
TObject *obj;
TIter next(this);
Bool_t error = kFALSE;
if (!cl) {
Error("AssertClass", "class == 0");
return kTRUE;
}
for (int i = 0; (obj = next()); i++)
if (!obj->InheritsFrom(cl)) {
Error("AssertClass", "element %d is not an instance of class %s (%s)",
i, cl->GetName(), obj->ClassName());
error = kTRUE;
}
return error;
}
//______________________________________________________________________________
void TCollection::Browse(TBrowser *b)
{
// Browse this collection (called by TBrowser).
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
TIter next(this);
TObject *obj;
if (b)
while ((obj = next())) b->Add(obj);
else
TObject::Browse(b);
}
//______________________________________________________________________________
void TCollection::Draw(Option_t *option)
{
// Draw all objects in this collection.
this->ForEach(TObject,Draw)(option);
}
//______________________________________________________________________________
void TCollection::Dump()
{
// Dump all objects in this collection.
this->ForEach(TObject,Dump)();
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const char *name) const
{
// Find an object in this collection using its name. Requires a sequential
// scan till the object has been found. Returns 0 if object with specified
// name is not found.
TIter next(this);
TObject *obj;
while ((obj = next()))
if (!strcmp(name, obj->GetName())) return obj;
return 0;
}
//______________________________________________________________________________
TObject *TCollection::operator()(const char *name) const
{
// Find an object in this collection by name.
return FindObject(name);
}
//______________________________________________________________________________
TObject *TCollection::FindObject(TObject *obj) const
{
// Find an object in this collection using the object's IsEqual()
// member function. Requires a sequential scan till the object has
// been found. Returns 0 if object is not found.
// Typically this function is overridden by a more efficient version
// in concrete collection classes (e.g. THashTable).
TIter next(this);
TObject *ob;
while ((ob = next()))
if (ob->IsEqual(obj)) return ob;
return 0;
}
//______________________________________________________________________________
Int_t TCollection::GrowBy(Int_t delta) const
{
// Increase the collection's capacity by delta slots.
if (delta < 0) {
Error("GrowBy", "delta < 0");
delta = Capacity();
}
return Capacity() + TMath::Range(2, kMaxInt - Capacity(), delta);
}
//______________________________________________________________________________
Bool_t TCollection::IsArgNull(const char *where, TObject *obj) const
{
// Returns true if object is a null pointer.
return obj ? kFALSE : (Error(where, "argument is a null pointer"), kTRUE);
}
//______________________________________________________________________________
void TCollection::ls(Option_t *option)
{
// List (ls) all objects in this collection.
this->ForEach(TObject,ls)(option);
}
//______________________________________________________________________________
void TCollection::Paint(Option_t *option)
{
// Paint all objects in this collection.
// this->ForEach(TObject,Paint)((Option_t *)TObjectPaint_nxt.GetOption());
this->ForEach(TObject,Paint)(option);
}
//______________________________________________________________________________
void TCollection::Print(Option_t *option)
{
// Print all objects in this collection.
this->ForEach(TObject,Print)(option);
}
//______________________________________________________________________________
void TCollection::RecursiveRemove(TObject *obj)
{
// Remove object from this collection and recursively remove the object
// from all other objects (and collections).
if (!obj) return;
// Scan list and remove obj in the list itself
while (Remove(obj))
;
// Scan again the list and invoke RecursiveRemove for all objects
TIter next(this);
TObject *object;
while ((object = next())) {
if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TCollection::RemoveAll(TCollection *col)
{
// Remove all objects in collection col from this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Remove(obj);
}
//_______________________________________________________________________
void TCollection::Streamer(TBuffer &b)
{
// Stream all objects in the collection to or from the I/O buffer.
Int_t nobjects;
TObject *obj;
UInt_t R__s, R__c;
if (b.IsReading()) {
Version_t v = b.ReadVersion(&R__s, &R__c);
if (v > 2)
TObject::Streamer(b);
if (v > 1)
fName.Streamer(b);
b >> nobjects;
for (Int_t i = 0; i < nobjects; i++) {
b >> obj;
Add(obj);
}
b.CheckByteCount(R__s, R__c,TCollection::IsA());
} else {
R__c = b.WriteVersion(TCollection::IsA(), kTRUE);
TObject::Streamer(b);
fName.Streamer(b);
nobjects = GetSize();
b << nobjects;
TIter next(this);
while ((obj = next())) {
b << obj;
}
b.SetByteCount(R__c, kTRUE);
}
}
//______________________________________________________________________________
Int_t TCollection::Write(const char *name, Int_t option, Int_t bsize)
{
// Write all objects in this collection. By default all objects in
// the collection are written individually (each object gets its
// own key). Note, this is not recursive, collections in the collection
// are written with a single key. To write all objects using a single
// key specify a name and set option to TObject::kSingleKey (i.e. 1).
if ((option & kSingleKey)) {
return TObject::Write(name, option, bsize);
} else {
option &= ~kSingleKey;
Int_t nbytes = 0;
TIter next(this);
TObject *obj;
while ((obj = next())) {
nbytes += obj->Write(name, option, bsize);
}
return nbytes;
}
}
// -------------------- Static data members access -----------------------------
//______________________________________________________________________________
TCollection *TCollection::GetCurrentCollection()
{
return fgCurrentCollection;
}
//______________________________________________________________________________
void TCollection::SetCurrentCollection()
{
fgCurrentCollection = this;
}
//______________________________________________________________________________
void TCollection::StartGarbageCollection()
{
if (!fgGarbageCollection) {
fgGarbageCollection = new TObjectTable;
fgEmptyingGarbage = kFALSE;
fgGarbageStack = 0;
}
fgGarbageStack++;
}
//______________________________________________________________________________
void TCollection::EmptyGarbageCollection()
{
if (fgGarbageStack > 0) fgGarbageStack--;
if (fgGarbageCollection && fgGarbageStack == 0 && fgEmptyingGarbage == kFALSE) {
fgEmptyingGarbage = kTRUE;
fgGarbageCollection->Delete();
fgEmptyingGarbage = kFALSE;
SafeDelete(fgGarbageCollection);
}
}
//______________________________________________________________________________
void TCollection::GarbageCollect(TObject *obj)
{
if (fgGarbageCollection && !fgEmptyingGarbage) {
fgGarbageCollection->Add(obj);
} else
delete obj;
}
//______________________________________________________________________________
TIter::TIter(const TIter &iter)
{
// Copy a TIter. This involves allocating a new TIterator of the right
// sub class and assigning it with the original.
if (iter.fIterator) {
fIterator = iter.GetCollection()->MakeIterator();
fIterator->operator=(*iter.fIterator);
} else
fIterator = 0;
}
//______________________________________________________________________________
TIter &TIter::operator=(const TIter &rhs)
{
// Assigning an TIter to another. This involves allocatiing a new TIterator
// of the right sub class and assigning it with the original.
if (this != &rhs) {
if (rhs.fIterator) {
delete fIterator;
fIterator = rhs.GetCollection()->MakeIterator();
fIterator->operator=(*rhs.fIterator);
}
}
return *this;
}
<|endoftext|>
|
<commit_before>#include<iostream>
#include<unistd.h>
#include<cstdlib>
using namespace std;
void exec(char **argv, std::string sys, std::string second, int argc)
{
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}
void run(int argc, char** argv)
{
std::string curdir = getcwd(NULL,0);
std::string main = argv[1];
if(main == "install")
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --install-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "run" )
{
std::string second = argv[2];
std::string sys = "py -3 bot.py --run-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "make" )
{
std::string second = argv[2];
std::string sys = "py -3 bot.py --make-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "compile" or main == "build")
{
std::string second = argv[2];
std::string sys = "py -3 bot.py --build-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
}else if(main == "update")
{
std::string second = argv[2];
std::string sys = "py -3 bot.py --build-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
second = argv[2];
sys = "py -3 bot.py --install-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
}else
{
cout << "Clarissa Package Manager Help Menu:" <<endl;
cout << "\tcompile: [FOR DEVELOPERS] Compiles Clarissa Application to .cpk" <<endl;
cout << "\t\tEx: cpk compile [APP_NAME]" <<endl;
cout << "\tinstall: Installs a Clarissa Package (.cpk) from a directory" <<endl;
cout << "\t\tEx: cpk install [CPK_DIR]" << endl;
cout << "\tmake: [FOR DEVELOPERS] builds a sample application" <<endl;
cout << "\t\tEx: cpk make [APP_NAME]" << endl;
cout << "\trun: Runs installed app" << endl;
cout << "\t\tEx: cpk run [APP_NAME] [optional: --python]" <<endl;
cout << "\tupdate: Updates installed cpk" << endl;
cout << "\t\tEx: cpk update [APP_NAME] [optional: --from-external]" <<endl;
}
}
int main(int argc, char** argv)
{
try
{
run(argc, argv);
}catch( std::logic_error err)
{
cout << "Clarissa Package Manager Help Menu:" <<endl;
cout << "\tcompile: [FOR DEVELOPERS] Compiles Clarissa Application to .cpk" <<endl;
cout << "\t\tEx: cpk compile [APP_NAME]" <<endl;
cout << "\tinstall: Installs a Clarissa Package (.cpk) from a directory" <<endl;
cout << "\t\tEx: cpk install [CPK_DIR]" << endl;
cout << "\tmake: [FOR DEVELOPERS] builds a sample application" <<endl;
cout << "\t\tEx: cpk make [APP_NAME]" << endl;
cout << "\trun: Runs installed app" << endl;
cout << "\t\tEx: cpk run [APP_NAME] [optional: --python]" <<endl;
cout << "\tupdate: Updates installed cpk" << endl;
cout << "\t\tEx: cpk update [APP_NAME] [optional: --from-external]" <<endl;
}
return 0;
}
<commit_msg>Update cpk-man.cpp<commit_after>#include<iostream>
#include<unistd.h>
#include<cstdlib>
using namespace std;
void exec(char **argv, std::string sys, std::string second, int argc)
{
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}
void run(int argc, char** argv)
{
std::string curdir = getcwd(NULL,0);
std::string main = argv[1];
if(main == "install")
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --install-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "run" )
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --run-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "make" )
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --make-app ";
sys = sys + second;
std::string result = "";
for(int i = 3; i < argc; i++)
{
result = result + " " + argv[i];
}
sys = sys + " " + result;
system(sys.c_str());
}else if( main == "compile" or main == "build")
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --build-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
}else if(main == "update")
{
std::string second = argv[2];
std::string sys = "python3 "+curdir+"/bot.py --build-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
second = argv[2];
sys = "py -3 bot.py --install-app ";
sys = sys + second;
sys = sys + " "+second;
exec(argv, sys, second, argc);
}else
{
cout << "Clarissa Package Manager Help Menu:" <<endl;
cout << "\tcompile: [FOR DEVELOPERS] Compiles Clarissa Application to .cpk" <<endl;
cout << "\t\tEx: cpk compile [APP_NAME]" <<endl;
cout << "\tinstall: Installs a Clarissa Package (.cpk) from a directory" <<endl;
cout << "\t\tEx: cpk install [CPK_DIR]" << endl;
cout << "\tmake: [FOR DEVELOPERS] builds a sample application" <<endl;
cout << "\t\tEx: cpk make [APP_NAME]" << endl;
cout << "\trun: Runs installed app" << endl;
cout << "\t\tEx: cpk run [APP_NAME] [optional: --python]" <<endl;
cout << "\tupdate: Updates installed cpk" << endl;
cout << "\t\tEx: cpk update [APP_NAME] [optional: --from-external]" <<endl;
}
}
int main(int argc, char** argv)
{
try
{
run(argc, argv);
}catch( std::logic_error err)
{
cout << "Clarissa Package Manager Help Menu:" <<endl;
cout << "\tcompile: [FOR DEVELOPERS] Compiles Clarissa Application to .cpk" <<endl;
cout << "\t\tEx: cpk compile [APP_NAME]" <<endl;
cout << "\tinstall: Installs a Clarissa Package (.cpk) from a directory" <<endl;
cout << "\t\tEx: cpk install [CPK_DIR]" << endl;
cout << "\tmake: [FOR DEVELOPERS] builds a sample application" <<endl;
cout << "\t\tEx: cpk make [APP_NAME]" << endl;
cout << "\trun: Runs installed app" << endl;
cout << "\t\tEx: cpk run [APP_NAME] [optional: --python]" <<endl;
cout << "\tupdate: Updates installed cpk" << endl;
cout << "\t\tEx: cpk update [APP_NAME] [optional: --from-external]" <<endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file Resource.hpp
* @brief Resource class prototype.
* @author zer0
* @date 2016-04-12
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <string>
#include <unordered_map>
#include <tinyxml2.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
constexpr bool IsCompactXmlFile() noexcept
{
return false;
}
/**
* Resource class prototype.
*
* @author zer0
* @date 2016-04-12
*/
class Resource
{
public:
static constexpr char const * const ROOT_TAG = "resource";
static constexpr char const * const NAME_ATTRIBUTE = "name";
public:
using Str = std::string;
using Map = std::unordered_map<Str, Str>;
private:
Str _tag;
Map _map;
public:
Resource() {
__EMPTY_BLOCK__
}
Resource(Resource const & obj) {
this->copy(obj);
}
Resource(Resource && obj) {
this->swap(obj);
}
virtual ~Resource() {
__EMPTY_BLOCK__
}
public:
Resource & operator =(Resource const & obj) {
return this->copy(obj);
}
Resource & operator =(Resource && obj) {
this->swap(obj);
return *this;
}
public:
Resource & copy(Resource const & obj) {
if (this != &obj) {
this->_tag = obj._tag;
this->_map = obj._map;
}
return *this;
}
void swap(Resource & obj) {
if (this != &obj) {
this->_tag.swap(obj._tag);
this->_map.swap(obj._map);
}
}
public:
void clear() noexcept {
this->_tag.assign("");
this->_map.clear();
}
std::size_t size() const noexcept {
return this->_map.size();
}
std::string get_tag() const noexcept {
return this->_tag;
}
// XML.
public:
bool readFile(std::string const & path, std::string const & tag) {
this->_tag = tag;
this->_map = Resource::readFromXmlFile(path, tag);
return !this->_map.empty();
}
bool readString(std::string const & xml, std::string const & tag) {
this->_tag = tag;
this->_map = Resource::readFromXmlString(xml, tag);
return !this->_map.empty();
}
bool save(std::string const & path) {
return Resource::save(path, this->_tag, this->_map);
}
// Accessor.
public:
template <typename Type, typename Converter>
bool getValue(std::string const & key, Type * result, Converter func) const {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
return false;
}
Type convert = 0;
try {
convert = func(find_value->second);
} catch (std::invalid_argument & e) {
// e.what();
return false;
}
if (result != nullptr) {
*result = convert;
}
return true;
}
public:
bool getString(std::string const & key, std::string * result) const {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
return false;
}
if (result != nullptr) {
*result = find_value->second;
}
return true;
}
std::string getString(std::string const & key, std::string default_value) const {
std::string result;
if (getString(key, &result)) {
return result;
}
return default_value;
}
std::string getString(std::string const & key) const {
return getString(key, std::string(""));
}
auto get(std::string const & key
, std::string default_value) const
-> decltype(default_value) {
return getString(key, std::string(""));
}
#ifndef __RESOURCE_ACCESSOR_IMPLEMENT
#define __RESOURCE_ACCESSOR_IMPLEMENT(name, type, func, value) \
public: \
bool get##name(std::string const & key, type * result) const { \
return getValue(key, result \
, [](std::string const & str) -> type { \
return func(str); \
}); \
} \
type get##name(std::string const & key \
, type default_value = value) const { \
type result = 0; \
if (get##name(key, &result)) { \
return result; \
} \
return default_value; \
} \
auto get(std::string const & key \
, type default_value = value) const \
-> decltype(default_value) { \
return this->get##name(key, default_value); \
}
#endif
public:
__RESOURCE_ACCESSOR_IMPLEMENT(Integer, int, std::stoi, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(UnInteger, unsigned int, std::stoul, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(LongLong, long long, std::stoll, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(UnLongLong, unsigned long long, std::stoull, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(Float, float, std::stof, 0.0);
__RESOURCE_ACCESSOR_IMPLEMENT(Double, double, std::stod, 0.0);
__RESOURCE_ACCESSOR_IMPLEMENT(LongDouble, long double, std::stold, 0.0);
// Mutator.
public:
void set(std::string const & key, std::string const & value) {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
this->_map.insert(std::make_pair(key, value));
} else {
find_value->second = value;
}
}
#ifndef __RESOURCE_MUTATOR_IMPLEMENT
#define __RESOURCE_MUTATOR_IMPLEMENT(type) \
public: \
void set(std::string const & key, type const & value) { \
this->set(key, std::to_string(value)); \
}
#endif
public:
__RESOURCE_MUTATOR_IMPLEMENT(int);
__RESOURCE_MUTATOR_IMPLEMENT(unsigned int);
__RESOURCE_MUTATOR_IMPLEMENT(long long);
__RESOURCE_MUTATOR_IMPLEMENT(unsigned long long);
__RESOURCE_MUTATOR_IMPLEMENT(float);
__RESOURCE_MUTATOR_IMPLEMENT(double);
__RESOURCE_MUTATOR_IMPLEMENT(long double);
public:
std::string & at(std::string const & key) {
return this->_map.at(key);
}
std::string const & at(std::string const & key) const {
return this->_map.at(key);
}
// TinyXML2 operators.
public:
using Document = tinyxml2::XMLDocument;
using Element = tinyxml2::XMLElement;
using Node = tinyxml2::XMLNode;
public:
static Map readFromXmlDocument(Document const & doc, std::string const & tag) {
Element const * root = doc.FirstChildElement(ROOT_TAG);
if (root == nullptr) {
return Map();
}
Element const * cursor = root->FirstChildElement(tag.c_str());
Map map;
while (cursor != nullptr) {
map.insert(std::make_pair(std::string(cursor->Attribute(NAME_ATTRIBUTE))
, std::string(cursor->GetText())));
cursor = cursor->NextSiblingElement(tag.c_str());
}
return map;
}
public:
static Map readFromXmlString(std::string const & xml, std::string const & tag) {
Document doc;
if (doc.Parse(xml.c_str()) == tinyxml2::XML_NO_ERROR) {
return Resource::readFromXmlDocument(doc, tag);
}
return Map();
}
static Map readFromXmlFile(std::string const & path, std::string const & tag) {
Document doc;
if (doc.LoadFile(path.c_str()) == tinyxml2::XML_NO_ERROR) {
return Resource::readFromXmlDocument(doc, tag);
}
return Map();
}
public:
static bool save(std::string const & path, std::string const & tag, Map const & map) {
Document doc;
Node * node = doc.InsertFirstChild(doc.NewElement(ROOT_TAG));
for (auto cursor : map) {
Element * element = doc.NewElement(tag.c_str());
element->SetAttribute(NAME_ATTRIBUTE, cursor.first.c_str());
element->SetText(cursor.second.c_str());
node->InsertEndChild(element);
}
if (doc.SaveFile(path.c_str()) == tinyxml2::XML_NO_ERROR) {
return true;
}
return false;
}
};
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
<commit_msg>Create Resource::set_tag() method.<commit_after>/**
* @file Resource.hpp
* @brief Resource class prototype.
* @author zer0
* @date 2016-04-12
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <string>
#include <unordered_map>
#include <tinyxml2.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
constexpr bool IsCompactXmlFile() noexcept
{
return false;
}
/**
* Resource class prototype.
*
* @author zer0
* @date 2016-04-12
*/
class Resource
{
public:
static constexpr char const * const ROOT_TAG = "resource";
static constexpr char const * const NAME_ATTRIBUTE = "name";
public:
using Str = std::string;
using Map = std::unordered_map<Str, Str>;
private:
Str _tag;
Map _map;
public:
Resource() {
__EMPTY_BLOCK__
}
Resource(Resource const & obj) {
this->copy(obj);
}
Resource(Resource && obj) {
this->swap(obj);
}
virtual ~Resource() {
__EMPTY_BLOCK__
}
public:
Resource & operator =(Resource const & obj) {
return this->copy(obj);
}
Resource & operator =(Resource && obj) {
this->swap(obj);
return *this;
}
public:
Resource & copy(Resource const & obj) {
if (this != &obj) {
this->_tag = obj._tag;
this->_map = obj._map;
}
return *this;
}
void swap(Resource & obj) {
if (this != &obj) {
this->_tag.swap(obj._tag);
this->_map.swap(obj._map);
}
}
public:
void clear() noexcept {
this->_tag.assign("");
this->_map.clear();
}
std::size_t size() const noexcept {
return this->_map.size();
}
public:
void set_tag(std::string const & tag) noexcept {
this->_tag = tag;
}
std::string get_tag() const noexcept {
return this->_tag;
}
// XML.
public:
bool readFile(std::string const & path, std::string const & tag) {
this->_tag = tag;
this->_map = Resource::readFromXmlFile(path, tag);
return !this->_map.empty();
}
bool readString(std::string const & xml, std::string const & tag) {
this->_tag = tag;
this->_map = Resource::readFromXmlString(xml, tag);
return !this->_map.empty();
}
bool save(std::string const & path) {
return Resource::save(path, this->_tag, this->_map);
}
// Accessor.
public:
template <typename Type, typename Converter>
bool getValue(std::string const & key, Type * result, Converter func) const {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
return false;
}
Type convert = 0;
try {
convert = func(find_value->second);
} catch (std::invalid_argument & e) {
// e.what();
return false;
}
if (result != nullptr) {
*result = convert;
}
return true;
}
public:
bool getString(std::string const & key, std::string * result) const {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
return false;
}
if (result != nullptr) {
*result = find_value->second;
}
return true;
}
std::string getString(std::string const & key, std::string default_value) const {
std::string result;
if (getString(key, &result)) {
return result;
}
return default_value;
}
std::string getString(std::string const & key) const {
return getString(key, std::string(""));
}
auto get(std::string const & key
, std::string default_value) const
-> decltype(default_value) {
return getString(key, std::string(""));
}
#ifndef __RESOURCE_ACCESSOR_IMPLEMENT
#define __RESOURCE_ACCESSOR_IMPLEMENT(name, type, func, value) \
public: \
bool get##name(std::string const & key, type * result) const { \
return getValue(key, result \
, [](std::string const & str) -> type { \
return func(str); \
}); \
} \
type get##name(std::string const & key \
, type default_value = value) const { \
type result = 0; \
if (get##name(key, &result)) { \
return result; \
} \
return default_value; \
} \
auto get(std::string const & key \
, type default_value = value) const \
-> decltype(default_value) { \
return this->get##name(key, default_value); \
}
#endif
public:
__RESOURCE_ACCESSOR_IMPLEMENT(Integer, int, std::stoi, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(UnInteger, unsigned int, std::stoul, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(LongLong, long long, std::stoll, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(UnLongLong, unsigned long long, std::stoull, 0);
__RESOURCE_ACCESSOR_IMPLEMENT(Float, float, std::stof, 0.0);
__RESOURCE_ACCESSOR_IMPLEMENT(Double, double, std::stod, 0.0);
__RESOURCE_ACCESSOR_IMPLEMENT(LongDouble, long double, std::stold, 0.0);
// Mutator.
public:
void set(std::string const & key, std::string const & value) {
auto find_value = this->_map.find(key);
if (find_value == this->_map.end()) {
this->_map.insert(std::make_pair(key, value));
} else {
find_value->second = value;
}
}
#ifndef __RESOURCE_MUTATOR_IMPLEMENT
#define __RESOURCE_MUTATOR_IMPLEMENT(type) \
public: \
void set(std::string const & key, type const & value) { \
this->set(key, std::to_string(value)); \
}
#endif
public:
__RESOURCE_MUTATOR_IMPLEMENT(int);
__RESOURCE_MUTATOR_IMPLEMENT(unsigned int);
__RESOURCE_MUTATOR_IMPLEMENT(long long);
__RESOURCE_MUTATOR_IMPLEMENT(unsigned long long);
__RESOURCE_MUTATOR_IMPLEMENT(float);
__RESOURCE_MUTATOR_IMPLEMENT(double);
__RESOURCE_MUTATOR_IMPLEMENT(long double);
public:
std::string & at(std::string const & key) {
return this->_map.at(key);
}
std::string const & at(std::string const & key) const {
return this->_map.at(key);
}
// TinyXML2 operators.
public:
using Document = tinyxml2::XMLDocument;
using Element = tinyxml2::XMLElement;
using Node = tinyxml2::XMLNode;
public:
static Map readFromXmlDocument(Document const & doc, std::string const & tag) {
Element const * root = doc.FirstChildElement(ROOT_TAG);
if (root == nullptr) {
return Map();
}
Element const * cursor = root->FirstChildElement(tag.c_str());
Map map;
while (cursor != nullptr) {
map.insert(std::make_pair(std::string(cursor->Attribute(NAME_ATTRIBUTE))
, std::string(cursor->GetText())));
cursor = cursor->NextSiblingElement(tag.c_str());
}
return map;
}
public:
static Map readFromXmlString(std::string const & xml, std::string const & tag) {
Document doc;
if (doc.Parse(xml.c_str()) == tinyxml2::XML_NO_ERROR) {
return Resource::readFromXmlDocument(doc, tag);
}
return Map();
}
static Map readFromXmlFile(std::string const & path, std::string const & tag) {
Document doc;
if (doc.LoadFile(path.c_str()) == tinyxml2::XML_NO_ERROR) {
return Resource::readFromXmlDocument(doc, tag);
}
return Map();
}
public:
static bool save(std::string const & path, std::string const & tag, Map const & map) {
Document doc;
Node * node = doc.InsertFirstChild(doc.NewElement(ROOT_TAG));
for (auto cursor : map) {
Element * element = doc.NewElement(tag.c_str());
element->SetAttribute(NAME_ATTRIBUTE, cursor.first.c_str());
element->SetText(cursor.second.c_str());
node->InsertEndChild(element);
}
if (doc.SaveFile(path.c_str()) == tinyxml2::XML_NO_ERROR) {
return true;
}
return false;
}
};
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_RESOURCE_HPP__
<|endoftext|>
|
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2012, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include <QApplication>
#include <QX11Info>
#include <QProcess>
#include <QProcessEnvironment>
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <QUrl>
#include <QDebug>
#include <QTranslator>
#include <QLocale>
#include <QMessageBox>
#include <QSplashScreen>
#include <QDateTime>
#include <QPixmap>
#include <QColor>
#include <QFont>
#include <QTextCodec>
#include "LFileDialog.h"
#include <LuminaXDG.h>
#include <LuminaOS.h>
#ifndef PREFIX
#define PREFIX QString("/usr/local")
#endif
static QApplication *App = 0;
void printUsageInfo(){
qDebug() << "lumina-open: Application launcher for the Lumina Desktop Environment";
qDebug() << "Description: Given a file (with absolute path) or URL, this utility will try to find the appropriate application with which to open the file. If the file is a *.desktop application shortcut, it will just start the application appropriately. It can also perform a few specific system operations if given special flags.";
qDebug() << "Usage: lumina-open [-select] <absolute file path or URL>";
qDebug() << " lumina-open [-volumeup, -volumedown, -brightnessup, -brightnessdown]";
qDebug() << " [-select] (optional) flag to bypass any default application settings and show the application selector window";
qDebug() << "Special Flags:";
qDebug() << " \"-volume[up/down]\" Flag to increase/decrease audio volume by 5%";
qDebug() << " \"-brightness[up/down]\" Flag to increase/decrease screen brightness by 5%";
exit(1);
}
void setupApplication(int argc, char **argv){
App = new QApplication(argc, argv);
QTranslator translator;
QLocale mylocale;
QString langCode = mylocale.name();
if(!QFile::exists(PREFIX + "/share/Lumina-DE/i18n/lumina-open_" + langCode + ".qm") ){
langCode.truncate( langCode.indexOf("_") );
}
translator.load( QString("lumina-open_") + langCode, PREFIX + "/share/Lumina-DE/i18n/" );
App->installTranslator( &translator );
qDebug() << "Locale:" << langCode;
//Load current encoding for this locale
QTextCodec::setCodecForTr( QTextCodec::codecForLocale() ); //make sure to use the same codec
qDebug() << "Locale Encoding:" << QTextCodec::codecForLocale()->name();
}
void showOSD(int argc, char **argv, QString message){
setupApplication(argc, argv);
//qDebug() << "Display OSD";
QPixmap pix(":/icons/OSD.png");
QSplashScreen splash(pix, Qt::SplashScreen | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
splash.setWindowTitle("");
QFont myfont;
myfont.setBold(true);
myfont.setPixelSize(13);
splash.setFont(myfont);
qDebug() << "Display OSD";
splash.show();
//qDebug() << " - show message";
splash.showMessage(message, Qt::AlignCenter, Qt::white);
//qDebug() << " - loop";
QDateTime end = QDateTime::currentDateTime().addMSecs(800);
while(QDateTime::currentDateTime() < end){ App->processEvents(); }
splash.hide();
}
QString cmdFromUser(int argc, char **argv, QString inFile, QString extension, QString& path, bool showDLG=false){
//First check to see if there is a default for this extension
QString defApp = LFileDialog::getDefaultApp(extension);
if(extension=="directory" && defApp.isEmpty() && !showDLG){
//Just use the Lumina File Manager
return "lumina-fm";
}else if( !defApp.isEmpty() && !showDLG ){
bool ok = false;
XDGDesktop DF = LXDG::loadDesktopFile(defApp, ok);
if(ok){
QString exec = LXDG::getDesktopExec(DF);
if(!exec.isEmpty()){
qDebug() << "[lumina-open] Using default application:" << DF.name << "File:" << inFile;
if(!DF.path.isEmpty()){ path = DF.path; }
return exec;
}
}
//invalid default - reset it and continue on
LFileDialog::setDefaultApp(extension, "");
}
//No default set -- Start up the application selection dialog
setupApplication(argc,argv);
LFileDialog w;
if(inFile.startsWith(extension)){
//URL
w.setFileInfo(inFile, extension, false);
}else{
//File
if(inFile.endsWith("/")){ inFile.chop(1); }
w.setFileInfo(inFile.section("/",-1), extension, true);
}
w.show();
App->exec();
if(!w.appSelected){ exit(1); }
//Return the run path if appropriate
if(!w.appPath.isEmpty()){ path = w.appPath; }
//Just do the default application registration here for now
// might move it to the runtime phase later after seeing that the app has successfully started
if(w.setDefault){ LFileDialog::setDefaultApp(extension, w.appFile); }
else{ LFileDialog::setDefaultApp(extension, ""); }
//Now return the resulting application command
return w.appExec;
}
void getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){
//Get the input file
QString inFile;
bool showDLG = false; //flag to bypass any default application setting
if(argc > 1){
for(int i=1; i<argc; i++){
if(QString(argv[i]).simplified() == "-select"){
showDLG = true;
}else if(QString(argv[i]).simplified() == "-volumeup"){
int vol = LOS::audioVolume()+5; //increase 5%
if(vol>100){ vol=100; }
LOS::setAudioVolume(vol);
showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
return;
}else if(QString(argv[i]).simplified() == "-volumedown"){
int vol = LOS::audioVolume()-5; //decrease 5%
if(vol<0){ vol=0; }
LOS::setAudioVolume(vol);
showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
return;
}else if(QString(argv[i]).simplified() == "-brightnessup"){
int bright = LOS::ScreenBrightness();
if(bright > 0){ //brightness control available
bright = bright+5; //increase 5%
if(bright>100){ bright = 100; }
LOS::setScreenBrightness(bright);
showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
}
return;
}else if(QString(argv[i]).simplified() == "-brightnessdown"){
int bright = LOS::ScreenBrightness();
if(bright > 0){ //brightness control available
bright = bright-5; //decrease 5%
if(bright<0){ bright = 0; }
LOS::setScreenBrightness(bright);
showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
}
return;
}else{
inFile = argv[i];
break;
}
}
}else{
printUsageInfo();
}
//Make sure that it is a valid file/URL
bool isFile=false; bool isUrl=false;
if(QFile::exists(inFile)){ isFile=true; }
else if(QUrl(inFile).isValid()){ isUrl=true; }
if( !isFile && !isUrl ){ qDebug() << "Error: Invalid file or URL"; return;}
//Determing the type of file (extension)
QString extension;
if(isFile){
QFileInfo info(inFile);
extension=info.completeSuffix();
if(info.isDir()){ extension="directory"; }
else if(info.isExecutable() && extension.isEmpty()){ extension="binary"; }
}else if(isUrl){ extension = inFile.section(":",0,0); }
//if not an application - find the right application to open the file
QString cmd;
bool useInputFile = false;
if(extension=="directory" && !showDLG){
cmd = "lumina-fm";
useInputFile=true;
}else if(extension=="desktop" && !showDLG){
bool ok = false;
XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);
if(!ok){
qDebug() << "[ERROR] Input *.desktop file could not be read:" << inFile;
exit(1);
}
switch(DF.type){
case XDGDesktop::APP:
if(!DF.exec.isEmpty()){
cmd = LXDG::getDesktopExec(DF);
if(!DF.path.isEmpty()){ path = DF.path; }
}else{
qDebug() << "[ERROR] Input *.desktop application file is missing the Exec line:" << inFile;
exit(1);
}
break;
case XDGDesktop::LINK:
if(!DF.url.isEmpty()){
//This is a URL - so adjust the input variables appropriately
inFile = DF.url;
cmd.clear();
extension = inFile.section(":",0,0);
}else{
qDebug() << "[ERROR] Input *.desktop link file is missing the URL line:" << inFile;
exit(1);
}
break;
case XDGDesktop::DIR:
if(!DF.path.isEmpty()){
//This is a directory link - adjust inputs
inFile = DF.path;
cmd.clear();
extension = "directorypath";
}else{
qDebug() << "[ERROR] Input *.desktop directory file is missing the Path line:" << inFile;
exit(1);
}
break;
default:
qDebug() << "[ERROR] Unknown *.desktop file type:" << inFile;
exit(1);
}
}
if(cmd.isEmpty()){
if(extension=="binary"){ cmd = inFile; }
else{
//Find out the proper application to use this file/directory
useInputFile=true;
cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);
}
}
//qDebug() << "Found Command:" << cmd << "Extension:" << extension;
//Clean up the command appropriately for output
if(cmd.contains("%")){cmd = cmd.remove("%U").remove("%u").remove("%F").remove("%f").simplified(); }
binary = cmd;
if(useInputFile){ args = inFile; }
}
int main(int argc, char **argv){
//Run all the actual code in a separate function to have as little memory usage
// as possible aside from the main application when running
//Make sure the XDG environment variables exist first
LXDG::setEnvironmentVars();
//now get the command
QString cmd, args, path;
getCMD(argc, argv, cmd, args, path);
//qDebug() << "Run CMD:" << cmd << args;
//Now run the command (move to execvp() later?)
if(cmd.isEmpty()){ return 0; } //no command to run (handled internally)
if(!args.isEmpty()){ cmd.append(" \""+args+"\""); }
int retcode = system( cmd.toUtf8() );
/*
QProcess *p = new QProcess();
p->setProcessEnvironment(QProcessEnvironment::systemEnvironment());
if(!path.isEmpty() && QFile::exists(path)){ p->setWorkingDirectory(path); }
p->start(cmd+" \""+args+"\"");
//Check the startup procedure
while(!p->waitForStarted(5000)){
if(p->state() == QProcess::NotRunning){
//bad/invalid start
qDebug() << "[lumina-open] Application did not startup properly:"<<cmd+" "+args;
return p->exitCode();
}else if(p->state() == QProcess::Running){
//This just missed the "started" signal - continue
break;
}
}
//Now check up on it once every minute until it is finished
while(!p->waitForFinished(60000)){
if(p->state() != QProcess::Running){ break; } //somehow missed the finished signal
}
int retcode = p->exitCode();*/
if(retcode!=0){
qDebug() << "[lumina-open] Application Error:" << retcode;
QMessageBox::critical(0,QObject::tr("Application Error"), QObject::tr("The following application experienced an error and needed to close:")+"\n\n"+cmd);
}
return retcode;
}
<commit_msg>Update lumina-open to remove some of the other Exec= flags that might be available (if not handled previously).<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2012, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include <QApplication>
#include <QX11Info>
#include <QProcess>
#include <QProcessEnvironment>
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <QUrl>
#include <QDebug>
#include <QTranslator>
#include <QLocale>
#include <QMessageBox>
#include <QSplashScreen>
#include <QDateTime>
#include <QPixmap>
#include <QColor>
#include <QFont>
#include <QTextCodec>
#include "LFileDialog.h"
#include <LuminaXDG.h>
#include <LuminaOS.h>
#ifndef PREFIX
#define PREFIX QString("/usr/local")
#endif
static QApplication *App = 0;
void printUsageInfo(){
qDebug() << "lumina-open: Application launcher for the Lumina Desktop Environment";
qDebug() << "Description: Given a file (with absolute path) or URL, this utility will try to find the appropriate application with which to open the file. If the file is a *.desktop application shortcut, it will just start the application appropriately. It can also perform a few specific system operations if given special flags.";
qDebug() << "Usage: lumina-open [-select] <absolute file path or URL>";
qDebug() << " lumina-open [-volumeup, -volumedown, -brightnessup, -brightnessdown]";
qDebug() << " [-select] (optional) flag to bypass any default application settings and show the application selector window";
qDebug() << "Special Flags:";
qDebug() << " \"-volume[up/down]\" Flag to increase/decrease audio volume by 5%";
qDebug() << " \"-brightness[up/down]\" Flag to increase/decrease screen brightness by 5%";
exit(1);
}
void setupApplication(int argc, char **argv){
App = new QApplication(argc, argv);
QTranslator translator;
QLocale mylocale;
QString langCode = mylocale.name();
if(!QFile::exists(PREFIX + "/share/Lumina-DE/i18n/lumina-open_" + langCode + ".qm") ){
langCode.truncate( langCode.indexOf("_") );
}
translator.load( QString("lumina-open_") + langCode, PREFIX + "/share/Lumina-DE/i18n/" );
App->installTranslator( &translator );
qDebug() << "Locale:" << langCode;
//Load current encoding for this locale
QTextCodec::setCodecForTr( QTextCodec::codecForLocale() ); //make sure to use the same codec
qDebug() << "Locale Encoding:" << QTextCodec::codecForLocale()->name();
}
void showOSD(int argc, char **argv, QString message){
setupApplication(argc, argv);
//qDebug() << "Display OSD";
QPixmap pix(":/icons/OSD.png");
QSplashScreen splash(pix, Qt::SplashScreen | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
splash.setWindowTitle("");
QFont myfont;
myfont.setBold(true);
myfont.setPixelSize(13);
splash.setFont(myfont);
qDebug() << "Display OSD";
splash.show();
//qDebug() << " - show message";
splash.showMessage(message, Qt::AlignCenter, Qt::white);
//qDebug() << " - loop";
QDateTime end = QDateTime::currentDateTime().addMSecs(800);
while(QDateTime::currentDateTime() < end){ App->processEvents(); }
splash.hide();
}
QString cmdFromUser(int argc, char **argv, QString inFile, QString extension, QString& path, bool showDLG=false){
//First check to see if there is a default for this extension
QString defApp = LFileDialog::getDefaultApp(extension);
if(extension=="directory" && defApp.isEmpty() && !showDLG){
//Just use the Lumina File Manager
return "lumina-fm";
}else if( !defApp.isEmpty() && !showDLG ){
bool ok = false;
XDGDesktop DF = LXDG::loadDesktopFile(defApp, ok);
if(ok){
QString exec = LXDG::getDesktopExec(DF);
if(!exec.isEmpty()){
qDebug() << "[lumina-open] Using default application:" << DF.name << "File:" << inFile;
if(!DF.path.isEmpty()){ path = DF.path; }
return exec;
}
}
//invalid default - reset it and continue on
LFileDialog::setDefaultApp(extension, "");
}
//No default set -- Start up the application selection dialog
setupApplication(argc,argv);
LFileDialog w;
if(inFile.startsWith(extension)){
//URL
w.setFileInfo(inFile, extension, false);
}else{
//File
if(inFile.endsWith("/")){ inFile.chop(1); }
w.setFileInfo(inFile.section("/",-1), extension, true);
}
w.show();
App->exec();
if(!w.appSelected){ exit(1); }
//Return the run path if appropriate
if(!w.appPath.isEmpty()){ path = w.appPath; }
//Just do the default application registration here for now
// might move it to the runtime phase later after seeing that the app has successfully started
if(w.setDefault){ LFileDialog::setDefaultApp(extension, w.appFile); }
else{ LFileDialog::setDefaultApp(extension, ""); }
//Now return the resulting application command
return w.appExec;
}
void getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){
//Get the input file
QString inFile;
bool showDLG = false; //flag to bypass any default application setting
if(argc > 1){
for(int i=1; i<argc; i++){
if(QString(argv[i]).simplified() == "-select"){
showDLG = true;
}else if(QString(argv[i]).simplified() == "-volumeup"){
int vol = LOS::audioVolume()+5; //increase 5%
if(vol>100){ vol=100; }
LOS::setAudioVolume(vol);
showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
return;
}else if(QString(argv[i]).simplified() == "-volumedown"){
int vol = LOS::audioVolume()-5; //decrease 5%
if(vol<0){ vol=0; }
LOS::setAudioVolume(vol);
showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
return;
}else if(QString(argv[i]).simplified() == "-brightnessup"){
int bright = LOS::ScreenBrightness();
if(bright > 0){ //brightness control available
bright = bright+5; //increase 5%
if(bright>100){ bright = 100; }
LOS::setScreenBrightness(bright);
showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
}
return;
}else if(QString(argv[i]).simplified() == "-brightnessdown"){
int bright = LOS::ScreenBrightness();
if(bright > 0){ //brightness control available
bright = bright-5; //decrease 5%
if(bright<0){ bright = 0; }
LOS::setScreenBrightness(bright);
showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
}
return;
}else{
inFile = argv[i];
break;
}
}
}else{
printUsageInfo();
}
//Make sure that it is a valid file/URL
bool isFile=false; bool isUrl=false;
if(QFile::exists(inFile)){ isFile=true; }
else if(QUrl(inFile).isValid()){ isUrl=true; }
if( !isFile && !isUrl ){ qDebug() << "Error: Invalid file or URL"; return;}
//Determing the type of file (extension)
QString extension;
if(isFile){
QFileInfo info(inFile);
extension=info.completeSuffix();
if(info.isDir()){ extension="directory"; }
else if(info.isExecutable() && extension.isEmpty()){ extension="binary"; }
}else if(isUrl){ extension = inFile.section(":",0,0); }
//if not an application - find the right application to open the file
QString cmd;
bool useInputFile = false;
if(extension=="directory" && !showDLG){
cmd = "lumina-fm";
useInputFile=true;
}else if(extension=="desktop" && !showDLG){
bool ok = false;
XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);
if(!ok){
qDebug() << "[ERROR] Input *.desktop file could not be read:" << inFile;
exit(1);
}
switch(DF.type){
case XDGDesktop::APP:
if(!DF.exec.isEmpty()){
cmd = LXDG::getDesktopExec(DF);
if(!DF.path.isEmpty()){ path = DF.path; }
}else{
qDebug() << "[ERROR] Input *.desktop application file is missing the Exec line:" << inFile;
exit(1);
}
break;
case XDGDesktop::LINK:
if(!DF.url.isEmpty()){
//This is a URL - so adjust the input variables appropriately
inFile = DF.url;
cmd.clear();
extension = inFile.section(":",0,0);
}else{
qDebug() << "[ERROR] Input *.desktop link file is missing the URL line:" << inFile;
exit(1);
}
break;
case XDGDesktop::DIR:
if(!DF.path.isEmpty()){
//This is a directory link - adjust inputs
inFile = DF.path;
cmd.clear();
extension = "directory";
}else{
qDebug() << "[ERROR] Input *.desktop directory file is missing the Path line:" << inFile;
exit(1);
}
break;
default:
qDebug() << "[ERROR] Unknown *.desktop file type:" << inFile;
exit(1);
}
}
if(cmd.isEmpty()){
if(extension=="binary"){ cmd = inFile; }
else{
//Find out the proper application to use this file/directory
useInputFile=true;
cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);
}
}
//qDebug() << "Found Command:" << cmd << "Extension:" << extension;
//Clean up the command appropriately for output
if(cmd.contains("%")){cmd = cmd.remove("%U").remove("%u").remove("%F").remove("%f").remove("%i").remove("%c").remove("%k").simplified(); }
binary = cmd;
if(useInputFile){ args = inFile; }
}
int main(int argc, char **argv){
//Run all the actual code in a separate function to have as little memory usage
// as possible aside from the main application when running
//Make sure the XDG environment variables exist first
LXDG::setEnvironmentVars();
//now get the command
QString cmd, args, path;
getCMD(argc, argv, cmd, args, path);
//qDebug() << "Run CMD:" << cmd << args;
//Now run the command (move to execvp() later?)
if(cmd.isEmpty()){ return 0; } //no command to run (handled internally)
if(!args.isEmpty()){ cmd.append(" \""+args+"\""); }
int retcode = system( cmd.toUtf8() );
/*
QProcess *p = new QProcess();
p->setProcessEnvironment(QProcessEnvironment::systemEnvironment());
if(!path.isEmpty() && QFile::exists(path)){ p->setWorkingDirectory(path); }
p->start(cmd+" \""+args+"\"");
//Check the startup procedure
while(!p->waitForStarted(5000)){
if(p->state() == QProcess::NotRunning){
//bad/invalid start
qDebug() << "[lumina-open] Application did not startup properly:"<<cmd+" "+args;
return p->exitCode();
}else if(p->state() == QProcess::Running){
//This just missed the "started" signal - continue
break;
}
}
//Now check up on it once every minute until it is finished
while(!p->waitForFinished(60000)){
if(p->state() != QProcess::Running){ break; } //somehow missed the finished signal
}
int retcode = p->exitCode();*/
if(retcode!=0){
qDebug() << "[lumina-open] Application Error:" << retcode;
QMessageBox::critical(0,QObject::tr("Application Error"), QObject::tr("The following application experienced an error and needed to close:")+"\n\n"+cmd);
}
return retcode;
}
<|endoftext|>
|
<commit_before>// $Id: reconstruct_fragment.C,v 1.1 2003/03/04 14:43:11 anker Exp $
//
// A little helper program that tries to reconstruct broken fragments in a
// molecule. This program assumes that there is only *one* chain in the
// file.
//
// Usage: reconstruct_fragemnt reference_fragment_name res_id infile outfile
#include <BALL/common.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/STRUCTURE/reconstructFragmentProcessor.h>
#include <BALL/FORMAT/PDBFile.h>
using namespace BALL;
using namespace std;
int main(int argc, char** argv)
{
if (argc != 5)
{
Log.info() << "Usage:" << endl;
Log.info() << argv[0] << " fragment-name residue-id infile.pdb outfile.pdb"
<< endl;
return(1);
}
String reference_fragment_name(argv[1]);
String res_id(argv[2]);
String infile_name(argv[3]);
String outfile_name(argv[4]);
System system;
PDBFile infile(infile_name);
infile >> system;
infile.close();
FragmentDB db;
system.apply(db.normalize_names);
system.apply(db.build_bonds);
ResidueIterator res_it = system.beginResidue();
while (res_it->getID() != res_id)
{
++res_it;
}
if (!res_it.isValid())
{
std::cerr << "Didn't find res_id " << res_id << " in system" << std::endl;
}
const Fragment& ref = *db.getFragment(reference_fragment_name);
Size atoms = ReconstructFragmentProcessor::reconstructFragment(*res_it, ref);
Log.info() << " added " << atoms << " atoms" << std::endl;
Size bonds = db.build_bonds.buildFragmentBonds(*res_it, ref);
Log.info() << " added " << bonds << " bonds" << std::endl;
ResidueChecker check(db);
system.apply(check);
PDBFile outfile(outfile_name, std::ios::out);
outfile << system;
outfile.close();
}
<commit_msg>added automatic mode<commit_after>// $Id: reconstruct_fragment.C,v 1.2 2003/03/04 18:24:30 anker Exp $
//
// A little helper program that tries to reconstruct broken fragments in a
// molecule. This program assumes that there is only *one* chain in the
// file.
//
// Usage: reconstruct_fragemnt reference_fragment_name res_id infile outfile
#include <BALL/common.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/STRUCTURE/reconstructFragmentProcessor.h>
#include <BALL/FORMAT/PDBFile.h>
using namespace BALL;
using namespace std;
int main(int argc, char** argv)
{
if ((argc != 5) && (argc != 3))
{
Log.info() << "Usage:" << endl;
Log.info() << argv[0] << " infile.pdb outfile.pdb"
<< "\n" << endl;
Log.info() << " or\n" << endl;
Log.info() << argv[0] << " fragment-name residue-id infile.pdb outfile.pdb"
return(1);
}
bool automatic = true;
String reference_fragment_name;
String res_id;
String infile_name;
String outfile_name;
if (argc == 5)
{
automatic = false;
reference_fragment_name = argv[1];
res_id = argv[2];
infile_name = argv[3];
outfile_name = argv[4];
}
else
{
infile_name = argv[1];
outfile_name = argv[2];
}
System system;
PDBFile infile(infile_name);
infile >> system;
infile.close();
FragmentDB db;
system.apply(db.normalize_names);
if (automatic == true)
{
ReconstructFragmentProcessor proc(db);
system.apply(proc);
system.apply(db.build_bonds);
}
else
{
ResidueIterator res_it = system.beginResidue();
while (res_it->getID() != res_id)
{
++res_it;
}
if (!res_it.isValid())
{
cerr << "Didn't find res_id " << res_id << " in system" << endl;
}
const Fragment& ref = *db.getFragment(reference_fragment_name);
Size atoms = ReconstructFragmentProcessor::reconstructFragment(*res_it, ref);
Log.info() << " added " << atoms << " atoms" << std::endl;
Size bonds = db.build_bonds.buildFragmentBonds(*res_it, ref);
Log.info() << " added " << bonds << " bonds" << std::endl;
}
ResidueChecker check(db);
system.apply(check);
PDBFile outfile(outfile_name, ios::out);
outfile << system;
outfile.close();
}
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InWorldChatModule.cpp
* @brief Simple OpenSim world chat module. Listens for ChatFromSimulator packets and shows the chat on the UI.
* Outgoing chat sent using ChatFromViewer packets. Manages EC_ChatBubbles, EC_Billboards, chat logging etc.
* @note Depends on RexLogicModule so don't create dependency to this module.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "InWorldChatModule.h"
//#include "ChatWidget.h"
#include "EC_ChatBubble.h"
#include "EC_Billboard.h"
#include "EC_OpenSimPresence.h"
#include "ConsoleCommandServiceInterface.h"
#include "WorldStream.h"
#include "SceneManager.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "NetworkMessages/NetInMessage.h"
#include "CoreStringUtils.h"
#include "GenericMessageUtils.h"
#include "UiModule.h"
#include "ConfigurationManager.h"
//#include "EntityComponent/EC_OpenSimPresence.h"
#include "EntityComponent/EC_OpenSimPrim.h"
#include <QColor>
#include "MemoryLeakCheck.h"
namespace Naali
{
InWorldChatModule::InWorldChatModule() :
ModuleInterfaceImpl(NameStatic()),
networkStateEventCategory_(0),
networkInEventCategory_(0),
frameworkEventCategory_(0),
showChatBubbles_(true),
logging_(false),
logFile_(0)
//chatWidget_(0)
{
}
InWorldChatModule::~InWorldChatModule()
{
SAFE_DELETE(logFile_);
}
void InWorldChatModule::Load()
{
DECLARE_MODULE_EC(EC_Billboard);
DECLARE_MODULE_EC(EC_ChatBubble);
}
void InWorldChatModule::PostInitialize()
{
frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
if (frameworkEventCategory_ == 0)
LogError("Failed to query \"Framework\" event category");
uiModule_ = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices);
RegisterConsoleCommand(Console::CreateCommand("bbtest",
"Adds a billboard to each entity in the scene.",
Console::Bind(this, &InWorldChatModule::TestAddBillboard)));
RegisterConsoleCommand(Console::CreateCommand("chat",
"Sends a chat message. Usage: \"chat(message)\"",
Console::Bind(this, &InWorldChatModule::ConsoleChat)));
showChatBubbles_ = framework_->GetDefaultConfig().DeclareSetting("InWorldChatModule", "ShowChatBubbles", true);
logging_ = framework_->GetDefaultConfig().DeclareSetting("InWorldChatModule", "Logging", false);
}
void InWorldChatModule::Update(f64 frametime)
{
}
bool InWorldChatModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface *data)
{
if (category_id == frameworkEventCategory_)
{
if (event_id == Foundation::NETWORKING_REGISTERED)
{
ProtocolUtilities::NetworkingRegisteredEvent *event_data = checked_static_cast<ProtocolUtilities::NetworkingRegisteredEvent *>(data);
if (event_data)
{
networkStateEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
if (networkStateEventCategory_ == 0)
LogError("Failed to query \"NetworkState\" event category");
networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
if (networkInEventCategory_ == 0)
LogError("Failed to query \"NetworkIn\" event category");
return false;
}
}
if(event_id == Foundation::WORLD_STREAM_READY)
{
ProtocolUtilities::WorldStreamReadyEvent *event_data = checked_static_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
if (event_data)
currentWorldStream_ = event_data->WorldStream;
networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
if (networkInEventCategory_ == 0)
LogError("Failed to query \"NetworkIn\" event category");
return false;
}
}
if (category_id == networkStateEventCategory_)
{
if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
{
/*
if (!uiModule_.expired())
{
chatWidget_ = new ChatWidget(framework_);
connect(chatWidget_, SIGNAL(ChatEntered(const QString &)), this, SLOT(SendChatFromViewer(const QString &)));
chatProxy_ = uiModule_.lock()->GetSceneManager()->AddWidgetToScene(
chatWidget_, UiServices::UiWidgetProperties(QPointF(0,0), QSize(chatWidget_->size()), Qt::Widget, "InWorldChat", false, false));
connect(chatProxy_->scene(), SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(RepositionChatWidget(const QRectF &)));
RepositionChatWidget(chatProxy_->scene()->sceneRect());
chatProxy_->show();
*/
// Get settings.
showChatBubbles_ = framework_->GetDefaultConfig().GetSetting<bool>("InWorldChatModule", "ShowChatBubbles");
logging_ = framework_->GetDefaultConfig().GetSetting<bool>("InWorldChatModule", "Logging");
}
else if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED)
{
//SAFE_DELETE(chatWidget_);
// Save settings.
framework_->GetDefaultConfig().SetSetting<bool>("InWorldChatModule", "ShowChatBubbles", showChatBubbles_);
framework_->GetDefaultConfig().SetSetting<bool>("InWorldChatModule", "Logging", logging_);
}
}
if (category_id == networkInEventCategory_)
{
if (event_id != RexNetMsgGenericMessage && event_id != RexNetMsgChatFromSimulator)
return false;
using namespace ProtocolUtilities;
NetworkEventInboundData *netdata = checked_static_cast<NetworkEventInboundData *>(data);
assert(netdata);
if (!netdata)
return false;
ProtocolUtilities::NetInMessage &msg = *netdata->message;
switch(event_id)
{
case RexNetMsgGenericMessage:
if (ParseGenericMessageMethod(msg) == "RexEmotionIcon")
HandleRexEmotionIconMessage(ParseGenericMessageParameters(msg));
return false;
case RexNetMsgChatFromSimulator:
HandleChatFromSimulatorMessage(msg);
return false;
default:
return false;
}
}
return false;
}
const std::string InWorldChatModule::moduleName = std::string("InWorldChatModule");
const std::string &InWorldChatModule::NameStatic()
{
return moduleName;
}
void InWorldChatModule::SendChatFromViewer(const QString &msg)
{
if (currentWorldStream_)
currentWorldStream_->SendChatFromViewerPacket(std::string(msg.toUtf8()));
}
Console::CommandResult InWorldChatModule::TestAddBillboard(const StringVector ¶ms)
{
Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
/// If/when there are multiple scenes at some day, have the SceneManager know the currently active one
/// instead of RexLogicModule, so no dependency to it is needed.
for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
{
Scene::EntityPtr entity = *iter;
entity->AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
EC_Billboard *billboard = entity->GetComponent<EC_Billboard>().get();
assert(billboard);
billboard->Show(Vector3df(0.f, 0.f, 1.5f), 10.f, "smoke.png");
}
return Console::ResultSuccess();
}
Console::CommandResult InWorldChatModule::ConsoleChat(const StringVector ¶ms)
{
if (params.size() == 0)
return Console::ResultFailure("Can't send empty chat message!");
SendChatFromViewer(params[0].c_str());
return Console::ResultSuccess();
}
void InWorldChatModule::ApplyDefaultChatBubble(Scene::Entity &entity, const QString &message)
{
Foundation::ComponentInterfacePtr component = entity.GetOrCreateComponent(EC_ChatBubble::TypeNameStatic());
assert(component.get());
EC_ChatBubble &chatBubble = *(checked_static_cast<EC_ChatBubble *>(component.get()));
chatBubble.ShowMessage(message);
}
void InWorldChatModule::ApplyBillboard(Scene::Entity &entity, const std::string &texture, float timeToShow)
{
boost::shared_ptr<EC_Billboard> ec_bb = entity.GetComponent<EC_Billboard>();
// If we didn't have the billboard component yet, create one now.
if (!ec_bb)
{
entity.AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
ec_bb = entity.GetComponent<EC_Billboard>();
assert(ec_bb.get());
}
ec_bb->Show(Vector3df(0.f, 0.f, 1.5f), timeToShow, texture.c_str());
}
Scene::Entity *InWorldChatModule::GetEntityWithId(const RexUUID &id)
{
Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
{
Scene::Entity &entity = **iter;
boost::shared_ptr<EC_OpenSimPresence> ec_presence = entity.GetComponent<EC_OpenSimPresence>();
boost::shared_ptr<RexLogic::EC_OpenSimPrim> ec_prim = entity.GetComponent<RexLogic::EC_OpenSimPrim>();
if (ec_presence)
{
if (ec_presence->agentId == id)
return &entity;
}
else if (ec_prim)
{
if (ec_prim->FullId == id)
return &entity;
}
}
return 0;
}
void InWorldChatModule::HandleRexEmotionIconMessage(StringVector ¶ms)
{
// Param 0: avatar UUID
// Param 1: texture ID
// Param 2: timeout (remember to replace any , with . before parsing)
if (params.size() < 3)
throw Exception("Failed to parse RexEmotionIcon message!");
LogInfo("Received RexEmotionIcon: " + params[0] + " " + params[1] + " " + params[2]);
ReplaceCharInplace(params[2], ',', '.');
if (!RexUUID::IsValid(params[0]))
throw Exception("Invalid Entity UUID passed in RexEmotionIcon message!");
RexUUID entityUUID(params[0]);
if (entityUUID.IsNull())
throw Exception("Null Entity UUID passed in RexEmotionIcon message!");
Scene::Entity *entity = GetEntityWithId(entityUUID);
if (!entity)
throw Exception("Received RexEmotionIcon message for a nonexisting entity!");
// timeToShow: value of [-1, 0[ denotes "infinite".
// a positive value between [0, 86400] denotes the number of seconds to show. (max roughly one day)
float timeToShow = atof(params[2].c_str());
if (!(timeToShow >= -2.f && timeToShow <= 86401.f)) // Checking through negation due to possible NaNs and infs. (being lax and also allowing off-by-one)
throw Exception("Invalid time-to-show passed in RexEmotionIcon message!");
if (RexUUID::IsValid(params[1]))
{
RexUUID textureID(params[1]);
// We've been passed a texture UUID to show on the billboard.
///\todo request the asset and show that on the billboard.
}
else // We've been passed a string URL or a filename on the local computer.
{
///\todo Request a download from that URL and show the resulting image on the billboard.
// Now assuming that the textureID points to a local file, just to get a proof-of-concept something showing in the UI.
ApplyBillboard(*entity, params[1], timeToShow);
}
}
void InWorldChatModule::HandleChatFromSimulatorMessage(ProtocolUtilities::NetInMessage &msg)
{
msg.ResetReading();
std::string fromName = msg.ReadString();
RexUUID sourceId = msg.ReadUUID();
msg.SkipToFirstVariableByName("Message");
std::string message = msg.ReadString();
if (message.size() < 1)
return;
if (logging_)
{
if (!logFile_)
CreateLogFile();
if (logFile_)
{
std::stringstream ss;
ss << "[" << GetLocalTimeString() << "] " << fromName << ": " << message;
QTextStream out(logFile_);
out << ss.str().c_str() << "\n";
}
}
if (showChatBubbles_)
{
Scene::Entity *entity = GetEntityWithId(sourceId);
if (entity)
ApplyDefaultChatBubble(*entity, QString::fromUtf8(message.c_str()));
}
// Connect chat ui to this modules ChatReceived
// emit ChatReceived()
//if (chatWindow_)
// chatWindow_->ChatReceived(name, msg);
}
bool InWorldChatModule::CreateLogFile()
{
// Create filename. Format: "<server_name>_yyyy_dd_MM_<counter>.log"
// Use QSettings for getting the application settings home dir
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "realXtend", "chatlogs/");
QString path = settings.fileName();
path.replace(".ini", "");
QDir dir(path);
if (!dir.exists())
dir.mkpath(path);
QString filename = path;
QString server = currentWorldStream_->GetSimName().c_str();
// Protection against invalid characters and possible evil filename injections
server.replace('.', '_');
server.replace(' ', '_');
server.replace('\\', '_');
server.replace('/', '_');
server.replace(':', '_');
server.replace('*', '_');
server.replace('?', '_');
server.replace('\"', '_');
server.replace('<', '_');
server.replace('>', '_');
server.replace('|', '_');
filename.append(server);
filename.append('_');
filename.append(QDate::currentDate().toString("yyyy-MM-dd"));
// Create file
int fileSuffixCounter = 1;
logFile_ = new QFile;
while(!logFile_->isOpen() && fileSuffixCounter < 100)
{
QString file = filename + "_" + QString("%1.log").arg(fileSuffixCounter++);
if (!QFile::exists(file))
{
SAFE_DELETE(logFile_);
logFile_ = new QFile(file);
logFile_->open(QIODevice::WriteOnly | QIODevice::Text);
}
}
if (!logFile_->isOpen())
{
LogError("Could not create log file for chat logging.");
SAFE_DELETE(logFile_);
return false;
}
QTextStream log(logFile_);
QString entry = tr("Chat log created ") + QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss");
log << entry << "\n";
LogDebug(entry.toStdString());
return true;
}
/*
void InWorldChatModule::RepositionChatWidget(const QRectF &rect)
{
if (rect.isValid() && chatProxy_ && chatWidget_)
chatProxy_->setPos(rect.width()-chatWidget_->size().width(), rect.height()-chatWidget_->size().height());
}
*/
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
}
using namespace Naali;
POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(InWorldChatModule)
POCO_END_MANIFEST
<commit_msg>Fix compile error<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InWorldChatModule.cpp
* @brief Simple OpenSim world chat module. Listens for ChatFromSimulator packets and shows the chat on the UI.
* Outgoing chat sent using ChatFromViewer packets. Manages EC_ChatBubbles, EC_Billboards, chat logging etc.
* @note Depends on RexLogicModule so don't create dependency to this module.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "InWorldChatModule.h"
//#include "ChatWidget.h"
#include "EC_ChatBubble.h"
#include "EC_Billboard.h"
#include "EC_OpenSimPresence.h"
#include "ConsoleCommandServiceInterface.h"
#include "WorldStream.h"
#include "SceneManager.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "NetworkMessages/NetInMessage.h"
#include "CoreStringUtils.h"
#include "GenericMessageUtils.h"
#include "UiModule.h"
#include "ConfigurationManager.h"
//#include "EntityComponent/EC_OpenSimPresence.h"
#include "EntityComponent/EC_OpenSimPrim.h"
#include <QColor>
#include "MemoryLeakCheck.h"
namespace Naali
{
InWorldChatModule::InWorldChatModule() :
ModuleInterfaceImpl(NameStatic()),
networkStateEventCategory_(0),
networkInEventCategory_(0),
frameworkEventCategory_(0),
showChatBubbles_(true),
logging_(false),
logFile_(0)
//chatWidget_(0)
{
}
InWorldChatModule::~InWorldChatModule()
{
SAFE_DELETE(logFile_);
}
void InWorldChatModule::Load()
{
DECLARE_MODULE_EC(EC_Billboard);
DECLARE_MODULE_EC(EC_ChatBubble);
}
void InWorldChatModule::PostInitialize()
{
frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
if (frameworkEventCategory_ == 0)
LogError("Failed to query \"Framework\" event category");
uiModule_ = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices);
RegisterConsoleCommand(Console::CreateCommand("bbtest",
"Adds a billboard to each entity in the scene.",
Console::Bind(this, &InWorldChatModule::TestAddBillboard)));
RegisterConsoleCommand(Console::CreateCommand("chat",
"Sends a chat message. Usage: \"chat(message)\"",
Console::Bind(this, &InWorldChatModule::ConsoleChat)));
showChatBubbles_ = framework_->GetDefaultConfig().DeclareSetting("InWorldChatModule", "ShowChatBubbles", true);
logging_ = framework_->GetDefaultConfig().DeclareSetting("InWorldChatModule", "Logging", false);
}
void InWorldChatModule::Update(f64 frametime)
{
}
bool InWorldChatModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface *data)
{
if (category_id == frameworkEventCategory_)
{
if (event_id == Foundation::NETWORKING_REGISTERED)
{
ProtocolUtilities::NetworkingRegisteredEvent *event_data = checked_static_cast<ProtocolUtilities::NetworkingRegisteredEvent *>(data);
if (event_data)
{
networkStateEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
if (networkStateEventCategory_ == 0)
LogError("Failed to query \"NetworkState\" event category");
networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
if (networkInEventCategory_ == 0)
LogError("Failed to query \"NetworkIn\" event category");
return false;
}
}
if(event_id == Foundation::WORLD_STREAM_READY)
{
ProtocolUtilities::WorldStreamReadyEvent *event_data = checked_static_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
if (event_data)
currentWorldStream_ = event_data->WorldStream;
networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
if (networkInEventCategory_ == 0)
LogError("Failed to query \"NetworkIn\" event category");
return false;
}
}
if (category_id == networkStateEventCategory_)
{
if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
{
/*
if (!uiModule_.expired())
{
chatWidget_ = new ChatWidget(framework_);
connect(chatWidget_, SIGNAL(ChatEntered(const QString &)), this, SLOT(SendChatFromViewer(const QString &)));
chatProxy_ = uiModule_.lock()->GetSceneManager()->AddWidgetToScene(
chatWidget_, UiServices::UiWidgetProperties(QPointF(0,0), QSize(chatWidget_->size()), Qt::Widget, "InWorldChat", false, false));
connect(chatProxy_->scene(), SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(RepositionChatWidget(const QRectF &)));
RepositionChatWidget(chatProxy_->scene()->sceneRect());
chatProxy_->show();
*/
// Get settings.
showChatBubbles_ = framework_->GetDefaultConfig().GetSetting<bool>("InWorldChatModule", "ShowChatBubbles");
logging_ = framework_->GetDefaultConfig().GetSetting<bool>("InWorldChatModule", "Logging");
}
else if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED)
{
//SAFE_DELETE(chatWidget_);
// Save settings.
framework_->GetDefaultConfig().SetSetting<bool>("InWorldChatModule", "ShowChatBubbles", showChatBubbles_);
framework_->GetDefaultConfig().SetSetting<bool>("InWorldChatModule", "Logging", logging_);
}
}
if (category_id == networkInEventCategory_)
{
if (event_id != RexNetMsgGenericMessage && event_id != RexNetMsgChatFromSimulator)
return false;
using namespace ProtocolUtilities;
NetworkEventInboundData *netdata = checked_static_cast<NetworkEventInboundData *>(data);
assert(netdata);
if (!netdata)
return false;
ProtocolUtilities::NetInMessage &msg = *netdata->message;
switch(event_id)
{
case RexNetMsgGenericMessage:
if (ParseGenericMessageMethod(msg) == "RexEmotionIcon")
{
StringVector sv = ParseGenericMessageParameters(msg);
HandleRexEmotionIconMessage(sv);
}
return false;
case RexNetMsgChatFromSimulator:
HandleChatFromSimulatorMessage(msg);
return false;
default:
return false;
}
}
return false;
}
const std::string InWorldChatModule::moduleName = std::string("InWorldChatModule");
const std::string &InWorldChatModule::NameStatic()
{
return moduleName;
}
void InWorldChatModule::SendChatFromViewer(const QString &msg)
{
if (currentWorldStream_)
currentWorldStream_->SendChatFromViewerPacket(std::string(msg.toUtf8()));
}
Console::CommandResult InWorldChatModule::TestAddBillboard(const StringVector ¶ms)
{
Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
/// If/when there are multiple scenes at some day, have the SceneManager know the currently active one
/// instead of RexLogicModule, so no dependency to it is needed.
for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
{
Scene::EntityPtr entity = *iter;
entity->AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
EC_Billboard *billboard = entity->GetComponent<EC_Billboard>().get();
assert(billboard);
billboard->Show(Vector3df(0.f, 0.f, 1.5f), 10.f, "smoke.png");
}
return Console::ResultSuccess();
}
Console::CommandResult InWorldChatModule::ConsoleChat(const StringVector ¶ms)
{
if (params.size() == 0)
return Console::ResultFailure("Can't send empty chat message!");
SendChatFromViewer(params[0].c_str());
return Console::ResultSuccess();
}
void InWorldChatModule::ApplyDefaultChatBubble(Scene::Entity &entity, const QString &message)
{
Foundation::ComponentInterfacePtr component = entity.GetOrCreateComponent(EC_ChatBubble::TypeNameStatic());
assert(component.get());
EC_ChatBubble &chatBubble = *(checked_static_cast<EC_ChatBubble *>(component.get()));
chatBubble.ShowMessage(message);
}
void InWorldChatModule::ApplyBillboard(Scene::Entity &entity, const std::string &texture, float timeToShow)
{
boost::shared_ptr<EC_Billboard> ec_bb = entity.GetComponent<EC_Billboard>();
// If we didn't have the billboard component yet, create one now.
if (!ec_bb)
{
entity.AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
ec_bb = entity.GetComponent<EC_Billboard>();
assert(ec_bb.get());
}
ec_bb->Show(Vector3df(0.f, 0.f, 1.5f), timeToShow, texture.c_str());
}
Scene::Entity *InWorldChatModule::GetEntityWithId(const RexUUID &id)
{
Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
{
Scene::Entity &entity = **iter;
boost::shared_ptr<EC_OpenSimPresence> ec_presence = entity.GetComponent<EC_OpenSimPresence>();
boost::shared_ptr<RexLogic::EC_OpenSimPrim> ec_prim = entity.GetComponent<RexLogic::EC_OpenSimPrim>();
if (ec_presence)
{
if (ec_presence->agentId == id)
return &entity;
}
else if (ec_prim)
{
if (ec_prim->FullId == id)
return &entity;
}
}
return 0;
}
void InWorldChatModule::HandleRexEmotionIconMessage(StringVector ¶ms)
{
// Param 0: avatar UUID
// Param 1: texture ID
// Param 2: timeout (remember to replace any , with . before parsing)
if (params.size() < 3)
throw Exception("Failed to parse RexEmotionIcon message!");
LogInfo("Received RexEmotionIcon: " + params[0] + " " + params[1] + " " + params[2]);
ReplaceCharInplace(params[2], ',', '.');
if (!RexUUID::IsValid(params[0]))
throw Exception("Invalid Entity UUID passed in RexEmotionIcon message!");
RexUUID entityUUID(params[0]);
if (entityUUID.IsNull())
throw Exception("Null Entity UUID passed in RexEmotionIcon message!");
Scene::Entity *entity = GetEntityWithId(entityUUID);
if (!entity)
throw Exception("Received RexEmotionIcon message for a nonexisting entity!");
// timeToShow: value of [-1, 0[ denotes "infinite".
// a positive value between [0, 86400] denotes the number of seconds to show. (max roughly one day)
float timeToShow = atof(params[2].c_str());
if (!(timeToShow >= -2.f && timeToShow <= 86401.f)) // Checking through negation due to possible NaNs and infs. (being lax and also allowing off-by-one)
throw Exception("Invalid time-to-show passed in RexEmotionIcon message!");
if (RexUUID::IsValid(params[1]))
{
RexUUID textureID(params[1]);
// We've been passed a texture UUID to show on the billboard.
///\todo request the asset and show that on the billboard.
}
else // We've been passed a string URL or a filename on the local computer.
{
///\todo Request a download from that URL and show the resulting image on the billboard.
// Now assuming that the textureID points to a local file, just to get a proof-of-concept something showing in the UI.
ApplyBillboard(*entity, params[1], timeToShow);
}
}
void InWorldChatModule::HandleChatFromSimulatorMessage(ProtocolUtilities::NetInMessage &msg)
{
msg.ResetReading();
std::string fromName = msg.ReadString();
RexUUID sourceId = msg.ReadUUID();
msg.SkipToFirstVariableByName("Message");
std::string message = msg.ReadString();
if (message.size() < 1)
return;
if (logging_)
{
if (!logFile_)
CreateLogFile();
if (logFile_)
{
std::stringstream ss;
ss << "[" << GetLocalTimeString() << "] " << fromName << ": " << message;
QTextStream out(logFile_);
out << ss.str().c_str() << "\n";
}
}
if (showChatBubbles_)
{
Scene::Entity *entity = GetEntityWithId(sourceId);
if (entity)
ApplyDefaultChatBubble(*entity, QString::fromUtf8(message.c_str()));
}
// Connect chat ui to this modules ChatReceived
// emit ChatReceived()
//if (chatWindow_)
// chatWindow_->ChatReceived(name, msg);
}
bool InWorldChatModule::CreateLogFile()
{
// Create filename. Format: "<server_name>_yyyy_dd_MM_<counter>.log"
// Use QSettings for getting the application settings home dir
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "realXtend", "chatlogs/");
QString path = settings.fileName();
path.replace(".ini", "");
QDir dir(path);
if (!dir.exists())
dir.mkpath(path);
QString filename = path;
QString server = currentWorldStream_->GetSimName().c_str();
// Protection against invalid characters and possible evil filename injections
server.replace('.', '_');
server.replace(' ', '_');
server.replace('\\', '_');
server.replace('/', '_');
server.replace(':', '_');
server.replace('*', '_');
server.replace('?', '_');
server.replace('\"', '_');
server.replace('<', '_');
server.replace('>', '_');
server.replace('|', '_');
filename.append(server);
filename.append('_');
filename.append(QDate::currentDate().toString("yyyy-MM-dd"));
// Create file
int fileSuffixCounter = 1;
logFile_ = new QFile;
while(!logFile_->isOpen() && fileSuffixCounter < 100)
{
QString file = filename + "_" + QString("%1.log").arg(fileSuffixCounter++);
if (!QFile::exists(file))
{
SAFE_DELETE(logFile_);
logFile_ = new QFile(file);
logFile_->open(QIODevice::WriteOnly | QIODevice::Text);
}
}
if (!logFile_->isOpen())
{
LogError("Could not create log file for chat logging.");
SAFE_DELETE(logFile_);
return false;
}
QTextStream log(logFile_);
QString entry = tr("Chat log created ") + QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss");
log << entry << "\n";
LogDebug(entry.toStdString());
return true;
}
/*
void InWorldChatModule::RepositionChatWidget(const QRectF &rect)
{
if (rect.isValid() && chatProxy_ && chatWidget_)
chatProxy_->setPos(rect.width()-chatWidget_->size().width(), rect.height()-chatWidget_->size().height());
}
*/
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
}
using namespace Naali;
POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(InWorldChatModule)
POCO_END_MANIFEST
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MultiStock.hxx"
#include "stock/MapStock.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "util/djbhash.h"
#include "util/DeleteDisposer.hxx"
#include "util/StringAPI.hxx"
#include <cassert>
void
MultiStock::Item::Lease::ReleaseLease(bool _reuse) noexcept
{
item.DeleteLease(this, _reuse);
}
MultiStock::Item::~Item() noexcept
{
assert(leases.empty());
item.Put(!reuse);
}
void
MultiStock::Item::AddLease(StockGetHandler &handler,
LeasePtr &lease_ref) noexcept
{
lease_ref.Set(AddLease());
handler.OnStockItemReady(item);
}
inline void
MultiStock::Item::DeleteLease(Lease *lease, bool _reuse) noexcept
{
reuse &= _reuse;
assert(!leases.empty());
leases.erase_and_dispose(leases.iterator_to(*lease),
DeleteDisposer());
++remaining_leases;
parent.OnLeaseReleased(*this);
}
struct MultiStock::MapItem::Waiting final
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
Cancellable
{
MapItem &parent;
StockRequest request;
LeasePtr &lease_ref;
StockGetHandler &handler;
CancellablePointer &caller_cancel_ptr;
Waiting(MapItem &_parent, StockRequest &&_request,
LeasePtr &_lease_ref, StockGetHandler &_handler,
CancellablePointer &_cancel_ptr) noexcept
:parent(_parent), request(std::move(_request)),
lease_ref(_lease_ref), handler(_handler),
caller_cancel_ptr(_cancel_ptr)
{
caller_cancel_ptr = *this;
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
parent.RemoveWaiting(*this);
}
};
MultiStock::MapItem::MapItem(StockMap &_map_stock, Stock &_stock) noexcept
:map_stock(_map_stock), stock(_stock),
retry_event(stock.GetEventLoop(), BIND_THIS_METHOD(RetryWaiting))
{
map_stock.SetSticky(stock, true);
}
MultiStock::MapItem::~MapItem() noexcept
{
assert(items.empty());
assert(waiting.empty());
map_stock.SetSticky(stock, false);
if (get_cancel_ptr)
get_cancel_ptr.Cancel();
}
MultiStock::Item *
MultiStock::MapItem::FindUsable() noexcept
{ for (auto &i : items)
if (i.CanUse())
return &i;
return nullptr;
}
MultiStock::Item &
MultiStock::MapItem::GetNow(StockRequest request, unsigned max_leases)
{
if (auto *i = FindUsable())
return *i;
auto *stock_item = stock.GetNow(std::move(request));
assert(stock_item != nullptr);
auto *item = new Item(*this, *stock_item, max_leases);
items.push_back(*item);
return *item;
}
inline void
MultiStock::MapItem::Get(StockRequest request, unsigned max_leases,
LeasePtr &lease_ref,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (auto *i = FindUsable()) {
i->AddLease(handler, lease_ref);
return;
}
if (auto *stock_item = stock.GetIdle()) {
auto *i = new Item(*this, *stock_item, max_leases);
items.push_back(*i);
i->AddLease(handler, lease_ref);
return;
}
get_max_leases = max_leases;
auto *w = new Waiting(*this, std::move(request),
lease_ref, handler, cancel_ptr);
waiting.push_back(*w);
if (!stock.IsFull() && !get_cancel_ptr)
stock.GetCreate(std::move(w->request), *this, get_cancel_ptr);
}
inline void
MultiStock::MapItem::RemoveItem(Item &item) noexcept
{
items.erase_and_dispose(items.iterator_to(item), DeleteDisposer{});
if (items.empty() && !ScheduleRetryWaiting())
delete this;
}
inline void
MultiStock::MapItem::RemoveWaiting(Waiting &w) noexcept
{
waiting.erase_and_dispose(waiting.iterator_to(w), DeleteDisposer{});
if (!waiting.empty())
return;
if (retry_event.IsPending()) {
/* an item is ready, but was not yet delivered to the
Waiting; delete all empty items */
retry_event.Cancel();
DeleteEmptyItems();
}
if (items.empty())
delete this;
else if (get_cancel_ptr)
get_cancel_ptr.CancelAndClear();
}
inline void
MultiStock::MapItem::DeleteEmptyItems(const Item *except) noexcept
{
items.remove_and_dispose_if([except](const auto &item){
return &item != except && item.IsEmpty();
}, DeleteDisposer{});
}
inline void
MultiStock::MapItem::FinishWaiting(Item &item) noexcept
{
assert(item.CanUse());
assert(!waiting.empty());
auto &w = waiting.front();
/* if there is still a request object, move it to the
next item in the waiting list */
if (w.request)
if (auto n = std::next(waiting.begin());
n != waiting.end())
n->request = std::move(w.request);
auto &handler = w.handler;
auto &lease_ref = w.lease_ref;
waiting.pop_front_and_dispose(DeleteDisposer{});
/* do it again until no more usable items are
found */
if (!ScheduleRetryWaiting())
/* no more waiting: we can now remove all
remaining idle items which havn't been
removed while there were still waiting
items, but we had more empty items than we
really needed */
DeleteEmptyItems(&item);
item.AddLease(handler, lease_ref);
}
inline void
MultiStock::MapItem::RetryWaiting() noexcept
{
if (waiting.empty())
return;
if (auto *i = FindUsable()) {
FinishWaiting(*i);
return;
}
auto &w = waiting.front();
assert(w.request);
if (!stock.IsFull() && !get_cancel_ptr)
stock.GetCreate(std::move(w.request), *this, get_cancel_ptr);
}
bool
MultiStock::MapItem::ScheduleRetryWaiting() noexcept
{
if (waiting.empty())
return false;
retry_event.Schedule();
return true;
}
void
MultiStock::MapItem::OnStockItemReady(StockItem &stock_item) noexcept
{
assert(!waiting.empty());
get_cancel_ptr = nullptr;
auto *item = new Item(*this, stock_item, get_max_leases);
items.push_back(*item);
ScheduleRetryWaiting();
}
void
MultiStock::MapItem::OnStockItemError(std::exception_ptr error) noexcept
{
assert(!waiting.empty());
get_cancel_ptr = nullptr;
waiting.clear_and_dispose([&error](auto *w){
w->handler.OnStockItemError(error);
delete w;
});
if (items.empty())
delete this;
}
inline void
MultiStock::MapItem::OnLeaseReleased(Item &item) noexcept
{
/* now that a lease was released, schedule the "waiting" list
again */
if (ScheduleRetryWaiting() && item.CanUse())
/* somebody's waiting and the iten can be reused for
them - don't try to delete the item, even if it's
empty */
return;
if (item.IsEmpty())
RemoveItem(item);
}
inline std::size_t
MultiStock::MapItem::Hash::operator()(const char *key) const noexcept
{
assert(key != nullptr);
return djb_hash_string(key);
}
inline std::size_t
MultiStock::MapItem::Hash::operator()(const MapItem &value) const noexcept
{
return (*this)(value.stock.GetName());
}
inline bool
MultiStock::MapItem::Equal::operator()(const char *a, const MapItem &b) const noexcept
{
return StringIsEqual(a, b.stock.GetName());
}
inline bool
MultiStock::MapItem::Equal::operator()(const MapItem &a, const MapItem &b) const noexcept
{
return (*this)(a.stock.GetName(), b);
}
MultiStock::MultiStock(StockMap &_hstock) noexcept
:hstock(_hstock),
map(Map::bucket_traits(buckets, N_BUCKETS))
{
}
MultiStock::~MultiStock() noexcept
{
/* by now, all leases must be freed */
assert(map.empty());
}
MultiStock::MapItem &
MultiStock::MakeMapItem(const char *uri, void *request) noexcept
{
Map::insert_commit_data hint;
auto [i, inserted] =
map.insert_check(uri, map.hash_function(), map.key_eq(), hint);
if (inserted) {
auto *item = new MapItem(hstock,
hstock.GetStock(uri, request));
map.insert_commit(*item, hint);
return *item;
} else
return *i;
}
StockItem *
MultiStock::GetNow(const char *uri, StockRequest request,
unsigned max_leases,
LeasePtr &lease_ref)
{
return MakeMapItem(uri, request.get())
.GetNow(std::move(request), max_leases)
.AddLease(lease_ref);
}
void
MultiStock::Get(const char *uri, StockRequest request,
unsigned max_leases,
LeasePtr &lease_ref,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
MakeMapItem(uri, request.get())
.Get(std::move(request), max_leases,
lease_ref, handler, cancel_ptr);
}
<commit_msg>stock/MultiStock: add lease immediately in OnStockItemReady()<commit_after>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MultiStock.hxx"
#include "stock/MapStock.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "util/djbhash.h"
#include "util/DeleteDisposer.hxx"
#include "util/StringAPI.hxx"
#include <cassert>
void
MultiStock::Item::Lease::ReleaseLease(bool _reuse) noexcept
{
item.DeleteLease(this, _reuse);
}
MultiStock::Item::~Item() noexcept
{
assert(leases.empty());
item.Put(!reuse);
}
void
MultiStock::Item::AddLease(StockGetHandler &handler,
LeasePtr &lease_ref) noexcept
{
lease_ref.Set(AddLease());
handler.OnStockItemReady(item);
}
inline void
MultiStock::Item::DeleteLease(Lease *lease, bool _reuse) noexcept
{
reuse &= _reuse;
assert(!leases.empty());
leases.erase_and_dispose(leases.iterator_to(*lease),
DeleteDisposer());
++remaining_leases;
parent.OnLeaseReleased(*this);
}
struct MultiStock::MapItem::Waiting final
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
Cancellable
{
MapItem &parent;
StockRequest request;
LeasePtr &lease_ref;
StockGetHandler &handler;
CancellablePointer &caller_cancel_ptr;
Waiting(MapItem &_parent, StockRequest &&_request,
LeasePtr &_lease_ref, StockGetHandler &_handler,
CancellablePointer &_cancel_ptr) noexcept
:parent(_parent), request(std::move(_request)),
lease_ref(_lease_ref), handler(_handler),
caller_cancel_ptr(_cancel_ptr)
{
caller_cancel_ptr = *this;
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
parent.RemoveWaiting(*this);
}
};
MultiStock::MapItem::MapItem(StockMap &_map_stock, Stock &_stock) noexcept
:map_stock(_map_stock), stock(_stock),
retry_event(stock.GetEventLoop(), BIND_THIS_METHOD(RetryWaiting))
{
map_stock.SetSticky(stock, true);
}
MultiStock::MapItem::~MapItem() noexcept
{
assert(items.empty());
assert(waiting.empty());
map_stock.SetSticky(stock, false);
if (get_cancel_ptr)
get_cancel_ptr.Cancel();
}
MultiStock::Item *
MultiStock::MapItem::FindUsable() noexcept
{ for (auto &i : items)
if (i.CanUse())
return &i;
return nullptr;
}
MultiStock::Item &
MultiStock::MapItem::GetNow(StockRequest request, unsigned max_leases)
{
if (auto *i = FindUsable())
return *i;
auto *stock_item = stock.GetNow(std::move(request));
assert(stock_item != nullptr);
auto *item = new Item(*this, *stock_item, max_leases);
items.push_back(*item);
return *item;
}
inline void
MultiStock::MapItem::Get(StockRequest request, unsigned max_leases,
LeasePtr &lease_ref,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (auto *i = FindUsable()) {
i->AddLease(handler, lease_ref);
return;
}
if (auto *stock_item = stock.GetIdle()) {
auto *i = new Item(*this, *stock_item, max_leases);
items.push_back(*i);
i->AddLease(handler, lease_ref);
return;
}
get_max_leases = max_leases;
auto *w = new Waiting(*this, std::move(request),
lease_ref, handler, cancel_ptr);
waiting.push_back(*w);
if (!stock.IsFull() && !get_cancel_ptr)
stock.GetCreate(std::move(w->request), *this, get_cancel_ptr);
}
inline void
MultiStock::MapItem::RemoveItem(Item &item) noexcept
{
items.erase_and_dispose(items.iterator_to(item), DeleteDisposer{});
if (items.empty() && !ScheduleRetryWaiting())
delete this;
}
inline void
MultiStock::MapItem::RemoveWaiting(Waiting &w) noexcept
{
waiting.erase_and_dispose(waiting.iterator_to(w), DeleteDisposer{});
if (!waiting.empty())
return;
if (retry_event.IsPending()) {
/* an item is ready, but was not yet delivered to the
Waiting; delete all empty items */
retry_event.Cancel();
DeleteEmptyItems();
}
if (items.empty())
delete this;
else if (get_cancel_ptr)
get_cancel_ptr.CancelAndClear();
}
inline void
MultiStock::MapItem::DeleteEmptyItems(const Item *except) noexcept
{
items.remove_and_dispose_if([except](const auto &item){
return &item != except && item.IsEmpty();
}, DeleteDisposer{});
}
inline void
MultiStock::MapItem::FinishWaiting(Item &item) noexcept
{
assert(item.CanUse());
assert(!waiting.empty());
auto &w = waiting.front();
/* if there is still a request object, move it to the
next item in the waiting list */
if (w.request)
if (auto n = std::next(waiting.begin());
n != waiting.end())
n->request = std::move(w.request);
auto &handler = w.handler;
auto &lease_ref = w.lease_ref;
waiting.pop_front_and_dispose(DeleteDisposer{});
/* do it again until no more usable items are
found */
if (!ScheduleRetryWaiting())
/* no more waiting: we can now remove all
remaining idle items which havn't been
removed while there were still waiting
items, but we had more empty items than we
really needed */
DeleteEmptyItems(&item);
item.AddLease(handler, lease_ref);
}
inline void
MultiStock::MapItem::RetryWaiting() noexcept
{
if (waiting.empty())
return;
if (auto *i = FindUsable()) {
FinishWaiting(*i);
return;
}
auto &w = waiting.front();
assert(w.request);
if (!stock.IsFull() && !get_cancel_ptr)
stock.GetCreate(std::move(w.request), *this, get_cancel_ptr);
}
bool
MultiStock::MapItem::ScheduleRetryWaiting() noexcept
{
if (waiting.empty())
return false;
retry_event.Schedule();
return true;
}
void
MultiStock::MapItem::OnStockItemReady(StockItem &stock_item) noexcept
{
assert(!waiting.empty());
get_cancel_ptr = nullptr;
auto *item = new Item(*this, stock_item, get_max_leases);
items.push_back(*item);
FinishWaiting(*item);
}
void
MultiStock::MapItem::OnStockItemError(std::exception_ptr error) noexcept
{
assert(!waiting.empty());
get_cancel_ptr = nullptr;
waiting.clear_and_dispose([&error](auto *w){
w->handler.OnStockItemError(error);
delete w;
});
if (items.empty())
delete this;
}
inline void
MultiStock::MapItem::OnLeaseReleased(Item &item) noexcept
{
/* now that a lease was released, schedule the "waiting" list
again */
if (ScheduleRetryWaiting() && item.CanUse())
/* somebody's waiting and the iten can be reused for
them - don't try to delete the item, even if it's
empty */
return;
if (item.IsEmpty())
RemoveItem(item);
}
inline std::size_t
MultiStock::MapItem::Hash::operator()(const char *key) const noexcept
{
assert(key != nullptr);
return djb_hash_string(key);
}
inline std::size_t
MultiStock::MapItem::Hash::operator()(const MapItem &value) const noexcept
{
return (*this)(value.stock.GetName());
}
inline bool
MultiStock::MapItem::Equal::operator()(const char *a, const MapItem &b) const noexcept
{
return StringIsEqual(a, b.stock.GetName());
}
inline bool
MultiStock::MapItem::Equal::operator()(const MapItem &a, const MapItem &b) const noexcept
{
return (*this)(a.stock.GetName(), b);
}
MultiStock::MultiStock(StockMap &_hstock) noexcept
:hstock(_hstock),
map(Map::bucket_traits(buckets, N_BUCKETS))
{
}
MultiStock::~MultiStock() noexcept
{
/* by now, all leases must be freed */
assert(map.empty());
}
MultiStock::MapItem &
MultiStock::MakeMapItem(const char *uri, void *request) noexcept
{
Map::insert_commit_data hint;
auto [i, inserted] =
map.insert_check(uri, map.hash_function(), map.key_eq(), hint);
if (inserted) {
auto *item = new MapItem(hstock,
hstock.GetStock(uri, request));
map.insert_commit(*item, hint);
return *item;
} else
return *i;
}
StockItem *
MultiStock::GetNow(const char *uri, StockRequest request,
unsigned max_leases,
LeasePtr &lease_ref)
{
return MakeMapItem(uri, request.get())
.GetNow(std::move(request), max_leases)
.AddLease(lease_ref);
}
void
MultiStock::Get(const char *uri, StockRequest request,
unsigned max_leases,
LeasePtr &lease_ref,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
MakeMapItem(uri, request.get())
.Get(std::move(request), max_leases,
lease_ref, handler, cancel_ptr);
}
<|endoftext|>
|
<commit_before>
#include <gloperate-qtquick/viewer/QmlEngine.h>
#include <QVariant>
#include <QQmlContext>
#include <QJSValueIterator>
#include <cppexpose/reflection/Property.h>
#include <cppexpose/typed/DirectValue.h>
#include <cppassist/io/FilePath.h>
#include <gloperate/gloperate.h>
#include <gloperate/viewer/ViewerContext.h>
#include <gloperate/scripting/ScriptEnvironment.h>
#include <gloperate-qtquick/controls/TextController.h>
#include <gloperate-qtquick/viewer/RenderItem.h>
#include <gloperate-qtquick/viewer/QmlScriptFunction.h>
namespace gloperate_qtquick
{
QmlEngine::QmlEngine(gloperate::ViewerContext * viewerContext)
: m_viewerContext(viewerContext)
{
// Register QML types
qmlRegisterType<RenderItem> ("gloperate.rendering", 1, 0, "RenderItem");
qmlRegisterType<TextController>("gloperate.ui", 1, 0, "TextController");
// Add gloperate qml-libraries
std::string importPath = gloperate::dataPath() + "/gloperate/qml/GLOperate/Ui";
addImportPath(QString::fromStdString(importPath));
// Register global functions and properties
rootContext()->setContextObject(this);
// Create global objects
m_global = newObject();
m_gloperate = newObject();
}
QmlEngine::~QmlEngine()
{
}
gloperate::ViewerContext * QmlEngine::viewerContext() const
{
return m_viewerContext;
}
QString QmlEngine::execute(const QString & code)
{
return QString::fromStdString(
m_viewerContext->scriptEnvironment()->execute(code.toStdString()).value<std::string>()
);
}
cppexpose::Variant QmlEngine::fromScriptValue(const QJSValue & value)
{
if (value.isBool()) {
return cppexpose::Variant(value.toBool());
}
else if (value.isNumber()) {
return cppexpose::Variant(value.toNumber());
}
else if (value.isString()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isRegExp()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isError()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isDate()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isCallable()) {
// [TODO] This produces a memory leak, since the pointer to the function object will never be deleted.
// A solution would be to wrap a ref_ptr into the variant, but since there are also function objects
// which are not memory-managed (e.g., a C-function that has been passed to the scripting engine),
// it would be hard to determine the right use of function-variants.
// The script context could of course manage a list of created functions an delete them on destruction,
// but that would not solve the problem of "memory leak" while the program is running.
QmlScriptFunction * function = new QmlScriptFunction(this, value);
return cppexpose::Variant::fromValue<cppexpose::AbstractFunction *>(function);
}
else if (value.isArray()) {
cppexpose::VariantArray array;
QJSValueIterator it(value);
while (it.next())
{
if (it.hasNext()) // Skip last item (length)
{
array.push_back(fromScriptValue(it.value()));
}
}
return array;
}
else if (value.isObject()) {
cppexpose::VariantMap obj;
QJSValueIterator it(value);
while (it.next())
{
obj[it.name().toStdString()] = fromScriptValue(it.value());
}
return obj;
}
else {
return cppexpose::Variant();
}
}
QJSValue QmlEngine::toScriptValue(const cppexpose::Variant & var)
{
if (var.hasType<char>()) {
return QJSValue(var.value<char>());
}
else if (var.hasType<unsigned char>()) {
return QJSValue(var.value<unsigned char>());
}
else if (var.hasType<short>()) {
return QJSValue(var.value<short>());
}
else if (var.hasType<unsigned short>()) {
return QJSValue(var.value<unsigned short>());
}
else if (var.hasType<int>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned int>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<long>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned long>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<long long>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned long long>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<float>()) {
return QJSValue(var.value<float>());
}
else if (var.hasType<double>()) {
return QJSValue(var.value<double>());
}
else if (var.hasType<char*>()) {
return QJSValue(var.value<char*>());
}
else if (var.hasType<std::string>()) {
return QJSValue(var.value<std::string>().c_str());
}
else if (var.hasType<bool>()) {
return QJSValue(var.value<bool>());
}
else if (var.hasType<cppassist::FilePath>()) {
return QJSValue(var.value<cppassist::FilePath>().path().c_str());
}
else if (var.hasType<cppexpose::VariantArray>()) {
QJSValue array = newArray();
cppexpose::VariantArray variantArray = var.value<cppexpose::VariantArray>();
for (unsigned int i=0; i<variantArray.size(); i++) {
array.setProperty(i, toScriptValue(variantArray.at(i)));
}
return array;
}
else if (var.hasType<cppexpose::VariantMap>()) {
QJSValue obj = newObject();
cppexpose::VariantMap variantMap = var.value<cppexpose::VariantMap>();
for (const std::pair<std::string, cppexpose::Variant> & pair : variantMap)
{
obj.setProperty(pair.first.c_str(), toScriptValue(pair.second));
}
return obj;
}
else {
return QJSValue();
}
}
cppexpose::Variant QmlEngine::fromQVariant(const QVariant & value)
{
if (value.type() == QVariant::Bool) {
return cppexpose::Variant(value.toBool());
}
else if (value.type() == QVariant::Char || value.type() == QVariant::Int) {
return cppexpose::Variant(value.toInt());
}
else if (value.type() == QVariant::UInt) {
return cppexpose::Variant(value.toUInt());
}
else if (value.type() == QVariant::LongLong) {
return cppexpose::Variant(value.toLongLong());
}
else if (value.type() == QVariant::ULongLong) {
return cppexpose::Variant(value.toULongLong());
}
else if (value.type() == QVariant::Double) {
return cppexpose::Variant(value.toDouble());
}
else if (value.type() == QVariant::StringList)
{
cppexpose::VariantArray array;
QStringList list = value.toStringList();
for (QStringList::iterator it = list.begin(); it != list.end(); ++it)
{
array.push_back( cppexpose::Variant((*it).toStdString()) );
}
return array;
}
else if (value.type() == QVariant::List)
{
cppexpose::VariantArray array;
QList<QVariant> list = value.toList();
for (QList<QVariant>::iterator it = list.begin(); it != list.end(); ++it)
{
array.push_back(fromQVariant(*it));
}
return array;
}
else if (value.type() == QVariant::Map)
{
cppexpose::VariantMap obj;
QMap<QString, QVariant> map = value.toMap();
for (QMap<QString, QVariant>::iterator it = map.begin(); it != map.end(); ++it)
{
std::string key = it.key().toStdString();
obj[key] = fromQVariant(it.value());
}
return obj;
}
else if (value.type() == QVariant::String || value.canConvert(QVariant::String))
{
return cppexpose::Variant(value.toString().toStdString());
}
else {
return cppexpose::Variant();
}
}
const QJSValue & QmlEngine::global() const
{
return m_global;
}
void QmlEngine::setGlobal(const QJSValue & obj)
{
m_global = obj;
}
const QJSValue & QmlEngine::gloperate() const
{
return m_gloperate;
}
void QmlEngine::setGloperate(const QJSValue & obj)
{
m_gloperate = obj;
}
} // namespace gloperate_qtquick
<commit_msg>Adjust qml scripting backend to use cppexpose::Function, example works again with qml scripting<commit_after>
#include <gloperate-qtquick/viewer/QmlEngine.h>
#include <QVariant>
#include <QQmlContext>
#include <QJSValueIterator>
#include <cppexpose/reflection/Property.h>
#include <cppexpose/typed/DirectValue.h>
#include <cppexpose/function/Function.h>
#include <cppassist/io/FilePath.h>
#include <gloperate/gloperate.h>
#include <gloperate/viewer/ViewerContext.h>
#include <gloperate/scripting/ScriptEnvironment.h>
#include <gloperate-qtquick/controls/TextController.h>
#include <gloperate-qtquick/viewer/RenderItem.h>
#include <gloperate-qtquick/viewer/QmlScriptFunction.h>
namespace gloperate_qtquick
{
QmlEngine::QmlEngine(gloperate::ViewerContext * viewerContext)
: m_viewerContext(viewerContext)
{
// Register QML types
qmlRegisterType<RenderItem> ("gloperate.rendering", 1, 0, "RenderItem");
qmlRegisterType<TextController>("gloperate.ui", 1, 0, "TextController");
// Add gloperate qml-libraries
std::string importPath = gloperate::dataPath() + "/gloperate/qml/GLOperate/Ui";
addImportPath(QString::fromStdString(importPath));
// Register global functions and properties
rootContext()->setContextObject(this);
// Create global objects
m_global = newObject();
m_gloperate = newObject();
}
QmlEngine::~QmlEngine()
{
}
gloperate::ViewerContext * QmlEngine::viewerContext() const
{
return m_viewerContext;
}
QString QmlEngine::execute(const QString & code)
{
return QString::fromStdString(
m_viewerContext->scriptEnvironment()->execute(code.toStdString()).value<std::string>()
);
}
cppexpose::Variant QmlEngine::fromScriptValue(const QJSValue & value)
{
if (value.isBool()) {
return cppexpose::Variant(value.toBool());
}
else if (value.isNumber()) {
return cppexpose::Variant(value.toNumber());
}
else if (value.isString()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isRegExp()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isError()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isDate()) {
return cppexpose::Variant(value.toString().toStdString());
}
else if (value.isCallable()) {
cppexpose::Function function("", new QmlScriptFunction(this, value));
return cppexpose::Variant::fromValue<cppexpose::Function>(function);
}
else if (value.isArray()) {
cppexpose::VariantArray array;
QJSValueIterator it(value);
while (it.next())
{
if (it.hasNext()) // Skip last item (length)
{
array.push_back(fromScriptValue(it.value()));
}
}
return array;
}
else if (value.isObject()) {
cppexpose::VariantMap obj;
QJSValueIterator it(value);
while (it.next())
{
obj[it.name().toStdString()] = fromScriptValue(it.value());
}
return obj;
}
else {
return cppexpose::Variant();
}
}
QJSValue QmlEngine::toScriptValue(const cppexpose::Variant & var)
{
if (var.hasType<char>()) {
return QJSValue(var.value<char>());
}
else if (var.hasType<unsigned char>()) {
return QJSValue(var.value<unsigned char>());
}
else if (var.hasType<short>()) {
return QJSValue(var.value<short>());
}
else if (var.hasType<unsigned short>()) {
return QJSValue(var.value<unsigned short>());
}
else if (var.hasType<int>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned int>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<long>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned long>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<long long>()) {
return QJSValue(var.value<int>());
}
else if (var.hasType<unsigned long long>()) {
return QJSValue(var.value<unsigned int>());
}
else if (var.hasType<float>()) {
return QJSValue(var.value<float>());
}
else if (var.hasType<double>()) {
return QJSValue(var.value<double>());
}
else if (var.hasType<char*>()) {
return QJSValue(var.value<char*>());
}
else if (var.hasType<std::string>()) {
return QJSValue(var.value<std::string>().c_str());
}
else if (var.hasType<bool>()) {
return QJSValue(var.value<bool>());
}
else if (var.hasType<cppassist::FilePath>()) {
return QJSValue(var.value<cppassist::FilePath>().path().c_str());
}
else if (var.hasType<cppexpose::VariantArray>()) {
QJSValue array = newArray();
cppexpose::VariantArray variantArray = var.value<cppexpose::VariantArray>();
for (unsigned int i=0; i<variantArray.size(); i++) {
array.setProperty(i, toScriptValue(variantArray.at(i)));
}
return array;
}
else if (var.hasType<cppexpose::VariantMap>()) {
QJSValue obj = newObject();
cppexpose::VariantMap variantMap = var.value<cppexpose::VariantMap>();
for (const std::pair<std::string, cppexpose::Variant> & pair : variantMap)
{
obj.setProperty(pair.first.c_str(), toScriptValue(pair.second));
}
return obj;
}
else {
return QJSValue();
}
}
cppexpose::Variant QmlEngine::fromQVariant(const QVariant & value)
{
if (value.type() == QVariant::Bool) {
return cppexpose::Variant(value.toBool());
}
else if (value.type() == QVariant::Char || value.type() == QVariant::Int) {
return cppexpose::Variant(value.toInt());
}
else if (value.type() == QVariant::UInt) {
return cppexpose::Variant(value.toUInt());
}
else if (value.type() == QVariant::LongLong) {
return cppexpose::Variant(value.toLongLong());
}
else if (value.type() == QVariant::ULongLong) {
return cppexpose::Variant(value.toULongLong());
}
else if (value.type() == QVariant::Double) {
return cppexpose::Variant(value.toDouble());
}
else if (value.type() == QVariant::StringList)
{
cppexpose::VariantArray array;
QStringList list = value.toStringList();
for (QStringList::iterator it = list.begin(); it != list.end(); ++it)
{
array.push_back( cppexpose::Variant((*it).toStdString()) );
}
return array;
}
else if (value.type() == QVariant::List)
{
cppexpose::VariantArray array;
QList<QVariant> list = value.toList();
for (QList<QVariant>::iterator it = list.begin(); it != list.end(); ++it)
{
array.push_back(fromQVariant(*it));
}
return array;
}
else if (value.type() == QVariant::Map)
{
cppexpose::VariantMap obj;
QMap<QString, QVariant> map = value.toMap();
for (QMap<QString, QVariant>::iterator it = map.begin(); it != map.end(); ++it)
{
std::string key = it.key().toStdString();
obj[key] = fromQVariant(it.value());
}
return obj;
}
else if (value.type() == QVariant::String || value.canConvert(QVariant::String))
{
return cppexpose::Variant(value.toString().toStdString());
}
else {
return cppexpose::Variant();
}
}
const QJSValue & QmlEngine::global() const
{
return m_global;
}
void QmlEngine::setGlobal(const QJSValue & obj)
{
m_global = obj;
}
const QJSValue & QmlEngine::gloperate() const
{
return m_gloperate;
}
void QmlEngine::setGloperate(const QJSValue & obj)
{
m_gloperate = obj;
}
} // namespace gloperate_qtquick
<|endoftext|>
|
<commit_before>/* example functions */
#include <iostream>
#include <time.h>
#include "egfunc.h"
double arith(double x, double y, int type)
{
double ans;
switch(type)
{
case 1:
ans = x+y;
std::cout << x << " + " << y << " = " << ans << std::endl;
break;
case 2:
ans = x-y;
std::cout << x << " - " << y << " = " << ans << std::endl;
break;
case 3:
ans = x*y;
std::cout << x << " * " << y << " = " << ans << std::endl;
break;
case 4:
ans = x/y;
std::cout << x << " / " << y << " = " << ans << std::endl;
break;
default:
std::cout << "Unknown operation!";
}
return ans;
}
int shoe()
{
int shoes;
std::cout << "number of shoes? ";
std::cin >> shoes;
if (shoes%2 != 0)
std::cout << "not in pairs\n";
else
std::cout << "thats " << shoes/2 << " pairs\n" << std::endl;
return shoes/2;
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
<commit_msg>remove old files with bad names and format<commit_after><|endoftext|>
|
<commit_before>#include "tests-base.hpp"
extern "C" {
#include "../normalization.h"
}
TEST(ResolveDecomposition, Found)
{
int32_t r = 0;
const char* d = resolvedecomposition(0xf, &r);
EXPECT_STREQ("\x33\x00\x20\xcc\x81", d);
EXPECT_EQ(FindResult_Found, r);
}
TEST(ResolveDecomposition, OffsetZero)
{
int32_t r = 0;
const char* d = resolvedecomposition(0, &r);
EXPECT_EQ(nullptr, d);
EXPECT_EQ(FindResult_Invalid, r);
}
TEST(ResolveDecomposition, OffsetOutOfBounds)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x00FFFFFF, &r);
EXPECT_EQ(nullptr, d);
EXPECT_EQ(FindResult_OutOfBounds, r);
}<commit_msg>resolvedecomposition: Added tests for finding first and last offset.<commit_after>#include "tests-base.hpp"
extern "C" {
#include "../normalization.h"
}
TEST(ResolveDecomposition, Found)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x0000000F, &r);
EXPECT_STREQ("\x33\x00\x20\xcc\x81", d);
EXPECT_EQ(FindResult_Found, r);
}
TEST(ResolveDecomposition, FoundFirst)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x00000001, &r);
EXPECT_STREQ("\x20", d);
EXPECT_EQ(FindResult_Found, r);
}
TEST(ResolveDecomposition, FoundLast)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x00007FF5, &r);
EXPECT_STREQ("\xE1\x84\x83\xE1\x85\xAE\xE1\x86\xAF", d);
EXPECT_EQ(FindResult_Found, r);
}
TEST(ResolveDecomposition, FoundWrongOffset)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x0000000E, &r);
EXPECT_STREQ("", d);
EXPECT_EQ(FindResult_Found, r);
}
TEST(ResolveDecomposition, OffsetZero)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x00000000, &r);
EXPECT_EQ(nullptr, d);
EXPECT_EQ(FindResult_Invalid, r);
}
TEST(ResolveDecomposition, OffsetOutOfBounds)
{
int32_t r = 0;
const char* d = resolvedecomposition(0x00FFFFFF, &r);
EXPECT_EQ(nullptr, d);
EXPECT_EQ(FindResult_OutOfBounds, r);
}<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REALM_OS_SYNC_CONFIG_HPP
#define REALM_OS_SYNC_CONFIG_HPP
#include "sync_user.hpp"
#include "sync_manager.hpp"
#include <realm/util/assert.hpp>
#include <realm/sync/client.hpp>
#include <realm/sync/protocol.hpp>
#include <functional>
#include <memory>
#include <string>
#include <system_error>
#include <unordered_map>
#include <realm/sync/history.hpp>
namespace realm {
class SyncUser;
class SyncSession;
using ChangesetTransformer = sync::ClientHistory::ChangesetCooker;
enum class SyncSessionStopPolicy;
struct SyncConfig;
using SyncBindSessionHandler = void(const std::string&, // path on disk of the Realm file.
const SyncConfig&, // the sync configuration object.
std::shared_ptr<SyncSession> // the session which should be bound.
);
struct SyncError;
using SyncSessionErrorHandler = void(std::shared_ptr<SyncSession>, SyncError);
struct SyncError {
using ProtocolError = realm::sync::ProtocolError;
std::error_code error_code;
std::string message;
bool is_fatal;
std::unordered_map<std::string, std::string> user_info;
/// The sync server may send down an error that the client does not recognize,
/// whether because of a version mismatch or an oversight. It is still valuable
/// to expose these errors so that users can do something about them.
bool is_unrecognized_by_client = false;
SyncError(std::error_code error_code, std::string message, bool is_fatal)
: error_code(std::move(error_code))
, message(std::move(message))
, is_fatal(is_fatal)
{
}
static constexpr const char c_original_file_path_key[] = "ORIGINAL_FILE_PATH";
static constexpr const char c_recovery_file_path_key[] = "RECOVERY_FILE_PATH";
/// The error is a client error, which applies to the client and all its sessions.
bool is_client_error() const
{
return error_code.category() == realm::sync::client_error_category();
}
/// The error is a protocol error, which may either be connection-level or session-level.
bool is_connection_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return !realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error is a connection-level protocol error.
bool is_session_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error indicates a client reset situation.
bool is_client_reset_requested() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
// Documented here: https://realm.io/docs/realm-object-server/#client-recovery-from-a-backup
return (error_code == ProtocolError::bad_server_file_ident
|| error_code == ProtocolError::bad_client_file_ident
|| error_code == ProtocolError::bad_server_version
|| error_code == ProtocolError::diverging_histories);
}
};
enum class ClientResyncMode {
// Enable automatic client resync with local transaction recovery
Recover,
// Enable automatic client resync without local transaction recovery
DiscardLocal,
// Fire a client reset error
Manual
};
struct SyncConfig {
using ProxyConfig = sync::Session::Config::ProxyConfig;
std::shared_ptr<SyncUser> user;
// The URL of the Realm, or of the reference Realm if partial sync is being used.
// The URL that will be used when connecting to the object server is that returned by `realm_url()`,
// and will differ from `reference_realm_url` if partial sync is being used.
// Set this field, but read from `realm_url()`.
std::string reference_realm_url;
SyncSessionStopPolicy stop_policy = SyncSessionStopPolicy::AfterChangesUploaded;
std::function<SyncBindSessionHandler> bind_session_handler;
std::function<SyncSessionErrorHandler> error_handler;
std::shared_ptr<ChangesetTransformer> transformer;
util::Optional<std::array<char, 64>> realm_encryption_key;
bool client_validate_ssl = true;
util::Optional<std::string> ssl_trust_certificate_path;
std::function<sync::Session::SSLVerifyCallback> ssl_verify_callback;
util::Optional<ProxyConfig> proxy_config;
bool is_partial = false;
util::Optional<std::string> custom_partial_sync_identifier;
bool validate_sync_history = true;
util::Optional<std::string> authorization_header_name;
std::map<std::string, std::string> custom_http_headers;
// Set the URL path prefix sync will use when opening a websocket for this session. Default is `/realm-sync`.
// Useful when the sync worker sits behind a firewall or load-balancer that rewrites incoming requests.
util::Optional<std::string> url_prefix = none;
// The name of the directory which Realms should be backed up to following
// a client reset
util::Optional<std::string> recovery_directory;
ClientResyncMode client_resync_mode = ClientResyncMode::Recover;
// The URL that will be used when connecting to the object server.
// This will differ from `reference_realm_url` when partial sync is being used.
std::string realm_url() const;
SyncConfig(std::shared_ptr<SyncUser> user, std::string reference_realm_url)
: user(std::move(user))
, reference_realm_url(std::move(reference_realm_url))
{
if (this->reference_realm_url.find("/__partial/") != npos)
throw std::invalid_argument("A Realm URL may not contain the reserved string \"/__partial/\".");
}
// Construct an identifier for this partially synced Realm by combining client and user identifiers.
static std::string partial_sync_identifier(const SyncUser& user);
};
} // namespace realm
#endif // REALM_OS_SYNC_CONFIG_HPP
<commit_msg>Make ClientResyncMode an unsigned char (#837)<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REALM_OS_SYNC_CONFIG_HPP
#define REALM_OS_SYNC_CONFIG_HPP
#include "sync_user.hpp"
#include "sync_manager.hpp"
#include <realm/util/assert.hpp>
#include <realm/sync/client.hpp>
#include <realm/sync/protocol.hpp>
#include <functional>
#include <memory>
#include <string>
#include <system_error>
#include <unordered_map>
#include <realm/sync/history.hpp>
namespace realm {
class SyncUser;
class SyncSession;
using ChangesetTransformer = sync::ClientHistory::ChangesetCooker;
enum class SyncSessionStopPolicy;
struct SyncConfig;
using SyncBindSessionHandler = void(const std::string&, // path on disk of the Realm file.
const SyncConfig&, // the sync configuration object.
std::shared_ptr<SyncSession> // the session which should be bound.
);
struct SyncError;
using SyncSessionErrorHandler = void(std::shared_ptr<SyncSession>, SyncError);
struct SyncError {
using ProtocolError = realm::sync::ProtocolError;
std::error_code error_code;
std::string message;
bool is_fatal;
std::unordered_map<std::string, std::string> user_info;
/// The sync server may send down an error that the client does not recognize,
/// whether because of a version mismatch or an oversight. It is still valuable
/// to expose these errors so that users can do something about them.
bool is_unrecognized_by_client = false;
SyncError(std::error_code error_code, std::string message, bool is_fatal)
: error_code(std::move(error_code))
, message(std::move(message))
, is_fatal(is_fatal)
{
}
static constexpr const char c_original_file_path_key[] = "ORIGINAL_FILE_PATH";
static constexpr const char c_recovery_file_path_key[] = "RECOVERY_FILE_PATH";
/// The error is a client error, which applies to the client and all its sessions.
bool is_client_error() const
{
return error_code.category() == realm::sync::client_error_category();
}
/// The error is a protocol error, which may either be connection-level or session-level.
bool is_connection_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return !realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error is a connection-level protocol error.
bool is_session_level_protocol_error() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
return realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
}
/// The error indicates a client reset situation.
bool is_client_reset_requested() const
{
if (error_code.category() != realm::sync::protocol_error_category()) {
return false;
}
// Documented here: https://realm.io/docs/realm-object-server/#client-recovery-from-a-backup
return (error_code == ProtocolError::bad_server_file_ident
|| error_code == ProtocolError::bad_client_file_ident
|| error_code == ProtocolError::bad_server_version
|| error_code == ProtocolError::diverging_histories);
}
};
enum class ClientResyncMode : unsigned char {
// Enable automatic client resync with local transaction recovery
Recover = 0,
// Enable automatic client resync without local transaction recovery
DiscardLocal = 1,
// Fire a client reset error
Manual = 2,
};
struct SyncConfig {
using ProxyConfig = sync::Session::Config::ProxyConfig;
std::shared_ptr<SyncUser> user;
// The URL of the Realm, or of the reference Realm if partial sync is being used.
// The URL that will be used when connecting to the object server is that returned by `realm_url()`,
// and will differ from `reference_realm_url` if partial sync is being used.
// Set this field, but read from `realm_url()`.
std::string reference_realm_url;
SyncSessionStopPolicy stop_policy = SyncSessionStopPolicy::AfterChangesUploaded;
std::function<SyncBindSessionHandler> bind_session_handler;
std::function<SyncSessionErrorHandler> error_handler;
std::shared_ptr<ChangesetTransformer> transformer;
util::Optional<std::array<char, 64>> realm_encryption_key;
bool client_validate_ssl = true;
util::Optional<std::string> ssl_trust_certificate_path;
std::function<sync::Session::SSLVerifyCallback> ssl_verify_callback;
util::Optional<ProxyConfig> proxy_config;
bool is_partial = false;
util::Optional<std::string> custom_partial_sync_identifier;
bool validate_sync_history = true;
util::Optional<std::string> authorization_header_name;
std::map<std::string, std::string> custom_http_headers;
// Set the URL path prefix sync will use when opening a websocket for this session. Default is `/realm-sync`.
// Useful when the sync worker sits behind a firewall or load-balancer that rewrites incoming requests.
util::Optional<std::string> url_prefix = none;
// The name of the directory which Realms should be backed up to following
// a client reset
util::Optional<std::string> recovery_directory;
ClientResyncMode client_resync_mode = ClientResyncMode::Recover;
// The URL that will be used when connecting to the object server.
// This will differ from `reference_realm_url` when partial sync is being used.
std::string realm_url() const;
SyncConfig(std::shared_ptr<SyncUser> user, std::string reference_realm_url)
: user(std::move(user))
, reference_realm_url(std::move(reference_realm_url))
{
if (this->reference_realm_url.find("/__partial/") != npos)
throw std::invalid_argument("A Realm URL may not contain the reserved string \"/__partial/\".");
}
// Construct an identifier for this partially synced Realm by combining client and user identifiers.
static std::string partial_sync_identifier(const SyncUser& user);
};
} // namespace realm
#endif // REALM_OS_SYNC_CONFIG_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "coversongsimilarity.h"
#include "essentiamath.h"
#include "essentia/utils/tnt/tnt2vector.h"
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace essentia;
Real gammaState(Real value, const Real disOnset, const Real disExtension);
namespace essentia {
namespace standard {
const char* CoverSongSimilarity::name = "CoverSongSimilarity";
const char* CoverSongSimilarity::category = "Music similarity";
const char* CoverSongSimilarity::description = DOC("This algorithm computes a cover song similiarity measure from an input cross similarity matrix of two chroma vectors of a query and reference song using various alignment constraints of smith-waterman local-alignment algorithm.\n\n"
"This algorithm expects to recieve the input matrix from essentia 'CrossSimilarityMatrix' algorithm\n\n"
"The algorithm provides two different allignment contraints for computing the smith-waterman score matrix (check references).\n\n"
"Exceptions are thrown if the input similarity matrix is not binary or empty.\n\n"
"References:\n"
"[1] Smith-Waterman algorithm Wikipedia (https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm).\n\n"
"[2] Serra, J., Serra, X., & Andrzejak, R. G. (2009). Cross recurrence quantification for cover song identification.New Journal of Physics.\n\n"
"[3] Chen, N., Li, W., & Xiao, H. (2017). Fusing similarity functions for cover song identification. Multimedia Tools and Applications.\n");
void CoverSongSimilarity::configure() {
_disOnset = parameter("disOnset").toReal();
_disExtension = parameter("disExtension").toReal();
std::string simType = toLower(parameter("simType").toString());
if (simType == "qmax") _simType = QMAX;
else if (simType == "dmax") _simType = DMAX;
else throw EssentiaException("CoverSongSimilarity: Invalid cover similarity type: ", simType);
}
void CoverSongSimilarity::compute() {
// get input and output
const std::vector<std::vector<Real> > simMatrix = _inputArray.get();
std::vector<std::vector<Real> >& scoreMatrix = _scoreMatrix.get();
if (simMatrix.empty())
throw EssentiaException("CoverSongSimilarity: Input similarity matrix is empty");
size_t Ny = simMatrix.size();
size_t Nx = simMatrix[0].size();
std::vector<std::vector<Real> > cumMatrix(Ny, std::vector<Real>(Nx, 0));
Real c1 = 0;
Real c2 = 0;
Real c3 = 0;
Real c4 = 0;
Real c5 = 0;
if (_simType == QMAX) {
// iterate through the similarity matrix to recursively construct the qmax scoring cumilative matrix
for(size_t i = 2; i < simMatrix.size(); i++) {
for(size_t j = 2; j < simMatrix[i].size(); j++) {
// measure the diagonal when a similarity is found in the input matrix
if (simMatrix[i][j] == 1) {
c1 = cumMatrix[i-1][j-1];
c2 = cumMatrix[i-2][j-1];
c3 = cumMatrix[i-1][j-2];
Real row[3] = {c1, c2 , c3};
cumMatrix[i][j] = *std::max_element(row, row+3) + 1;
}
else {
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
c1 = cumMatrix[i-1][j-1] - gammaState(simMatrix[i-1][j-1], _disOnset, _disExtension);
c2 = cumMatrix[i-2][j-1] - gammaState(simMatrix[i-2][j-1], _disOnset, _disExtension);
c3 = cumMatrix[i-1][j-2] - gammaState(simMatrix[i-1][j-2], _disOnset, _disExtension);
Real row2[4] = {0, c1, c2, c3};
cumMatrix[i][j] = *std::max_element(row2, row2+4);
}
}
}
scoreMatrix = cumMatrix;
}
else if (_simType == DMAX) {
// iterate through the similarity matrix to recursively construct the dmax scoring cumilative matrix
for(size_t i = 2; i < simMatrix.size(); ++i) {
for(size_t j = 2; i < simMatrix[i].size(); ++j) {
// measure the diagonal when a similarity is found in the input matrix
if (simMatrix[i][j] == 1.) {
c2 = cumMatrix[i-2][j-1] + simMatrix[i-1][j];
c3 = cumMatrix[i-1][j-2] + simMatrix[i][j-1];
c4 = cumMatrix[i-3][j-1] + simMatrix[i-2][j] + scoreMatrix[i-1][j];
c5 = cumMatrix[i-1][j-3] + simMatrix[i][j-2] + scoreMatrix[i][j-1];
Real row[5] = {cumMatrix[i-1][j-1], c2, c3, c4, c5};
cumMatrix[i][j] = *std::max_element(row, row+5) + 1;
}
else {
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
c1 = cumMatrix[i-1][j-1] - gammaState(simMatrix[i-1][j-1], _disOnset, _disExtension);
c2 = (cumMatrix[i-2][j-1] + simMatrix[i-1][j]) - gammaState(simMatrix[i-2][j-1], _disOnset, _disExtension);
c3 = (cumMatrix[i-1][j-2] + simMatrix[i][j-1]) - gammaState(simMatrix[i-1][j-2], _disOnset, _disExtension);
c4 = (cumMatrix[i-3][j-1] + simMatrix[i-2][j] + simMatrix[i-1][j]) - gammaState(simMatrix[i-3][j-1], _disOnset, _disExtension);
c5 = (cumMatrix[i-1][j-3] + simMatrix[i][j-2] + simMatrix[i][j-1]) - gammaState(simMatrix[i-1][j-3], _disOnset, _disExtension);
Real row2[6] = {0, c1, c2, c3, c4, c5};
cumMatrix[i][j] = *std::max_element(row2, row2+6);
}
}
}
scoreMatrix = cumMatrix;
}
}
} // namespace standard
} // namespace essentia
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* CoverSongSimilarity::name = standard::CoverSongSimilarity::name;
const char* CoverSongSimilarity::description = standard::CoverSongSimilarity::description;
void CoverSongSimilarity::configure() {
_disOnset = parameter("disOnset").toReal();
_disExtension = parameter("disExtension").toReal();
_c1 = 0;
_c2 = 0;
_c3 = 0;
_c4 = 0;
_c5 = 0;
_minFramesSize = 2*2;
_accumXFrameSize = 2;
_accumYFrameSize = 2;
input("inputArray").setAcquireSize(_minFramesSize);
input("inputArray").setReleaseSize(1);
output("scoreMatrix").setAcquireSize(1);
output("scoreMatrix").setReleaseSize(1);
}
AlgorithmStatus CoverSongSimilarity::process() {
const std::vector<std::vector<Real> >& inputFrames = _inputArray.tokens();
std::vector<TNT::Array2D<Real> >& scoreMatrix = _scoreMatrix.tokens();
//std::vector<std::vector<Real> >& inputFrames = array2DToVecvec(inputArray);
EXEC_DEBUG("process()");
AlgorithmStatus status = acquireData();
EXEC_DEBUG("data acquired (in: " << _inputArray.acquireSize()
<< " - out: " << _scoreMatrix.acquireSize() << ")");
if (status != OK) {
if (!shouldStop()) return status;
// if shouldStop is true, that means there is no more audio coming, so we need
// to take what's left to fill in half-frames, instead of waiting for more
// data to come in (which would have done by returning from this function)
int available = input("queryFeature").available();
if (available == 0) return NO_INPUT;
input("inputArray").setAcquireSize(available);
input("inputArray").setReleaseSize(available);
return process();
}
xFrames = inputFrames.size();
yFrames = inputFrames[0].size();
std::vector<std::vector<Real> > incrementMatrix(xFrames, std::vector<Real>(yFrames, 0));
if (_iterIdx > 0) {
_accumXFrameSize = xFrames * (_iterIdx + 1);
_accumYFrameSize = yFrames;
for (size_t i=0; i<incrementMatrix.size(); i++) {
_prevCumMatrixFrames.push_back(incrementMatrix[i]);
_previnputMatrixFrames.push_back(incrementMatrix[i]);
}
_x = xFrames * _iterIdx;
_y = yFrames;
_xIter = 0;
}
else {
_prevCumMatrixFrames.assign(xFrames, std::vector<Real>(yFrames, 0));
for (size_t i=0; i<incrementMatrix.size(); i++) {
_previnputMatrixFrames.push_back(incrementMatrix[i]);
}
_accumXFrameSize = xFrames;
_accumYFrameSize = yFrames;
_x = 2;
_y = 2;
_xIter = 2;
}
// iterate through the similarity matrix to recursively construct the qmax scoring cumilative matrix
for(size_t i = _x; i < _accumXFrameSize; i++) {
for(size_t j = 2; j < yFrames; j++) {
// measure the diagonal when a similarity is found in the input matrix
std::cout << "Val: " << _previnputMatrixFrames[i][j] << std::endl;
if (inputFrames[_xIter][j] == 1.0) {
_c1 = _prevCumMatrixFrames[i-1][j-1];
_c2 = _prevCumMatrixFrames[i-2][j-1];
_c3 = _prevCumMatrixFrames[i-1][j-2];
Real row[3] = {_c1, _c2 , _c3};
incrementMatrix[_xIter][j] = *std::max_element(row, row+3) + 1;
std::cout << "Hola1: " << incrementMatrix[_xIter][j] << " Idx: " << _xIter << ", " << j << std::endl;
}
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
else {
_c1 = _prevCumMatrixFrames[i-1][j-1] - gammaState(_previnputMatrixFrames[i-1][j-1], _disOnset, _disExtension);
_c2 = _prevCumMatrixFrames[i-2][j-1] - gammaState(_previnputMatrixFrames[i-2][j-1], _disOnset, _disExtension);
_c3 = _prevCumMatrixFrames[i-1][j-2] - gammaState(_previnputMatrixFrames[i-1][j-2], _disOnset, _disExtension);
Real row2[4] = {0, _c1, _c2, _c3};
incrementMatrix[_xIter][j] = *std::max_element(row2, row2+4);
// std::cout << "Hola2: " << incrementMatrix[_xIter][_yIter] << " Idx: " << _xIter << ", " << _yIter << std::endl;
}
}
if (_xIter < xFrames) _xIter++;
}
_iterIdx++;
scoreMatrix[0] = vecvecToArray2D(incrementMatrix);
releaseData();
}
} // namespace streaming
} // namespace essentia
// apply gap penalty for disruption and extension
Real gammaState(Real value, const Real disOnset, const Real disExtension) {
if (value == 1.0) return disOnset;
else if (value == 0.0) return disExtension;
else throw EssentiaException("CoverSongSimilarity:Non-binary elements found in the inputsimilarity matrix. Expected a binary similarity matrix!");
}
<commit_msg>minor edits in coversongsimilarity algo<commit_after>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "coversongsimilarity.h"
#include "essentiamath.h"
#include "essentia/utils/tnt/tnt2vector.h"
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace essentia;
Real gammaState(Real value, const Real disOnset, const Real disExtension);
namespace essentia {
namespace standard {
const char* CoverSongSimilarity::name = "CoverSongSimilarity";
const char* CoverSongSimilarity::category = "Music similarity";
const char* CoverSongSimilarity::description = DOC("This algorithm computes a cover song similiarity measure from an input cross similarity matrix of two chroma vectors of a query and reference song using various alignment constraints of smith-waterman local-alignment algorithm.\n\n"
"This algorithm expects to recieve the input matrix from essentia 'CrossSimilarityMatrix' algorithm\n\n"
"The algorithm provides two different allignment contraints for computing the smith-waterman score matrix (check references).\n\n"
"Exceptions are thrown if the input similarity matrix is not binary or empty.\n\n"
"References:\n"
"[1] Smith-Waterman algorithm Wikipedia (https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm).\n\n"
"[2] Serra, J., Serra, X., & Andrzejak, R. G. (2009). Cross recurrence quantification for cover song identification.New Journal of Physics.\n\n"
"[3] Chen, N., Li, W., & Xiao, H. (2017). Fusing similarity functions for cover song identification. Multimedia Tools and Applications.\n");
void CoverSongSimilarity::configure() {
_disOnset = parameter("disOnset").toReal();
_disExtension = parameter("disExtension").toReal();
std::string simType = toLower(parameter("simType").toString());
if (simType == "qmax") _simType = QMAX;
else if (simType == "dmax") _simType = DMAX;
else throw EssentiaException("CoverSongSimilarity: Invalid cover similarity type: ", simType);
}
void CoverSongSimilarity::compute() {
// get input and output
const std::vector<std::vector<Real> > simMatrix = _inputArray.get();
std::vector<std::vector<Real> >& scoreMatrix = _scoreMatrix.get();
if (simMatrix.empty())
throw EssentiaException("CoverSongSimilarity: Input similarity matrix is empty");
size_t Ny = simMatrix.size();
size_t Nx = simMatrix[0].size();
std::vector<std::vector<Real> > cumMatrix(Ny, std::vector<Real>(Nx, 0));
Real c1 = 0;
Real c2 = 0;
Real c3 = 0;
Real c4 = 0;
Real c5 = 0;
if (_simType == QMAX) {
// iterate through the similarity matrix to recursively construct the qmax scoring cumilative matrix
for(size_t i = 2; i < simMatrix.size(); i++) {
for(size_t j = 2; j < simMatrix[i].size(); j++) {
// measure the diagonal when a similarity is found in the input matrix
if (simMatrix[i][j] == 1) {
c1 = cumMatrix[i-1][j-1];
c2 = cumMatrix[i-2][j-1];
c3 = cumMatrix[i-1][j-2];
Real row[3] = {c1, c2 , c3};
cumMatrix[i][j] = *std::max_element(row, row+3) + 1;
}
else {
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
c1 = cumMatrix[i-1][j-1] - gammaState(simMatrix[i-1][j-1], _disOnset, _disExtension);
c2 = cumMatrix[i-2][j-1] - gammaState(simMatrix[i-2][j-1], _disOnset, _disExtension);
c3 = cumMatrix[i-1][j-2] - gammaState(simMatrix[i-1][j-2], _disOnset, _disExtension);
Real row2[4] = {0, c1, c2, c3};
cumMatrix[i][j] = *std::max_element(row2, row2+4);
}
}
}
scoreMatrix = cumMatrix;
}
else if (_simType == DMAX) {
// iterate through the similarity matrix to recursively construct the dmax scoring cumilative matrix
for(size_t i = 2; i < simMatrix.size(); ++i) {
for(size_t j = 2; i < simMatrix[i].size(); ++j) {
// measure the diagonal when a similarity is found in the input matrix
if (simMatrix[i][j] == 1.) {
c2 = cumMatrix[i-2][j-1] + simMatrix[i-1][j];
c3 = cumMatrix[i-1][j-2] + simMatrix[i][j-1];
c4 = cumMatrix[i-3][j-1] + simMatrix[i-2][j] + scoreMatrix[i-1][j];
c5 = cumMatrix[i-1][j-3] + simMatrix[i][j-2] + scoreMatrix[i][j-1];
Real row[5] = {cumMatrix[i-1][j-1], c2, c3, c4, c5};
cumMatrix[i][j] = *std::max_element(row, row+5) + 1;
}
else {
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
c1 = cumMatrix[i-1][j-1] - gammaState(simMatrix[i-1][j-1], _disOnset, _disExtension);
c2 = (cumMatrix[i-2][j-1] + simMatrix[i-1][j]) - gammaState(simMatrix[i-2][j-1], _disOnset, _disExtension);
c3 = (cumMatrix[i-1][j-2] + simMatrix[i][j-1]) - gammaState(simMatrix[i-1][j-2], _disOnset, _disExtension);
c4 = (cumMatrix[i-3][j-1] + simMatrix[i-2][j] + simMatrix[i-1][j]) - gammaState(simMatrix[i-3][j-1], _disOnset, _disExtension);
c5 = (cumMatrix[i-1][j-3] + simMatrix[i][j-2] + simMatrix[i][j-1]) - gammaState(simMatrix[i-1][j-3], _disOnset, _disExtension);
Real row2[6] = {0, c1, c2, c3, c4, c5};
cumMatrix[i][j] = *std::max_element(row2, row2+6);
}
}
}
scoreMatrix = cumMatrix;
}
}
} // namespace standard
} // namespace essentia
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* CoverSongSimilarity::name = standard::CoverSongSimilarity::name;
const char* CoverSongSimilarity::description = standard::CoverSongSimilarity::description;
void CoverSongSimilarity::configure() {
_disOnset = parameter("disOnset").toReal();
_disExtension = parameter("disExtension").toReal();
_c1 = 0;
_c2 = 0;
_c3 = 0;
_c4 = 0;
_c5 = 0;
_minFramesSize = 2*2;
_accumXFrameSize = 2;
_accumYFrameSize = 2;
input("inputArray").setAcquireSize(_minFramesSize);
input("inputArray").setReleaseSize(1);
output("scoreMatrix").setAcquireSize(1);
output("scoreMatrix").setReleaseSize(1);
}
AlgorithmStatus CoverSongSimilarity::process() {
const std::vector<std::vector<Real> >& inputFrames = _inputArray.tokens();
std::vector<TNT::Array2D<Real> >& scoreMatrix = _scoreMatrix.tokens();
//std::vector<std::vector<Real> >& inputFrames = array2DToVecvec(inputArray);
EXEC_DEBUG("process()");
AlgorithmStatus status = acquireData();
EXEC_DEBUG("data acquired (in: " << _inputArray.acquireSize()
<< " - out: " << _scoreMatrix.acquireSize() << ")");
if (status != OK) {
if (!shouldStop()) return status;
// if shouldStop is true, that means there is no more audio coming, so we need
// to take what's left to fill in half-frames, instead of waiting for more
// data to come in (which would have done by returning from this function)
int available = input("queryFeature").available();
if (available == 0) return NO_INPUT;
input("inputArray").setAcquireSize(available);
input("inputArray").setReleaseSize(available);
return process();
}
xFrames = inputFrames.size();
yFrames = inputFrames[0].size();
std::vector<std::vector<Real> > incrementMatrix(xFrames, std::vector<Real>(yFrames, 0));
if (_iterIdx > 0) {
_accumXFrameSize = xFrames * (_iterIdx + 1);
_accumYFrameSize = yFrames;
for (size_t i=0; i<incrementMatrix.size(); i++) {
_prevCumMatrixFrames.push_back(incrementMatrix[i]);
_previnputMatrixFrames.push_back(incrementMatrix[i]);
}
_x = xFrames * _iterIdx;
_y = yFrames;
_xIter = 0;
}
else {
_prevCumMatrixFrames.assign(xFrames, std::vector<Real>(yFrames, 0));
for (size_t i=0; i<incrementMatrix.size(); i++) {
_previnputMatrixFrames.push_back(incrementMatrix[i]);
}
_accumXFrameSize = xFrames;
_accumYFrameSize = yFrames;
_x = 2;
_y = 2;
_xIter = 2;
}
// iterate through the similarity matrix to recursively construct the qmax scoring cumilative matrix
for(size_t i = _x; i < _accumXFrameSize; i++) {
for(size_t j = 2; j < yFrames; j++) {
// measure the diagonal when a similarity is found in the input matrix
//std::cout << "Val: " << _previnputMatrixFrames[i][j] << std::endl;
if (inputFrames[_xIter][j] == 1.0) {
_c1 = _prevCumMatrixFrames[i-1][j-1];
_c2 = _prevCumMatrixFrames[i-2][j-1];
_c3 = _prevCumMatrixFrames[i-1][j-2];
Real row[3] = {_c1, _c2 , _c3};
incrementMatrix[_xIter][j] = *std::max_element(row, row+3) + 1;
}
// apply gap penalty onset for disruption and extension when similarity is not found in the input matrix
else {
_c1 = _prevCumMatrixFrames[i-1][j-1] - gammaState(_previnputMatrixFrames[i-1][j-1], _disOnset, _disExtension);
_c2 = _prevCumMatrixFrames[i-2][j-1] - gammaState(_previnputMatrixFrames[i-2][j-1], _disOnset, _disExtension);
_c3 = _prevCumMatrixFrames[i-1][j-2] - gammaState(_previnputMatrixFrames[i-1][j-2], _disOnset, _disExtension);
Real row2[4] = {0, _c1, _c2, _c3};
incrementMatrix[_xIter][j] = *std::max_element(row2, row2+4);
}
}
if (_xIter < xFrames) _xIter++;
}
_iterIdx++;
scoreMatrix[0] = vecvecToArray2D(incrementMatrix);
releaseData();
}
} // namespace streaming
} // namespace essentia
// apply gap penalty for disruption and extension
Real gammaState(Real value, const Real disOnset, const Real disExtension) {
if (value == 1.0) return disOnset;
else if (value == 0.0) return disExtension;
else throw EssentiaException("CoverSongSimilarity:Non-binary elements found in the inputsimilarity matrix. Expected a binary similarity matrix!");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#pragma once
namespace EbmlIO
{
class File
{
File(const File&);
File& operator=(const File&);
public:
File();
~File();
void SetStream(IStream*);
IStream* GetStream() const;
HRESULT SetSize(__int64);
__int64 SetPosition(__int64, STREAM_SEEK = STREAM_SEEK_SET);
__int64 GetPosition() const;
void Write(const void*, ULONG);
void Serialize8UInt(__int64);
void Serialize4UInt(ULONG);
void Serialize2UInt(USHORT);
void Serialize1UInt(BYTE);
static BYTE GetSerializeUIntSize(__int64);
void SerializeUInt(__int64, BYTE size);
void Serialize2SInt(SHORT);
void Serialize4Float(float);
void WriteID4(ULONG);
void WriteID3(ULONG);
void WriteID2(USHORT);
void WriteID1(BYTE);
ULONG ReadID4();
void Write8UInt(__int64);
void Write4UInt(ULONG);
void Write2UInt(USHORT);
void Write1UInt(BYTE);
void WriteUInt(__int64, ULONG size = 0);
void Write1String(const char*);
//void Write1String(const char* str, size_t len);
void Write1UTF8(const wchar_t*);
private:
IStream* m_pStream;
};
HRESULT SetSize(IStream*, __int64);
__int64 SetPosition(IStream*, __int64, STREAM_SEEK);
void Serialize(ISequentialStream*, const BYTE*, const BYTE*);
void Serialize(ISequentialStream*, const void*, ULONG);
void Write(ISequentialStream*, const void*, ULONG);
void WriteID4(ISequentialStream*, ULONG);
void WriteID3(ISequentialStream*, ULONG);
void WriteID2(ISequentialStream*, USHORT);
void WriteID1(ISequentialStream*, BYTE);
ULONG ReadID4(ISequentialStream*);
void Write8UInt(ISequentialStream*, __int64);
void Write4UInt(ISequentialStream*, ULONG);
void Write2UInt(ISequentialStream*, USHORT);
void Write1UInt(ISequentialStream*, BYTE);
void WriteUInt(ISequentialStream*, __int64, ULONG size = 0);
void Write1String(ISequentialStream*, const char*);
void Write1String(ISequentialStream*, const char*, size_t);
void Write1UTF8(ISequentialStream*, const wchar_t*);
} //end namespace EbmlIO
<commit_msg>webmmuxebmlio: fix SetPosition declaration<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#pragma once
namespace EbmlIO
{
class File
{
File(const File&);
File& operator=(const File&);
public:
File();
~File();
void SetStream(IStream*);
IStream* GetStream() const;
HRESULT SetSize(__int64);
__int64 SetPosition(__int64, STREAM_SEEK origin = STREAM_SEEK_SET);
__int64 GetPosition() const;
void Write(const void*, ULONG);
void Serialize8UInt(__int64);
void Serialize4UInt(ULONG);
void Serialize2UInt(USHORT);
void Serialize1UInt(BYTE);
static BYTE GetSerializeUIntSize(__int64);
void SerializeUInt(__int64, BYTE size);
void Serialize2SInt(SHORT);
void Serialize4Float(float);
void WriteID4(ULONG);
void WriteID3(ULONG);
void WriteID2(USHORT);
void WriteID1(BYTE);
ULONG ReadID4();
void Write8UInt(__int64);
void Write4UInt(ULONG);
void Write2UInt(USHORT);
void Write1UInt(BYTE);
void WriteUInt(__int64, ULONG size = 0);
void Write1String(const char*);
//void Write1String(const char* str, size_t len);
void Write1UTF8(const wchar_t*);
private:
IStream* m_pStream;
};
HRESULT SetSize(IStream*, __int64);
__int64 SetPosition(IStream*, __int64, STREAM_SEEK);
void Serialize(ISequentialStream*, const BYTE*, const BYTE*);
void Serialize(ISequentialStream*, const void*, ULONG);
void Write(ISequentialStream*, const void*, ULONG);
void WriteID4(ISequentialStream*, ULONG);
void WriteID3(ISequentialStream*, ULONG);
void WriteID2(ISequentialStream*, USHORT);
void WriteID1(ISequentialStream*, BYTE);
ULONG ReadID4(ISequentialStream*);
void Write8UInt(ISequentialStream*, __int64);
void Write4UInt(ISequentialStream*, ULONG);
void Write2UInt(ISequentialStream*, USHORT);
void Write1UInt(ISequentialStream*, BYTE);
void WriteUInt(ISequentialStream*, __int64, ULONG size = 0);
void Write1String(ISequentialStream*, const char*);
void Write1String(ISequentialStream*, const char*, size_t);
void Write1UTF8(ISequentialStream*, const wchar_t*);
} //end namespace EbmlIO
<|endoftext|>
|
<commit_before>#include <map>
#include "dispatch-c++.h"
/*
* For synchronous dispatch.
*/
static void call_func_void_void(void * context)
{
std::function<void (void)> &func = *static_cast<std::function<void (void)> *>(context);
func();
}
/*
* For asynchronous dispatch.
*/
static void call_funcptr_void_void(void * context)
{
std::function<void (void)> * func_ptr = static_cast<std::function<void (void)> *>(context);
(*func_ptr)();
delete func_ptr;
}
/*
* For synchronous dispatch.
*/
static void call_func_void_size_t(void * context, size_t idx)
{
std::function<void (size_t)> &func = *static_cast<std::function<void (size_t)> *>(context);
func(idx);
}
namespace dispatch {
void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_after_f(when, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_apply(size_t iterations, dispatch_queue_t queue, const std::function<void (size_t)> &func)
{
dispatch_apply_f(iterations, queue, static_cast<void *>(const_cast<std::function<void (size_t)> *>(&func)), call_func_void_size_t);
}
void dispatch_async(dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_async_f(queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_sync(dispatch_queue_t queue, const std::function<void (void)> &func)
{
dispatch_sync_f(queue, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_func_void_void);
}
void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_group_async_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_group_notify(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_group_notify_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_once(dispatch_once_t * predicate, const std::function<void (void)> &func)
{
dispatch_once_f(predicate, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_funcptr_void_void);
}
queue::queue() : priQueue(nullptr)
{
}
queue::queue(const std::string &label, const attr attr)
{
static std::map<queue::attr, dispatch_queue_attr_t> mapAttr = {
{attr::SERIAL, DISPATCH_QUEUE_SERIAL},
{attr::CONCURRENT, DISPATCH_QUEUE_CONCURRENT}
};
this->priQueue = dispatch_queue_create(label.c_str(), mapAttr[attr]);
}
queue::queue(const queue &q)
{
this->priQueue = q.priQueue;
dispatch_retain(this->priQueue);
}
queue::queue(queue &&q)
{
this->priQueue = q.priQueue;
q.priQueue = nullptr;
}
queue::~queue()
{
if (this->priQueue != nullptr) {
dispatch_release(this->priQueue);
}
}
std::string queue::label()
{
return dispatch_queue_get_label(this->priQueue);
}
queue queue::globalQueue(const priority priority)
{
static std::map<queue::priority, long> mapPriority = {
{priority::HIGH, DISPATCH_QUEUE_PRIORITY_HIGH},
{priority::DEFAULT, DISPATCH_QUEUE_PRIORITY_DEFAULT},
{priority::LOW, DISPATCH_QUEUE_PRIORITY_LOW},
{priority::BACKGROUND, DISPATCH_QUEUE_PRIORITY_BACKGROUND},
};
queue q;
q.priQueue = dispatch_get_global_queue(mapPriority[priority], 0);
return q;
}
queue queue::mainQueue()
{
queue q;
q.priQueue = dispatch_get_main_queue();
return q;
}
void queue::apply(const size_t iterations, const std::function<void (size_t)> &func)
{
dispatch_apply(iterations, this->priQueue, func);
}
void queue::async(const std::function<void (void)> &func)
{
dispatch_async(this->priQueue, func);
}
void queue::sync(const std::function<void (void)> &func)
{
dispatch_sync(this->priQueue, func);
}
void queue::suspend()
{
dispatch_suspend(this->priQueue);
}
void queue::resume()
{
dispatch_resume(this->priQueue);
}
group::group() : priGroup(dispatch_group_create())
{
}
group::group(const group &grp)
{
this->priGroup = grp.priGroup;
dispatch_retain(this->priGroup);
}
group::group(group &&grp)
{
this->priGroup = grp.priGroup;
grp.priGroup = nullptr;
}
group::~group()
{
if (this->priGroup != nullptr) {
dispatch_release(this->priGroup);
}
}
void group::enter()
{
dispatch_group_enter(this->priGroup);
}
void group::leave()
{
dispatch_group_leave(this->priGroup);
}
long group::wait(dispatch_time_t timeout)
{
return dispatch_group_wait(this->priGroup, timeout);
}
void group::notify(queue &q, const std::function<void (void)> &func)
{
dispatch_group_notify(this->priGroup, q.priQueue, func);
}
void group::async(queue &q, const std::function<void (void)> &func)
{
dispatch_group_async(this->priGroup, q.priQueue, func);
}
semaphore::semaphore() : priSemaphore(dispatch_semaphore_create(0))
{
}
semaphore::semaphore(long count) : priSemaphore(dispatch_semaphore_create(count))
{
}
semaphore::semaphore(const semaphore &sema)
{
this->priSemaphore = sema.priSemaphore;
dispatch_retain(this->priSemaphore);
}
semaphore::semaphore(semaphore &&sema)
{
this->priSemaphore = sema.priSemaphore;
sema.priSemaphore = nullptr;
}
semaphore::~semaphore()
{
if (this->priSemaphore != nullptr) {
dispatch_release(this->priSemaphore);
}
}
long semaphore::signal()
{
return dispatch_semaphore_signal(this->priSemaphore);
}
long semaphore::wait(dispatch_time_t timeout)
{
return dispatch_semaphore_wait(this->priSemaphore, timeout);
}
}
<commit_msg>Using unordered_map instead of map.<commit_after>#include <unordered_map>
#include "dispatch-c++.h"
/*
* For synchronous dispatch.
*/
static void call_func_void_void(void * context)
{
std::function<void (void)> &func = *static_cast<std::function<void (void)> *>(context);
func();
}
/*
* For asynchronous dispatch.
*/
static void call_funcptr_void_void(void * context)
{
std::function<void (void)> * func_ptr = static_cast<std::function<void (void)> *>(context);
(*func_ptr)();
delete func_ptr;
}
/*
* For synchronous dispatch.
*/
static void call_func_void_size_t(void * context, size_t idx)
{
std::function<void (size_t)> &func = *static_cast<std::function<void (size_t)> *>(context);
func(idx);
}
namespace dispatch {
void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_after_f(when, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_apply(size_t iterations, dispatch_queue_t queue, const std::function<void (size_t)> &func)
{
dispatch_apply_f(iterations, queue, static_cast<void *>(const_cast<std::function<void (size_t)> *>(&func)), call_func_void_size_t);
}
void dispatch_async(dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_async_f(queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_sync(dispatch_queue_t queue, const std::function<void (void)> &func)
{
dispatch_sync_f(queue, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_func_void_void);
}
void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_group_async_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_group_notify(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
{
std::function<void (void)> * func_ptr = new std::function<void (void)>(func);
dispatch_group_notify_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
}
void dispatch_once(dispatch_once_t * predicate, const std::function<void (void)> &func)
{
dispatch_once_f(predicate, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_funcptr_void_void);
}
queue::queue() : priQueue(nullptr)
{
}
queue::queue(const std::string &label, const attr attr)
{
static const std::unordered_map<queue::attr, dispatch_queue_attr_t> mapAttr = {
{attr::SERIAL, DISPATCH_QUEUE_SERIAL},
{attr::CONCURRENT, DISPATCH_QUEUE_CONCURRENT}
};
this->priQueue = dispatch_queue_create(label.c_str(), mapAttr.at(attr));
}
queue::queue(const queue &q)
{
this->priQueue = q.priQueue;
dispatch_retain(this->priQueue);
}
queue::queue(queue &&q)
{
this->priQueue = q.priQueue;
q.priQueue = nullptr;
}
queue::~queue()
{
if (this->priQueue != nullptr) {
dispatch_release(this->priQueue);
}
}
std::string queue::label()
{
return dispatch_queue_get_label(this->priQueue);
}
queue queue::globalQueue(const priority priority)
{
static const std::unordered_map<queue::priority, long> mapPriority = {
{priority::HIGH, DISPATCH_QUEUE_PRIORITY_HIGH},
{priority::DEFAULT, DISPATCH_QUEUE_PRIORITY_DEFAULT},
{priority::LOW, DISPATCH_QUEUE_PRIORITY_LOW},
{priority::BACKGROUND, DISPATCH_QUEUE_PRIORITY_BACKGROUND},
};
queue q;
q.priQueue = dispatch_get_global_queue(mapPriority.at(priority), 0);
return q;
}
queue queue::mainQueue()
{
queue q;
q.priQueue = dispatch_get_main_queue();
return q;
}
void queue::apply(const size_t iterations, const std::function<void (size_t)> &func)
{
dispatch_apply(iterations, this->priQueue, func);
}
void queue::async(const std::function<void (void)> &func)
{
dispatch_async(this->priQueue, func);
}
void queue::sync(const std::function<void (void)> &func)
{
dispatch_sync(this->priQueue, func);
}
void queue::suspend()
{
dispatch_suspend(this->priQueue);
}
void queue::resume()
{
dispatch_resume(this->priQueue);
}
group::group() : priGroup(dispatch_group_create())
{
}
group::group(const group &grp)
{
this->priGroup = grp.priGroup;
dispatch_retain(this->priGroup);
}
group::group(group &&grp)
{
this->priGroup = grp.priGroup;
grp.priGroup = nullptr;
}
group::~group()
{
if (this->priGroup != nullptr) {
dispatch_release(this->priGroup);
}
}
void group::enter()
{
dispatch_group_enter(this->priGroup);
}
void group::leave()
{
dispatch_group_leave(this->priGroup);
}
long group::wait(dispatch_time_t timeout)
{
return dispatch_group_wait(this->priGroup, timeout);
}
void group::notify(queue &q, const std::function<void (void)> &func)
{
dispatch_group_notify(this->priGroup, q.priQueue, func);
}
void group::async(queue &q, const std::function<void (void)> &func)
{
dispatch_group_async(this->priGroup, q.priQueue, func);
}
semaphore::semaphore() : priSemaphore(dispatch_semaphore_create(0))
{
}
semaphore::semaphore(long count) : priSemaphore(dispatch_semaphore_create(count))
{
}
semaphore::semaphore(const semaphore &sema)
{
this->priSemaphore = sema.priSemaphore;
dispatch_retain(this->priSemaphore);
}
semaphore::semaphore(semaphore &&sema)
{
this->priSemaphore = sema.priSemaphore;
sema.priSemaphore = nullptr;
}
semaphore::~semaphore()
{
if (this->priSemaphore != nullptr) {
dispatch_release(this->priSemaphore);
}
}
long semaphore::signal()
{
return dispatch_semaphore_signal(this->priSemaphore);
}
long semaphore::wait(dispatch_time_t timeout)
{
return dispatch_semaphore_wait(this->priSemaphore, timeout);
}
}
<|endoftext|>
|
<commit_before><commit_msg>Removed unnecessary scoping.<commit_after><|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* bridge_test_mix.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/tests/bridge/bridge_test_mix.cpp
*
*-------------------------------------------------------------------------
*/
#include "bridge_test.h"
#include "backend/bridge/ddl/bridge.h"
#include "backend/bridge/ddl/ddl.h"
#include "backend/bridge/ddl/ddl_table.h"
#include "backend/bridge/ddl/ddl_index.h"
#include "backend/catalog/manager.h"
#include "backend/storage/database.h"
namespace peloton {
namespace bridge {
/**
* @brief Test many DDL functions together
*/
void BridgeTest::DDL_MIX_TEST() {
DDL_MIX_TEST_1();
DDL_MIX_TEST_2();
DDL_MIX_TEST_3();
}
/**
* @brief Create a table with simple columns that contain
* column-level constraints such as single column
* primary key, unique, and reference table
*/
void BridgeTest::DDL_MIX_TEST_1() {
auto& manager = catalog::Manager::GetInstance();
storage::Database* db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
// Get the simple columns
std::vector<catalog::Column> columns = CreateSimpleColumns();
// Table name and oid
std::string table_name = "test_table_column_constraint";
oid_t table_oid = 50001;
// Create a table
bool status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Get the table pointer and schema
storage::DataTable* table = db->GetTableWithOid(table_oid);
catalog::Schema* schema = table->GetSchema();
// Create the constrains
catalog::Constraint notnull_constraint(CONSTRAINT_TYPE_NOTNULL);
// Add one constraint to the one column
schema->AddConstraint("id", notnull_constraint);
// Create a primary key index and added primary key constraint to the 'name'
// column
oid_t primary_key_index_oid = 50002;
CreateSamplePrimaryKeyIndex(table_name, primary_key_index_oid);
// Create a unique index and added unique constraint to the 'time' column
oid_t unique_index_oid = 50003;
CreateSampleUniqueIndex(table_name, unique_index_oid);
// Create a reference table and foreign key constraint and added unique
// constraint to the 'salary' column
std::string pktable_name = "pktable";
oid_t pktable_oid = 50004;
CreateSampleForeignKey(pktable_oid, pktable_name, columns, table_oid);
// Check the first column's constraint
catalog::Column column = schema->GetColumn(0);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_NOTNULL, "", 1);
// Check the second column's constraint and index
column = schema->GetColumn(1);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_PRIMARY,
table_name + "_pkey", 1);
index::Index* index = table->GetIndexWithOid(primary_key_index_oid);
CheckIndex(index, table_name + "_pkey", 1, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, true);
// Check the third column's constraint and index
column = schema->GetColumn(2);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_UNIQUE, table_name + "_key",
1);
index = table->GetIndexWithOid(unique_index_oid);
CheckIndex(index, table_name + "_key", 1, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_UNIQUE, true);
// Check the fourth column's constraint and foreign key
column = schema->GetColumn(3);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_FOREIGN,
"THIS_IS_FOREIGN_CONSTRAINT", 1, 0);
catalog::ForeignKey* pktable = table->GetForeignKey(0);
CheckForeignKey(pktable, pktable_oid, "THIS_IS_FOREIGN_CONSTRAINT", 1, 1, 'r',
'c');
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
// Drop the table
status = DDLTable::DropTable(pktable_oid);
assert(status);
std::cout << ":::::: " << __func__ << " DONE\n";
}
/**
* @brief Test DDL and DML together. Create a table and drop it. Create a table
* again and insert tuple into the table.
*/
void BridgeTest::DDL_MIX_TEST_2() {
auto& manager = catalog::Manager::GetInstance();
storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
// Get the simple columns
std::vector<catalog::Column> columns = CreateSimpleColumns();
// Table name and oid
std::string table_name = "ddl_dml_mix_test_table";
oid_t table_oid = 60001;
// Create a table
bool status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
// Create a table again
status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Get the table pointer and schema
storage::DataTable* table = db->GetTableWithOid(table_oid);
catalog::Schema *schema = table->GetSchema();
// Ensure that the tile group is as expected.
assert(schema->GetColumnCount() == 4);
// Insert tuples
const bool allocate = true;
for (int col_itr = 0; col_itr < 5; col_itr++) {
storage::Tuple tuple(schema, allocate);
// Setting values
Value integerValue = ValueFactory::GetIntegerValue(243432);
Value stringValue = ValueFactory::GetStringValue("dude");
Value timestampValue = ValueFactory::GetTimestampValue(10.22);
Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);
tuple.SetValue(0, integerValue);
tuple.SetValue(1, stringValue);
tuple.SetValue(2, timestampValue);
tuple.SetValue(3, doubleValue);
table->InsertTuple((txn_id_t)col_itr, &tuple, false);
assert(tuple.GetValue(0) == integerValue);
assert(tuple.GetValue(1) == stringValue);
assert(tuple.GetValue(2) == timestampValue);
assert(tuple.GetValue(3) == doubleValue);
}
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
std::cout << ":::::: " << __func__ << " DONE\n";
}
/**
* @brief UpdateStats Test
*/
void BridgeTest::DDL_MIX_TEST_3() {
bool status;
// Get db
auto& manager = catalog::Manager::GetInstance();
storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
// Get the simple columns
std::vector<catalog::Column> columns = CreateSimpleColumns();
std::string table_name = "DDL_MIX_TEST_3";
// Create a table in Postgres
oid_t table_oid = CreateTableInPostgres(table_name);
assert(table_oid);
// Create a table in Peloton as well
status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// insert tuple
// Get the table pointer and schema
storage::DataTable* table = db->GetTableWithOid(table_oid);
catalog::Schema *schema = table->GetSchema();
// Ensure that the tile group is as expected.
assert(schema->GetColumnCount() == 4);
// Insert tuples
const bool allocate = true;
for (int col_itr = 0; col_itr < 5; col_itr++) {
storage::Tuple tuple(schema, allocate);
// Setting values
Value integerValue = ValueFactory::GetIntegerValue(243432);
Value stringValue = ValueFactory::GetStringValue("dude");
Value timestampValue = ValueFactory::GetTimestampValue(10.22);
Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);
tuple.SetValue(0, integerValue);
tuple.SetValue(1, stringValue);
tuple.SetValue(2, timestampValue);
tuple.SetValue(3, doubleValue);
table->InsertTuple((txn_id_t)col_itr, &tuple, false);
assert(tuple.GetValue(0) == integerValue);
assert(tuple.GetValue(1) == stringValue);
assert(tuple.GetValue(2) == timestampValue);
assert(tuple.GetValue(3) == doubleValue);
}
// get the number of tuples
assert( Bridge::GetNumberOfTuples(table_oid) == 0 );
// analyze
db->UpdateStats();
// get the number of tuples
assert( Bridge::GetNumberOfTuples(table_oid) == 5 );
// create table
// Create a table in Peloton as well
status = DDLTable::CreateTable(table_oid+1, table_name+"second", columns);
assert(status);
// Drop the table in Postgres
status = DropTableInPostgres(table_name);
assert(status);
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
// Drop the table
status = DDLTable::DropTable(table_oid+1);
assert(status);
std::cout << ":::::: " << __func__ << " DONE\n";
}
} // End bridge namespace
} // End peloton namespace
<commit_msg>Disabled BRIDGE_TEST_MIX_3 (UpdateStats test)<commit_after>/*-------------------------------------------------------------------------
*
* bridge_test_mix.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/tests/bridge/bridge_test_mix.cpp
*
*-------------------------------------------------------------------------
*/
#include "bridge_test.h"
#include "backend/bridge/ddl/bridge.h"
#include "backend/bridge/ddl/ddl.h"
#include "backend/bridge/ddl/ddl_table.h"
#include "backend/bridge/ddl/ddl_index.h"
#include "backend/catalog/manager.h"
#include "backend/storage/database.h"
namespace peloton {
namespace bridge {
/**
* @brief Test many DDL functions together
*/
void BridgeTest::DDL_MIX_TEST() {
DDL_MIX_TEST_1();
DDL_MIX_TEST_2();
DDL_MIX_TEST_3();
}
/**
* @brief Create a table with simple columns that contain
* column-level constraints such as single column
* primary key, unique, and reference table
*/
void BridgeTest::DDL_MIX_TEST_1() {
auto& manager = catalog::Manager::GetInstance();
storage::Database* db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
// Get the simple columns
std::vector<catalog::Column> columns = CreateSimpleColumns();
// Table name and oid
std::string table_name = "test_table_column_constraint";
oid_t table_oid = 50001;
// Create a table
bool status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Get the table pointer and schema
storage::DataTable* table = db->GetTableWithOid(table_oid);
catalog::Schema* schema = table->GetSchema();
// Create the constrains
catalog::Constraint notnull_constraint(CONSTRAINT_TYPE_NOTNULL);
// Add one constraint to the one column
schema->AddConstraint("id", notnull_constraint);
// Create a primary key index and added primary key constraint to the 'name'
// column
oid_t primary_key_index_oid = 50002;
CreateSamplePrimaryKeyIndex(table_name, primary_key_index_oid);
// Create a unique index and added unique constraint to the 'time' column
oid_t unique_index_oid = 50003;
CreateSampleUniqueIndex(table_name, unique_index_oid);
// Create a reference table and foreign key constraint and added unique
// constraint to the 'salary' column
std::string pktable_name = "pktable";
oid_t pktable_oid = 50004;
CreateSampleForeignKey(pktable_oid, pktable_name, columns, table_oid);
// Check the first column's constraint
catalog::Column column = schema->GetColumn(0);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_NOTNULL, "", 1);
// Check the second column's constraint and index
column = schema->GetColumn(1);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_PRIMARY,
table_name + "_pkey", 1);
index::Index* index = table->GetIndexWithOid(primary_key_index_oid);
CheckIndex(index, table_name + "_pkey", 1, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, true);
// Check the third column's constraint and index
column = schema->GetColumn(2);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_UNIQUE, table_name + "_key",
1);
index = table->GetIndexWithOid(unique_index_oid);
CheckIndex(index, table_name + "_key", 1, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_UNIQUE, true);
// Check the fourth column's constraint and foreign key
column = schema->GetColumn(3);
CheckColumnWithConstraint(column, CONSTRAINT_TYPE_FOREIGN,
"THIS_IS_FOREIGN_CONSTRAINT", 1, 0);
catalog::ForeignKey* pktable = table->GetForeignKey(0);
CheckForeignKey(pktable, pktable_oid, "THIS_IS_FOREIGN_CONSTRAINT", 1, 1, 'r',
'c');
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
// Drop the table
status = DDLTable::DropTable(pktable_oid);
assert(status);
std::cout << ":::::: " << __func__ << " DONE\n";
}
/**
* @brief Test DDL and DML together. Create a table and drop it. Create a table
* again and insert tuple into the table.
*/
void BridgeTest::DDL_MIX_TEST_2() {
auto& manager = catalog::Manager::GetInstance();
storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
// Get the simple columns
std::vector<catalog::Column> columns = CreateSimpleColumns();
// Table name and oid
std::string table_name = "ddl_dml_mix_test_table";
oid_t table_oid = 60001;
// Create a table
bool status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
// Create a table again
status = DDLTable::CreateTable(table_oid, table_name, columns);
assert(status);
// Get the table pointer and schema
storage::DataTable* table = db->GetTableWithOid(table_oid);
catalog::Schema *schema = table->GetSchema();
// Ensure that the tile group is as expected.
assert(schema->GetColumnCount() == 4);
// Insert tuples
const bool allocate = true;
for (int col_itr = 0; col_itr < 5; col_itr++) {
storage::Tuple tuple(schema, allocate);
// Setting values
Value integerValue = ValueFactory::GetIntegerValue(243432);
Value stringValue = ValueFactory::GetStringValue("dude");
Value timestampValue = ValueFactory::GetTimestampValue(10.22);
Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);
tuple.SetValue(0, integerValue);
tuple.SetValue(1, stringValue);
tuple.SetValue(2, timestampValue);
tuple.SetValue(3, doubleValue);
table->InsertTuple((txn_id_t)col_itr, &tuple, false);
assert(tuple.GetValue(0) == integerValue);
assert(tuple.GetValue(1) == stringValue);
assert(tuple.GetValue(2) == timestampValue);
assert(tuple.GetValue(3) == doubleValue);
}
// Drop the table
status = DDLTable::DropTable(table_oid);
assert(status);
std::cout << ":::::: " << __func__ << " DONE\n";
}
/**
* @brief UpdateStats Test
*/
void BridgeTest::DDL_MIX_TEST_3() {
bool status;
//
// // Get db
// auto& manager = catalog::Manager::GetInstance();
// storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
//
// // Get the simple columns
// std::vector<catalog::Column> columns = CreateSimpleColumns();
// std::string table_name = "DDL_MIX_TEST_3";
//
// // Create a table in Postgres
// oid_t table_oid = CreateTableInPostgres(table_name);
// assert(table_oid);
//
// // Create a table in Peloton as well
// status = DDLTable::CreateTable(table_oid, table_name, columns);
// assert(status);
//
// // insert tuple
// // Get the table pointer and schema
// storage::DataTable* table = db->GetTableWithOid(table_oid);
// catalog::Schema *schema = table->GetSchema();
//
// // Ensure that the tile group is as expected.
// assert(schema->GetColumnCount() == 4);
//
// // Insert tuples
// const bool allocate = true;
//
// for (int col_itr = 0; col_itr < 5; col_itr++) {
//
// storage::Tuple tuple(schema, allocate);
//
// // Setting values
// Value integerValue = ValueFactory::GetIntegerValue(243432);
// Value stringValue = ValueFactory::GetStringValue("dude");
// Value timestampValue = ValueFactory::GetTimestampValue(10.22);
// Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);
//
// tuple.SetValue(0, integerValue);
// tuple.SetValue(1, stringValue);
// tuple.SetValue(2, timestampValue);
// tuple.SetValue(3, doubleValue);
//
// table->InsertTuple((txn_id_t)col_itr, &tuple, false);
//
// assert(tuple.GetValue(0) == integerValue);
// assert(tuple.GetValue(1) == stringValue);
// assert(tuple.GetValue(2) == timestampValue);
// assert(tuple.GetValue(3) == doubleValue);
// }
//
// // get the number of tuples
// assert( Bridge::GetNumberOfTuples(table_oid) == 0 );
//
// // analyze
// db->UpdateStats();
//
// // get the number of tuples
// assert( Bridge::GetNumberOfTuples(table_oid) == 5 );
//
// // create table
// // Create a table in Peloton as well
// status = DDLTable::CreateTable(table_oid+1, table_name+"second", columns);
// assert(status);
//
// // Drop the table in Postgres
// status = DropTableInPostgres(table_name);
// assert(status);
//
// // Drop the table
// status = DDLTable::DropTable(table_oid);
// assert(status);
//
// // Drop the table
// status = DDLTable::DropTable(table_oid+1);
// assert(status);
//
// std::cout << ":::::: " << __func__ << " DONE\n";
}
} // End bridge namespace
} // End peloton namespace
<|endoftext|>
|
<commit_before>#include <type/type-checker.hh>
#include <ast/all.hh>
namespace type
{
TypeChecker::TypeChecker()
: current_class_(nullptr)
{}
TypeChecker::~TypeChecker()
{}
misc::Error& TypeChecker::error_get()
{
return error_;
}
void TypeChecker::type_check(ast::Expr* e1, ast::Expr* e2)
{
// FIXME : quick fix that breaks multiple type error report
if (error_.error_type_get() == misc::Error::NONE)
{
if (!e1->type_get() || !e2->type_get())
assert(false && "Compiler internal error");
if (!e1->type_get()->compatible_with(*(e2->type_get())))
{
error_ << misc::Error::TYPE
<< e1->location_get() << ": Type error, excpected "
<< *(e1->type_get()) << ", got " << *(e2->type_get())
<< std::endl;
}
}
}
void TypeChecker::type_set(ast::Expr* e1, ast::Expr* e2)
{
e1->type_set(e2->type_get());
}
Type* TypeChecker::type_call(ast::FunctionDec* d, Function* type)
{
// Look if prototype has already been checked
for (auto proto : d->to_generate_get())
{
if (proto->compatible_with(*type))
return proto->return_type_get();
}
// Else check this prototype
Function* temp = d->type_get();
// Set the prototype to function prototype
d->type_set(type);
// Add the prototype to be generated later (and for same check later)
d->to_generate_add(type);
// Check the body
in_declaration_.push(d);
d->body_get()->accept(*this);
in_declaration_.pop();
if (!d->type_get()->return_type_get())
d->type_get()->return_type_set(&Void::instance());
// Restore function original prototype
d->type_set(temp);
return type->return_type_get();
}
void TypeChecker::operator()(ast::ReturnStmt& ast)
{
type::Type* ret_type = &Void::instance();
ast::FunctionDec* to_type = in_declaration_.top();
type::Type* fun_type = to_type->type_get()->return_type_get();
if (ast.ret_value_get())
{
ast.ret_value_get()->accept(*this);
ret_type = ast.ret_value_get()->type_get();
}
if (fun_type)
{
if (fun_type == &Polymorphic::instance())
to_type->type_get()->return_type_set(ret_type);
else if (!fun_type->compatible_with(*ret_type))
error_ << misc::Error::TYPE
<< ast.location_get() << ": Type error, function has "
<< "deduced type " << *fun_type << ", but return is "
<< *ret_type << std::endl;
}
else
to_type->type_get()->return_type_set(ret_type);
}
void TypeChecker::operator()(ast::FunctionDec& s)
{
Function* f_type = new Function();
s.type_set(f_type);
if (s.args_get())
{
for (auto arg : s.args_get()->list_get())
{
ast::IdVar* var = dynamic_cast<ast::IdVar*> (arg);
if (var)
{
// If it is a var type it as polymorphic type
// for the correctness check (better check will be
// performed when type checking function call)
// -> see operator()(ast::FunctionVar&)
var->type_set(&Polymorphic::instance());
f_type->args_type_add(&Polymorphic::instance());
}
else
{
// If it is an assignement type it as it must be
arg->accept(*this);
f_type->args_type_add(arg->type_get());
}
}
}
in_declaration_.push(&s);
s.body_get()->accept(*this);
in_declaration_.pop();
if (!f_type->return_type_get())
f_type->return_type_set(&Void::instance());
}
void TypeChecker::operator()(ast::ClassDec& ast)
{
if (declared_class_[ast.name_get()])
error_ << misc::Error::TYPE
<< ast.location_get() << " : Redeclaration of class"
<< ast.name_get() << std::endl;
else
declared_class_[ast.name_get()] = &ast.type_get();
current_class_ = &ast.type_get();
ast.def_get()->accept(*this);
current_class_ = nullptr;
}
void TypeChecker::operator()(ast::FunctionVar& e)
{
// FIXME : Dirty fix supposed to be set when an ambiguous call is made
// This ambiguous call must only be made when checking function
// declaration. Else it is a bug or something I did not think of.
ast::ExprList* tmp = generate_prototype(e);
if (e.params_get() != tmp)
{
delete e.params_get();
e.params_set(tmp);
}
// If def get is null it is a builtin function (or a bug)
if (!e.def_get())
{
builtin::BuiltinLibrary::instance().type_check(e, error_, *this);
return;
}
bool ambigous = false;
Function* prototype = new Function();
if (e.params_get())
{
for (auto p : e.params_get()->list_get())
{
p->accept(*this);
if (p->type_get() == &Polymorphic::instance())
ambigous = true;
prototype->args_type_add(p->type_get());
}
}
if (!ambigous)
{
e.type_set(type_call(e.def_get(), prototype));
// If the result of the process is Polymorphic type then the code
// is invalid or contains a part of unsupported stuff.
// If you fine any example that is valid and fully supported
// I would be glad to see it and review my algorithm
if (e.type_get() == &Polymorphic::instance())
error_ << misc::Error::TYPE
<< e.location_get() << ": Function return type "
<< "ambiguous or contains unsupported stuff."
<< " If you believe your code works and is supported "
<< "please report it as BUG. Thanks !"
<< std::endl;
else if (!e.type_get())
e.type_set(&Polymorphic::instance());
}
else
e.type_set(&Polymorphic::instance());
}
void TypeChecker::operator()(ast::OpExpr& ast)
{
ast.left_expr_get()->accept(*this);
ast.right_expr_get()->accept(*this);
type_check(ast.left_expr_get(), ast.right_expr_get());
// So far if there is no error it does not really matter if the opexpr
// has right expr of left expr type since they are the same due to
// strong type of python just check if one of them is non polymorphic
if (ast.left_expr_get()->type_get() == &Polymorphic::instance())
type_set(&ast, ast.right_expr_get());
else
type_set(&ast, ast.left_expr_get());
}
void TypeChecker::operator()(ast::IdVar& ast)
{
if (ast.id_get() == "self")
{
if (current_class_)
ast.type_set(current_class_);
else
error_ << misc::Error::TYPE
<< ast.location_get() << " : self used outside class "
<< "definition" << std::endl;
return;
}
ast::Expr* e = dynamic_cast<ast::Expr*> (ast.def_get());
if (e)
type_set(&ast, e);
else if (ast.def_get())
assert(false && "Compiler internal error");
}
void TypeChecker::operator()(ast::FieldVar& ast)
{
ast.var_get()->accept(*this);
type::Class* field_super = nullptr;
field_super = dynamic_cast<type::Class*> (ast.var_get()->type_get());
// If the type of the field before is not a class or is not set
if (!field_super)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : not a class" << std::endl;
return;
}
// If name already exists in the class definition
if (field_super->component_get(ast.name_get()))
{
ast::Ast* dec = field_super->component_get(ast.name_get());
ast::FieldVar* var = dynamic_cast<ast::FieldVar*> (dec);
// If the name is not a field in the definition -> error
if (!var)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : " << ast.name_get()
<< " member of " << field_super << " not declared as"
<< " field" << std::endl;
return;
}
// If the definition as no type
if (!var->type_get())
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : can't deduce type of "
<< *ast.var_get() << std::endl;
return;
}
// Else OK
type_set(&ast, var);
}
else // If the name does not exists the define it in the class
field_super->component_add(ast.name_get(), &ast);
}
void TypeChecker::operator()(ast::AssignExpr& e)
{
e.rvalue_get()->accept(*this);
e.lvalue_get()->accept(*this);
type_set(e.lvalue_get(), e.rvalue_get());
type_set(&e, e.rvalue_get());
// FIXME avoid dirty (and unsafe) thing
if (e.def_get())
type_check(dynamic_cast<ast::Expr*> (e.def_get()), &e);
}
void TypeChecker::operator()(ast::NumeralExpr& ast)
{
ast.type_set(&Int::instance());
}
void TypeChecker::operator()(ast::StringExpr& ast)
{
ast.type_set(&String::instance());
}
const std::string& TypeChecker::name_get(const ast::Expr* e)
{
const ast::IdVar* v = dynamic_cast<const ast::IdVar*> (e);
assert(v && "Internal compiler error");
return v->id_get();
}
void TypeChecker::build_mapping(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
// Build the mapping
for (auto param : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (param);
if (e)
{
std::string s = name_get(e->lvalue_get());
args_map[s] = parameter(e->rvalue_get(), false);
order.push_back(s);
}
else
{
std::string s = name_get(param);
args_map[s] = parameter(nullptr,
false);
order.push_back(s);
}
}
}
void TypeChecker::build_call(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
auto order_it = order.begin();
bool positional = true;
for (auto call_arg : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (call_arg);
if (e)
{
std::string s = name_get(e->lvalue_get());
positional = false;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(e->rvalue_get(), true);
}
else if (!positional)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Non positional argument"
<< " detected after positional argument"
<< std::endl;
else
{
std::string s = *order_it;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(call_arg, true);
++order_it;
}
}
}
ast::ExprList* TypeChecker::generate_list(const yy::location& loc,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
ast::ExprList* params = new ast::ExprList(loc);
for (auto arg : order)
{
if (!args_map[arg].first)
error_ << misc::Error::TYPE
<< loc << ": Argument " << arg
<< " not specified" << std::endl;
else
params->push_back(clone(args_map[arg].first));
}
return params;
}
ast::Expr* TypeChecker::clone(ast::Ast* ast)
{
cloner::AstCloner clone;
clone.visit(ast);
return dynamic_cast<ast::Expr*> (clone.cloned_ast_get());
}
} // namespace type
<commit_msg>[TYPE] Correct bug with undeclared field(s)<commit_after>#include <type/type-checker.hh>
#include <ast/all.hh>
namespace type
{
TypeChecker::TypeChecker()
: current_class_(nullptr)
{}
TypeChecker::~TypeChecker()
{}
misc::Error& TypeChecker::error_get()
{
return error_;
}
void TypeChecker::type_check(ast::Expr* e1, ast::Expr* e2)
{
// FIXME : quick fix that breaks multiple type error report
if (error_.error_type_get() == misc::Error::NONE)
{
if (!e1->type_get() || !e2->type_get())
assert(false && "Compiler internal error");
if (!e1->type_get()->compatible_with(*(e2->type_get())))
{
error_ << misc::Error::TYPE
<< e1->location_get() << ": Type error, excpected "
<< *(e1->type_get()) << ", got " << *(e2->type_get())
<< std::endl;
}
}
}
void TypeChecker::type_set(ast::Expr* e1, ast::Expr* e2)
{
e1->type_set(e2->type_get());
}
Type* TypeChecker::type_call(ast::FunctionDec* d, Function* type)
{
// Look if prototype has already been checked
for (auto proto : d->to_generate_get())
{
if (proto->compatible_with(*type))
return proto->return_type_get();
}
// Else check this prototype
Function* temp = d->type_get();
// Set the prototype to function prototype
d->type_set(type);
// Add the prototype to be generated later (and for same check later)
d->to_generate_add(type);
// Check the body
in_declaration_.push(d);
d->body_get()->accept(*this);
in_declaration_.pop();
if (!d->type_get()->return_type_get())
d->type_get()->return_type_set(&Void::instance());
// Restore function original prototype
d->type_set(temp);
return type->return_type_get();
}
void TypeChecker::operator()(ast::ReturnStmt& ast)
{
type::Type* ret_type = &Void::instance();
ast::FunctionDec* to_type = in_declaration_.top();
type::Type* fun_type = to_type->type_get()->return_type_get();
if (ast.ret_value_get())
{
ast.ret_value_get()->accept(*this);
ret_type = ast.ret_value_get()->type_get();
}
if (fun_type)
{
if (fun_type == &Polymorphic::instance())
to_type->type_get()->return_type_set(ret_type);
else if (!fun_type->compatible_with(*ret_type))
error_ << misc::Error::TYPE
<< ast.location_get() << ": Type error, function has "
<< "deduced type " << *fun_type << ", but return is "
<< *ret_type << std::endl;
}
else
to_type->type_get()->return_type_set(ret_type);
}
void TypeChecker::operator()(ast::FunctionDec& s)
{
Function* f_type = new Function();
s.type_set(f_type);
if (s.args_get())
{
for (auto arg : s.args_get()->list_get())
{
ast::IdVar* var = dynamic_cast<ast::IdVar*> (arg);
if (var)
{
// If it is a var type it as polymorphic type
// for the correctness check (better check will be
// performed when type checking function call)
// -> see operator()(ast::FunctionVar&)
var->type_set(&Polymorphic::instance());
f_type->args_type_add(&Polymorphic::instance());
}
else
{
// If it is an assignement type it as it must be
arg->accept(*this);
f_type->args_type_add(arg->type_get());
}
}
}
in_declaration_.push(&s);
s.body_get()->accept(*this);
in_declaration_.pop();
if (!f_type->return_type_get())
f_type->return_type_set(&Void::instance());
}
void TypeChecker::operator()(ast::ClassDec& ast)
{
if (declared_class_[ast.name_get()])
error_ << misc::Error::TYPE
<< ast.location_get() << " : Redeclaration of class"
<< ast.name_get() << std::endl;
else
declared_class_[ast.name_get()] = &ast.type_get();
current_class_ = &ast.type_get();
ast.def_get()->accept(*this);
current_class_ = nullptr;
}
void TypeChecker::operator()(ast::FunctionVar& e)
{
// FIXME : Dirty fix supposed to be set when an ambiguous call is made
// This ambiguous call must only be made when checking function
// declaration. Else it is a bug or something I did not think of.
ast::ExprList* tmp = generate_prototype(e);
if (e.params_get() != tmp)
{
delete e.params_get();
e.params_set(tmp);
}
// If def get is null it is a builtin function (or a bug)
if (!e.def_get())
{
builtin::BuiltinLibrary::instance().type_check(e, error_, *this);
return;
}
bool ambigous = false;
Function* prototype = new Function();
if (e.params_get())
{
for (auto p : e.params_get()->list_get())
{
p->accept(*this);
if (p->type_get() == &Polymorphic::instance())
ambigous = true;
prototype->args_type_add(p->type_get());
}
}
if (!ambigous)
{
e.type_set(type_call(e.def_get(), prototype));
// If the result of the process is Polymorphic type then the code
// is invalid or contains a part of unsupported stuff.
// If you fine any example that is valid and fully supported
// I would be glad to see it and review my algorithm
if (e.type_get() == &Polymorphic::instance())
error_ << misc::Error::TYPE
<< e.location_get() << ": Function return type "
<< "ambiguous or contains unsupported stuff."
<< " If you believe your code works and is supported "
<< "please report it as BUG. Thanks !"
<< std::endl;
else if (!e.type_get())
e.type_set(&Polymorphic::instance());
}
else
e.type_set(&Polymorphic::instance());
}
void TypeChecker::operator()(ast::OpExpr& ast)
{
ast.left_expr_get()->accept(*this);
ast.right_expr_get()->accept(*this);
type_check(ast.left_expr_get(), ast.right_expr_get());
// So far if there is no error it does not really matter if the opexpr
// has right expr of left expr type since they are the same due to
// strong type of python just check if one of them is non polymorphic
if (ast.left_expr_get()->type_get() == &Polymorphic::instance())
type_set(&ast, ast.right_expr_get());
else
type_set(&ast, ast.left_expr_get());
}
void TypeChecker::operator()(ast::IdVar& ast)
{
if (ast.id_get() == "self")
{
if (current_class_)
ast.type_set(current_class_);
else
error_ << misc::Error::TYPE
<< ast.location_get() << " : self used outside class "
<< "definition" << std::endl;
return;
}
ast::Expr* e = dynamic_cast<ast::Expr*> (ast.def_get());
if (e)
type_set(&ast, e);
else if (ast.def_get())
assert(false && "Compiler internal error");
}
void TypeChecker::operator()(ast::FieldVar& ast)
{
ast.var_get()->accept(*this);
type::Class* field_super = nullptr;
field_super = dynamic_cast<type::Class*> (ast.var_get()->type_get());
// If the type of the field before is not a class or is not set
if (!field_super)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : not a class" << std::endl;
return;
}
// If name already exists in the class definition
if (field_super->component_get(ast.name_get()))
{
ast::Ast* dec = field_super->component_get(ast.name_get());
ast::FieldVar* var = dynamic_cast<ast::FieldVar*> (dec);
// If the name is not a field in the definition -> error
if (!var)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : " << ast.name_get()
<< " member of " << field_super << " not declared as"
<< " field" << std::endl;
return;
}
// If the definition as no type
if (!var->type_get())
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : can't deduce type of "
<< *ast.var_get() << std::endl;
return;
}
// Else OK
type_set(&ast, var);
}
else // If the name does not exists the define it in the class
field_super->component_add(ast.name_get(), &ast);
}
void TypeChecker::operator()(ast::AssignExpr& e)
{
e.rvalue_get()->accept(*this);
e.lvalue_get()->accept(*this);
if (!e.rvalue_get()->type_get()
&& dynamic_cast<ast::FieldVar*> (e.rvalue_get()))
error_ << misc::Error::TYPE
<< e.rvalue_get()->location_get() << " : unknown field"
<< std::endl;
type_set(e.lvalue_get(), e.rvalue_get());
type_set(&e, e.rvalue_get());
// FIXME avoid dirty (and unsafe) thing
if (e.def_get())
type_check(dynamic_cast<ast::Expr*> (e.def_get()), &e);
}
void TypeChecker::operator()(ast::NumeralExpr& ast)
{
ast.type_set(&Int::instance());
}
void TypeChecker::operator()(ast::StringExpr& ast)
{
ast.type_set(&String::instance());
}
const std::string& TypeChecker::name_get(const ast::Expr* e)
{
const ast::IdVar* v = dynamic_cast<const ast::IdVar*> (e);
assert(v && "Internal compiler error");
return v->id_get();
}
void TypeChecker::build_mapping(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
// Build the mapping
for (auto param : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (param);
if (e)
{
std::string s = name_get(e->lvalue_get());
args_map[s] = parameter(e->rvalue_get(), false);
order.push_back(s);
}
else
{
std::string s = name_get(param);
args_map[s] = parameter(nullptr,
false);
order.push_back(s);
}
}
}
void TypeChecker::build_call(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
auto order_it = order.begin();
bool positional = true;
for (auto call_arg : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (call_arg);
if (e)
{
std::string s = name_get(e->lvalue_get());
positional = false;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(e->rvalue_get(), true);
}
else if (!positional)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Non positional argument"
<< " detected after positional argument"
<< std::endl;
else
{
std::string s = *order_it;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(call_arg, true);
++order_it;
}
}
}
ast::ExprList* TypeChecker::generate_list(const yy::location& loc,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
ast::ExprList* params = new ast::ExprList(loc);
for (auto arg : order)
{
if (!args_map[arg].first)
error_ << misc::Error::TYPE
<< loc << ": Argument " << arg
<< " not specified" << std::endl;
else
params->push_back(clone(args_map[arg].first));
}
return params;
}
ast::Expr* TypeChecker::clone(ast::Ast* ast)
{
cloner::AstCloner clone;
clone.visit(ast);
return dynamic_cast<ast::Expr*> (clone.cloned_ast_get());
}
} // namespace type
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: addinlis.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:11:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <tools/debug.hxx>
#include <sfx2/objsh.hxx>
#include "addinlis.hxx"
#include "miscuno.hxx" // SC_IMPL_SERVICE_INFO
#include "document.hxx"
#include "brdcst.hxx"
#include "unoguard.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------------
//SMART_UNO_IMPLEMENTATION( ScAddInListener, UsrObject );
SC_SIMPLE_SERVICE_INFO( ScAddInListener, "ScAddInListener", "stardiv.one.sheet.AddInListener" )
//------------------------------------------------------------------------
List ScAddInListener::aAllListeners;
//------------------------------------------------------------------------
// static
ScAddInListener* ScAddInListener::CreateListener(
uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc )
{
ScAddInListener* pNew = new ScAddInListener( xVR, pDoc );
pNew->acquire(); // for aAllListeners
aAllListeners.Insert( pNew, LIST_APPEND );
if ( xVR.is() )
xVR->addResultListener( pNew ); // after at least 1 ref exists!
return pNew;
}
ScAddInListener::ScAddInListener( uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc ) :
xVolRes( xVR )
{
pDocs = new ScAddInDocs( 1, 1 );
pDocs->Insert( pDoc );
}
ScAddInListener::~ScAddInListener()
{
delete pDocs;
}
// static
ScAddInListener* ScAddInListener::Get( uno::Reference<sheet::XVolatileResult> xVR )
{
sheet::XVolatileResult* pComp = xVR.get();
ULONG nCount = aAllListeners.Count();
for (ULONG nPos=0; nPos<nCount; nPos++)
{
ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
if ( pComp == (sheet::XVolatileResult*)pLst->xVolRes.get() )
return pLst;
}
return NULL; // not found
}
//! move to some container object?
// static
void ScAddInListener::RemoveDocument( ScDocument* pDocumentP )
{
ULONG nPos = aAllListeners.Count();
while (nPos)
{
// loop backwards because elements are removed
--nPos;
ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
ScAddInDocs* p = pLst->pDocs;
USHORT nFoundPos;
if ( p->Seek_Entry( pDocumentP, &nFoundPos ) )
{
p->Remove( nFoundPos );
if ( p->Count() == 0 )
{
// this AddIn is no longer used
// dont delete, just remove the ref for the list
aAllListeners.Remove( nPos );
if ( pLst->xVolRes.is() )
pLst->xVolRes->removeResultListener( pLst );
pLst->release(); // Ref for aAllListeners - pLst may be deleted here
}
}
}
}
//------------------------------------------------------------------------
// XResultListener
void SAL_CALL ScAddInListener::modified( const ::com::sun::star::sheet::ResultEvent& aEvent )
throw(::com::sun::star::uno::RuntimeException)
{
ScUnoGuard aGuard; //! or generate a UserEvent
aResult = aEvent.Value; // store result
if ( !HasListeners() )
{
//! remove from list and removeListener, as in RemoveDocument ???
#if 0
//! this will crash if called before first StartListening !!!
aAllListeners.Remove( this );
if ( xVolRes.is() )
xVolRes->removeResultListener( this );
release(); // Ref for aAllListeners - this may be deleted here
return;
#endif
}
// notify document of changes
Broadcast( ScHint( SC_HINT_DATACHANGED, ScAddress(), NULL ) );
const ScDocument** ppDoc = (const ScDocument**) pDocs->GetData();
USHORT nCount = pDocs->Count();
for ( USHORT j=0; j<nCount; j++, ppDoc++ )
{
ScDocument* pDoc = (ScDocument*)*ppDoc;
pDoc->TrackFormulas();
pDoc->GetDocumentShell()->Broadcast( SfxSimpleHint( FID_DATACHANGED ) );
pDoc->ResetChanged( ScRange(0,0,0,MAXCOL,MAXROW,MAXTAB) );
}
}
// XEventListener
void SAL_CALL ScAddInListener::disposing( const ::com::sun::star::lang::EventObject& /* Source */ )
throw(::com::sun::star::uno::RuntimeException)
{
// hold a ref so this is not deleted at removeResultListener
uno::Reference<sheet::XResultListener> xRef( this );
if ( xVolRes.is() )
{
xVolRes->removeResultListener( this );
xVolRes = NULL;
}
}
//------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.5.330); FILE MERGED 2008/03/31 17:14:14 rt 1.5.330.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: addinlis.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <tools/debug.hxx>
#include <sfx2/objsh.hxx>
#include "addinlis.hxx"
#include "miscuno.hxx" // SC_IMPL_SERVICE_INFO
#include "document.hxx"
#include "brdcst.hxx"
#include "unoguard.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------------
//SMART_UNO_IMPLEMENTATION( ScAddInListener, UsrObject );
SC_SIMPLE_SERVICE_INFO( ScAddInListener, "ScAddInListener", "stardiv.one.sheet.AddInListener" )
//------------------------------------------------------------------------
List ScAddInListener::aAllListeners;
//------------------------------------------------------------------------
// static
ScAddInListener* ScAddInListener::CreateListener(
uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc )
{
ScAddInListener* pNew = new ScAddInListener( xVR, pDoc );
pNew->acquire(); // for aAllListeners
aAllListeners.Insert( pNew, LIST_APPEND );
if ( xVR.is() )
xVR->addResultListener( pNew ); // after at least 1 ref exists!
return pNew;
}
ScAddInListener::ScAddInListener( uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc ) :
xVolRes( xVR )
{
pDocs = new ScAddInDocs( 1, 1 );
pDocs->Insert( pDoc );
}
ScAddInListener::~ScAddInListener()
{
delete pDocs;
}
// static
ScAddInListener* ScAddInListener::Get( uno::Reference<sheet::XVolatileResult> xVR )
{
sheet::XVolatileResult* pComp = xVR.get();
ULONG nCount = aAllListeners.Count();
for (ULONG nPos=0; nPos<nCount; nPos++)
{
ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
if ( pComp == (sheet::XVolatileResult*)pLst->xVolRes.get() )
return pLst;
}
return NULL; // not found
}
//! move to some container object?
// static
void ScAddInListener::RemoveDocument( ScDocument* pDocumentP )
{
ULONG nPos = aAllListeners.Count();
while (nPos)
{
// loop backwards because elements are removed
--nPos;
ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
ScAddInDocs* p = pLst->pDocs;
USHORT nFoundPos;
if ( p->Seek_Entry( pDocumentP, &nFoundPos ) )
{
p->Remove( nFoundPos );
if ( p->Count() == 0 )
{
// this AddIn is no longer used
// dont delete, just remove the ref for the list
aAllListeners.Remove( nPos );
if ( pLst->xVolRes.is() )
pLst->xVolRes->removeResultListener( pLst );
pLst->release(); // Ref for aAllListeners - pLst may be deleted here
}
}
}
}
//------------------------------------------------------------------------
// XResultListener
void SAL_CALL ScAddInListener::modified( const ::com::sun::star::sheet::ResultEvent& aEvent )
throw(::com::sun::star::uno::RuntimeException)
{
ScUnoGuard aGuard; //! or generate a UserEvent
aResult = aEvent.Value; // store result
if ( !HasListeners() )
{
//! remove from list and removeListener, as in RemoveDocument ???
#if 0
//! this will crash if called before first StartListening !!!
aAllListeners.Remove( this );
if ( xVolRes.is() )
xVolRes->removeResultListener( this );
release(); // Ref for aAllListeners - this may be deleted here
return;
#endif
}
// notify document of changes
Broadcast( ScHint( SC_HINT_DATACHANGED, ScAddress(), NULL ) );
const ScDocument** ppDoc = (const ScDocument**) pDocs->GetData();
USHORT nCount = pDocs->Count();
for ( USHORT j=0; j<nCount; j++, ppDoc++ )
{
ScDocument* pDoc = (ScDocument*)*ppDoc;
pDoc->TrackFormulas();
pDoc->GetDocumentShell()->Broadcast( SfxSimpleHint( FID_DATACHANGED ) );
pDoc->ResetChanged( ScRange(0,0,0,MAXCOL,MAXROW,MAXTAB) );
}
}
// XEventListener
void SAL_CALL ScAddInListener::disposing( const ::com::sun::star::lang::EventObject& /* Source */ )
throw(::com::sun::star::uno::RuntimeException)
{
// hold a ref so this is not deleted at removeResultListener
uno::Reference<sheet::XResultListener> xRef( this );
if ( xVolRes.is() )
{
xVolRes->removeResultListener( this );
xVolRes = NULL;
}
}
//------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief Tests for the getenv library
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include <gtest/gtest.h>
#include <kdbgetenv.h>
TEST (GetEnv, NonExist)
{
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
}
TEST (GetEnv, ExistOverride)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistOverrideFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnv)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist", "hello", 1);
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnvFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist-fb", "hello", 1);
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/fallback/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallbackFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/env/fallback/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, OpenClose)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
elektraClose ();
}
TEST (GetEnv, OpenCloseFallback)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user:/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
elektraClose ();
}
void elektraPrintConfig ()
{
using namespace ckdb;
for (elektraCursor it = 0; it < ksGetSize (elektraConfig); ++it)
{
const Key * c = ksAtCursor (elektraConfig, it);
printf ("%s - %s\n", keyName (c), keyString (c));
}
}
// FIXME [new_backend]: tests disabled
TEST (GetEnv, DISABLED_ArgvParam)
{
const char * cargv[] = { "name", "--elektra:does-exist=hello", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, DISABLED_ArgvParamUninvolved)
{
const char * cargv[] = { "name", "--uninvolved", "--not-used", "-L", "--elektra:does-exist=hello",
"--uninvolved", "--not-used", "-L", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 8;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 7) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], std::string ("--uninvolved"));
EXPECT_EQ (argv[2], std::string ("--not-used"));
EXPECT_EQ (argv[3], std::string ("-L"));
EXPECT_EQ (argv[4], std::string ("--uninvolved"));
EXPECT_EQ (argv[5], std::string ("--not-used"));
EXPECT_EQ (argv[6], std::string ("-L"));
EXPECT_EQ (argv[7], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, DISABLED_ArgvParamVersion)
{
const char * cargv[] = { "curl", "--elektra-version", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("curl"));
EXPECT_EQ (argv[1], std::string ("--elektra-version"));
EXPECT_EQ (argv[2], static_cast<char *> (nullptr));
ckdb::Key * kdb_version = ksLookupByName (elektraConfig, "system:/elektra/version/constants/KDB_VERSION", 0);
EXPECT_EQ (getenv ("version"), "Elektra getenv is active\n" + std::string ("KDB_VERSION: ") +
std::string (keyString (kdb_version)) + std::string ("\nKDB_GETENV_VERSION: ") +
KDB_GETENV_VERSION);
elektraClose ();
}
TEST (GetEnv, DISABLED_NameArgv0)
{
using namespace ckdb;
int argc = 1;
const char * cargv[] = { "path/to/any-name", nullptr };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("path/to/any-name"));
k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/basename", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("any-name"));
elektraClose ();
}
TEST (GetEnv, DISABLED_NameExplicit)
{
using namespace ckdb;
int argc = 2;
const char * cargv[] = { "any-name", "--elektra%name%=other-name" };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("other-name"));
elektraClose ();
}
#include "main.cpp"
<commit_msg>env: remove fallback test<commit_after>/**
* @file
*
* @brief Tests for the getenv library
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include <gtest/gtest.h>
#include <kdbgetenv.h>
TEST (GetEnv, NonExist)
{
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
}
TEST (GetEnv, ExistOverride)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnv)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist", "hello", 1);
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnvFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist-fb", "hello", 1);
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/fallback/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallbackFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user:/env/fallback/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, OpenClose)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user:/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
elektraClose ();
}
TEST (GetEnv, OpenCloseFallback)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user:/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
elektraClose ();
}
void elektraPrintConfig ()
{
using namespace ckdb;
for (elektraCursor it = 0; it < ksGetSize (elektraConfig); ++it)
{
const Key * c = ksAtCursor (elektraConfig, it);
printf ("%s - %s\n", keyName (c), keyString (c));
}
}
// FIXME [new_backend]: tests disabled
TEST (GetEnv, DISABLED_ArgvParam)
{
const char * cargv[] = { "name", "--elektra:does-exist=hello", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, DISABLED_ArgvParamUninvolved)
{
const char * cargv[] = { "name", "--uninvolved", "--not-used", "-L", "--elektra:does-exist=hello",
"--uninvolved", "--not-used", "-L", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 8;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 7) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], std::string ("--uninvolved"));
EXPECT_EQ (argv[2], std::string ("--not-used"));
EXPECT_EQ (argv[3], std::string ("-L"));
EXPECT_EQ (argv[4], std::string ("--uninvolved"));
EXPECT_EQ (argv[5], std::string ("--not-used"));
EXPECT_EQ (argv[6], std::string ("-L"));
EXPECT_EQ (argv[7], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, DISABLED_ArgvParamVersion)
{
const char * cargv[] = { "curl", "--elektra-version", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("curl"));
EXPECT_EQ (argv[1], std::string ("--elektra-version"));
EXPECT_EQ (argv[2], static_cast<char *> (nullptr));
ckdb::Key * kdb_version = ksLookupByName (elektraConfig, "system:/elektra/version/constants/KDB_VERSION", 0);
EXPECT_EQ (getenv ("version"), "Elektra getenv is active\n" + std::string ("KDB_VERSION: ") +
std::string (keyString (kdb_version)) + std::string ("\nKDB_GETENV_VERSION: ") +
KDB_GETENV_VERSION);
elektraClose ();
}
TEST (GetEnv, DISABLED_NameArgv0)
{
using namespace ckdb;
int argc = 1;
const char * cargv[] = { "path/to/any-name", nullptr };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("path/to/any-name"));
k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/basename", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("any-name"));
elektraClose ();
}
TEST (GetEnv, DISABLED_NameExplicit)
{
using namespace ckdb;
int argc = 2;
const char * cargv[] = { "any-name", "--elektra%name%=other-name" };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc:/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("other-name"));
elektraClose ();
}
#include "main.cpp"
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Baidu, Inc.G
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Authors: Lei He (helei@qiyi.com)
#include <cmath>
#include <gflags/gflags.h>
#include "brpc/errno.pb.h"
#include "brpc/policy/gradient_concurrency_limiter.h"
namespace brpc {
namespace policy {
DEFINE_int32(gradient_cl_sampling_interval_us, 100,
"Interval for sampling request in gradient concurrency limiter");
DEFINE_int32(gradient_cl_sample_window_size_ms, 1000,
"Sample window size for update max concurrency in grandient "
"concurrency limiter");
DEFINE_int32(gradient_cl_min_sample_count, 100,
"Minimum sample count for update max concurrency");
DEFINE_double(gradient_cl_adjust_smooth, 0.9,
"Smooth coefficient for adjust the max concurrency, the value is 0-1,"
"the larger the value, the smaller the amount of each change");
DEFINE_int32(gradient_cl_initial_max_concurrency, 40,
"Initial max concurrency for grandient concurrency limiter");
DEFINE_bool(gradient_cl_enable_error_punish, true,
"Whether to consider failed requests when calculating maximum concurrency");
DEFINE_int32(gradient_cl_max_error_punish_ms, 3000,
"The maximum time wasted for a single failed request");
DEFINE_double(gradient_cl_fail_punish_ratio, 1.0,
"Use the failed requests to punish normal requests. The larger the "
"configuration item, the more aggressive the penalty strategy.");
DEFINE_int32(gradient_cl_reserved_concurrency, 0,
"The maximum concurrency reserved when the service is not overloaded."
"When the traffic increases, the larger the configuration item, the "
"faster the maximum concurrency grows until the server is fully loaded."
"When the value is less than or equal to 0, square root of current "
"concurrency is used.");
DEFINE_int32(gradient_cl_reset_count, 30,
"The service's latency will be re-measured every `reset_count' windows.");
static int32_t cast_max_concurrency(void* arg) {
return *(int32_t*) arg;
}
GradientConcurrencyLimiter::GradientConcurrencyLimiter()
: _unused_max_concurrency(0)
, _reset_count(NextResetCount())
, _min_latency_us(-1)
, _smooth(FLAGS_gradient_cl_adjust_smooth)
, _ema_qps(0)
, _max_concurrency_bvar(cast_max_concurrency, &_max_concurrency)
, _last_sampling_time_us(0)
, _max_concurrency(FLAGS_gradient_cl_initial_max_concurrency)
, _total_succ_req(0)
, _current_concurrency(0) {
}
int GradientConcurrencyLimiter::MaxConcurrency() const {
return _max_concurrency.load(butil::memory_order_relaxed);
}
int& GradientConcurrencyLimiter::MaxConcurrencyRef() {
return _unused_max_concurrency;
}
int GradientConcurrencyLimiter::Expose(const butil::StringPiece& prefix) {
if (_max_concurrency_bvar.expose_as(prefix, "gradient_cl_max_concurrency") != 0) {
return -1;
}
return 0;
}
GradientConcurrencyLimiter* GradientConcurrencyLimiter::New() const {
return new (std::nothrow) GradientConcurrencyLimiter;
}
void GradientConcurrencyLimiter::Destroy() {
delete this;
}
bool GradientConcurrencyLimiter::OnRequested() {
const int32_t current_concurrency =
_current_concurrency.fetch_add(1, butil::memory_order_relaxed);
if (current_concurrency >= _max_concurrency.load(butil::memory_order_relaxed)) {
return false;
}
return true;
}
void GradientConcurrencyLimiter::OnResponded(int error_code,
int64_t latency_us) {
_current_concurrency.fetch_sub(1, butil::memory_order_relaxed);
if (0 == error_code) {
_total_succ_req.fetch_add(1, butil::memory_order_relaxed);
} else if (ELIMIT == error_code) {
return;
}
int64_t now_time_us = butil::gettimeofday_us();
int64_t last_sampling_time_us =
_last_sampling_time_us.load(butil::memory_order_relaxed);
if (last_sampling_time_us == 0 ||
now_time_us - last_sampling_time_us >=
FLAGS_gradient_cl_sampling_interval_us) {
bool sample_this_call = _last_sampling_time_us.compare_exchange_weak(
last_sampling_time_us, now_time_us,
butil::memory_order_relaxed);
if (sample_this_call) {
AddSample(error_code, latency_us, now_time_us);
}
}
}
int GradientConcurrencyLimiter::NextResetCount() {
int max_reset_count = FLAGS_gradient_cl_reset_count;
return rand() % (max_reset_count / 2) + max_reset_count / 2;
}
void GradientConcurrencyLimiter::AddSample(int error_code, int64_t latency_us,
int64_t sampling_time_us) {
BAIDU_SCOPED_LOCK(_sw_mutex);
if (_sw.start_time_us == 0) {
_sw.start_time_us = sampling_time_us;
}
if (error_code != 0 &&
FLAGS_gradient_cl_enable_error_punish) {
++_sw.failed_count;
latency_us =
std::min(int64_t(FLAGS_gradient_cl_max_error_punish_ms) * 1000,
latency_us);
_sw.total_failed_us += latency_us;
} else if (error_code == 0) {
++_sw.succ_count;
_sw.total_succ_us += latency_us;
}
if (sampling_time_us - _sw.start_time_us <
FLAGS_gradient_cl_sample_window_size_ms * 1000) {
return;
} else if (_sw.succ_count + _sw.failed_count <
FLAGS_gradient_cl_min_sample_count) {
LOG_EVERY_N(INFO, 100) << "Insufficient sample size";
} else if (_sw.succ_count > 0) {
UpdateConcurrency(sampling_time_us);
ResetSampleWindow(sampling_time_us);
} else {
LOG(ERROR) << "All request failed, resize max_concurrency";
int32_t current_concurrency =
_current_concurrency.load(butil::memory_order_relaxed);
_current_concurrency.store(
current_concurrency / 2, butil::memory_order_relaxed);
}
}
void GradientConcurrencyLimiter::ResetSampleWindow(int64_t sampling_time_us) {
_sw.start_time_us = sampling_time_us;
_sw.succ_count = 0;
_sw.failed_count = 0;
_sw.total_failed_us = 0;
_sw.total_succ_us = 0;
}
void GradientConcurrencyLimiter::UpdateMinLatency(int64_t latency_us) {
if (_min_latency_us <= 0) {
_min_latency_us = latency_us;
} else if (latency_us < _min_latency_us) {
_min_latency_us = _min_latency_us * _smooth + latency_us * (1 - _smooth);
}
}
void GradientConcurrencyLimiter::UpdateQps(int32_t succ_count,
int64_t sampling_time_us) {
double qps = double(succ_count) / (sampling_time_us - _sw.start_time_us)
* 1000 * 1000;
_ema_qps = _ema_qps * _smooth + qps * (1 - _smooth);
}
void GradientConcurrencyLimiter::UpdateConcurrency(int64_t sampling_time_us) {
int32_t current_concurrency = _current_concurrency.load();
int max_concurrency = _max_concurrency.load();
int32_t total_succ_req =
_total_succ_req.exchange(0, butil::memory_order_relaxed);
int64_t failed_punish =
_sw.total_failed_us * FLAGS_gradient_cl_fail_punish_ratio;
int64_t avg_latency =
std::ceil((failed_punish + _sw.total_succ_us) / _sw.succ_count);
UpdateMinLatency(avg_latency);
UpdateQps(total_succ_req, sampling_time_us);
int reserved_concurrency = FLAGS_gradient_cl_reserved_concurrency;
if (reserved_concurrency <= 0) {
reserved_concurrency = std::ceil(std::sqrt(max_concurrency));
}
int32_t next_concurrency =
std::ceil(_ema_qps * _min_latency_us / 1000.0 / 1000);
int32_t saved_min_latency_us = _min_latency_us;
if (--_reset_count == 0) {
_reset_count = NextResetCount();
if (current_concurrency >= max_concurrency - 2) {
_min_latency_us = -1;
next_concurrency -= std::sqrt(max_concurrency);
next_concurrency = std::max(next_concurrency, reserved_concurrency);
} else {
// current_concurrency < max_concurrency means the server is
// not overloaded and does not need to detect noload_latency by
// lowering the maximum concurrency
next_concurrency += reserved_concurrency;
}
} else {
next_concurrency += reserved_concurrency;
}
LOG(INFO)
<< "Update max_concurrency by gradient limiter:"
<< " pre_max_concurrency:" << max_concurrency
<< ", min_avg_latency:" << saved_min_latency_us << "us"
<< ", reserved_concurrency:" << reserved_concurrency
<< ", sampling_avg_latency:" << avg_latency << "us"
<< ", failed_punish:" << failed_punish << "us"
<< ", ema_qps:" << _ema_qps
<< ", succ sample count" << _sw.succ_count
<< ", failed sample count" << _sw.failed_count
<< ", current_concurrency:" << current_concurrency
<< ", next_max_concurrency:" << next_concurrency;
_max_concurrency.store(next_concurrency, butil::memory_order_relaxed);
}
} // namespace policy
} // namespace brpc
<commit_msg>Modify max_concurrency only if necessary<commit_after>// Copyright (c) 2014 Baidu, Inc.G
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Authors: Lei He (helei@qiyi.com)
#include <cmath>
#include <gflags/gflags.h>
#include "brpc/errno.pb.h"
#include "brpc/policy/gradient_concurrency_limiter.h"
namespace brpc {
namespace policy {
DEFINE_int32(gradient_cl_sampling_interval_us, 100,
"Interval for sampling request in gradient concurrency limiter");
DEFINE_int32(gradient_cl_sample_window_size_ms, 1000,
"Sample window size for update max concurrency in grandient "
"concurrency limiter");
DEFINE_int32(gradient_cl_min_sample_count, 100,
"Minimum sample count for update max concurrency");
DEFINE_double(gradient_cl_adjust_smooth, 0.9,
"Smooth coefficient for adjust the max concurrency, the value is 0-1,"
"the larger the value, the smaller the amount of each change");
DEFINE_int32(gradient_cl_initial_max_concurrency, 40,
"Initial max concurrency for grandient concurrency limiter");
DEFINE_bool(gradient_cl_enable_error_punish, true,
"Whether to consider failed requests when calculating maximum concurrency");
DEFINE_int32(gradient_cl_max_error_punish_ms, 3000,
"The maximum time wasted for a single failed request");
DEFINE_double(gradient_cl_fail_punish_ratio, 1.0,
"Use the failed requests to punish normal requests. The larger the "
"configuration item, the more aggressive the penalty strategy.");
DEFINE_int32(gradient_cl_reserved_concurrency, 0,
"The maximum concurrency reserved when the service is not overloaded."
"When the traffic increases, the larger the configuration item, the "
"faster the maximum concurrency grows until the server is fully loaded."
"When the value is less than or equal to 0, square root of current "
"concurrency is used.");
DEFINE_int32(gradient_cl_reset_count, 30,
"The service's latency will be re-measured every `reset_count' windows.");
static int32_t cast_max_concurrency(void* arg) {
return *(int32_t*) arg;
}
GradientConcurrencyLimiter::GradientConcurrencyLimiter()
: _unused_max_concurrency(0)
, _reset_count(NextResetCount())
, _min_latency_us(-1)
, _smooth(FLAGS_gradient_cl_adjust_smooth)
, _ema_qps(0)
, _max_concurrency_bvar(cast_max_concurrency, &_max_concurrency)
, _last_sampling_time_us(0)
, _max_concurrency(FLAGS_gradient_cl_initial_max_concurrency)
, _total_succ_req(0)
, _current_concurrency(0) {
}
int GradientConcurrencyLimiter::MaxConcurrency() const {
return _max_concurrency.load(butil::memory_order_relaxed);
}
int& GradientConcurrencyLimiter::MaxConcurrencyRef() {
return _unused_max_concurrency;
}
int GradientConcurrencyLimiter::Expose(const butil::StringPiece& prefix) {
if (_max_concurrency_bvar.expose_as(prefix, "gradient_cl_max_concurrency") != 0) {
return -1;
}
return 0;
}
GradientConcurrencyLimiter* GradientConcurrencyLimiter::New() const {
return new (std::nothrow) GradientConcurrencyLimiter;
}
void GradientConcurrencyLimiter::Destroy() {
delete this;
}
bool GradientConcurrencyLimiter::OnRequested() {
const int32_t current_concurrency =
_current_concurrency.fetch_add(1, butil::memory_order_relaxed);
if (current_concurrency >= _max_concurrency.load(butil::memory_order_relaxed)) {
return false;
}
return true;
}
void GradientConcurrencyLimiter::OnResponded(int error_code,
int64_t latency_us) {
_current_concurrency.fetch_sub(1, butil::memory_order_relaxed);
if (0 == error_code) {
_total_succ_req.fetch_add(1, butil::memory_order_relaxed);
} else if (ELIMIT == error_code) {
return;
}
int64_t now_time_us = butil::gettimeofday_us();
int64_t last_sampling_time_us =
_last_sampling_time_us.load(butil::memory_order_relaxed);
if (last_sampling_time_us == 0 ||
now_time_us - last_sampling_time_us >=
FLAGS_gradient_cl_sampling_interval_us) {
bool sample_this_call = _last_sampling_time_us.compare_exchange_weak(
last_sampling_time_us, now_time_us,
butil::memory_order_relaxed);
if (sample_this_call) {
AddSample(error_code, latency_us, now_time_us);
}
}
}
int GradientConcurrencyLimiter::NextResetCount() {
int max_reset_count = FLAGS_gradient_cl_reset_count;
return rand() % (max_reset_count / 2) + max_reset_count / 2;
}
void GradientConcurrencyLimiter::AddSample(int error_code, int64_t latency_us,
int64_t sampling_time_us) {
BAIDU_SCOPED_LOCK(_sw_mutex);
if (_sw.start_time_us == 0) {
_sw.start_time_us = sampling_time_us;
}
if (error_code != 0 &&
FLAGS_gradient_cl_enable_error_punish) {
++_sw.failed_count;
latency_us =
std::min(int64_t(FLAGS_gradient_cl_max_error_punish_ms) * 1000,
latency_us);
_sw.total_failed_us += latency_us;
} else if (error_code == 0) {
++_sw.succ_count;
_sw.total_succ_us += latency_us;
}
if (sampling_time_us - _sw.start_time_us <
FLAGS_gradient_cl_sample_window_size_ms * 1000) {
return;
} else if (_sw.succ_count + _sw.failed_count <
FLAGS_gradient_cl_min_sample_count) {
LOG_EVERY_N(INFO, 100) << "Insufficient sample size";
} else if (_sw.succ_count > 0) {
UpdateConcurrency(sampling_time_us);
ResetSampleWindow(sampling_time_us);
} else {
LOG(ERROR) << "All request failed, resize max_concurrency";
int32_t current_concurrency =
_current_concurrency.load(butil::memory_order_relaxed);
_current_concurrency.store(
current_concurrency / 2, butil::memory_order_relaxed);
}
}
void GradientConcurrencyLimiter::ResetSampleWindow(int64_t sampling_time_us) {
_sw.start_time_us = sampling_time_us;
_sw.succ_count = 0;
_sw.failed_count = 0;
_sw.total_failed_us = 0;
_sw.total_succ_us = 0;
}
void GradientConcurrencyLimiter::UpdateMinLatency(int64_t latency_us) {
if (_min_latency_us <= 0) {
_min_latency_us = latency_us;
} else if (latency_us < _min_latency_us) {
_min_latency_us = _min_latency_us * _smooth + latency_us * (1 - _smooth);
}
}
void GradientConcurrencyLimiter::UpdateQps(int32_t succ_count,
int64_t sampling_time_us) {
double qps = double(succ_count) / (sampling_time_us - _sw.start_time_us)
* 1000 * 1000;
_ema_qps = _ema_qps * _smooth + qps * (1 - _smooth);
}
void GradientConcurrencyLimiter::UpdateConcurrency(int64_t sampling_time_us) {
int32_t current_concurrency = _current_concurrency.load();
int max_concurrency = _max_concurrency.load();
int32_t total_succ_req =
_total_succ_req.exchange(0, butil::memory_order_relaxed);
int64_t failed_punish =
_sw.total_failed_us * FLAGS_gradient_cl_fail_punish_ratio;
int64_t avg_latency =
std::ceil((failed_punish + _sw.total_succ_us) / _sw.succ_count);
UpdateMinLatency(avg_latency);
UpdateQps(total_succ_req, sampling_time_us);
int reserved_concurrency = FLAGS_gradient_cl_reserved_concurrency;
if (reserved_concurrency <= 0) {
reserved_concurrency = std::ceil(std::sqrt(max_concurrency));
}
int32_t next_concurrency =
std::ceil(_ema_qps * _min_latency_us / 1000.0 / 1000);
int32_t saved_min_latency_us = _min_latency_us;
if (--_reset_count == 0) {
_reset_count = NextResetCount();
if (current_concurrency >= max_concurrency - 2) {
_min_latency_us = -1;
next_concurrency -= std::sqrt(max_concurrency);
next_concurrency = std::max(next_concurrency, reserved_concurrency);
} else {
// current_concurrency < max_concurrency means the server is
// not overloaded and does not need to detect noload_latency by
// lowering the maximum concurrency
next_concurrency += reserved_concurrency;
}
} else {
next_concurrency += reserved_concurrency;
}
LOG(INFO)
<< "Update max_concurrency by gradient limiter:"
<< " pre_max_concurrency:" << max_concurrency
<< ", min_avg_latency:" << saved_min_latency_us << "us"
<< ", reserved_concurrency:" << reserved_concurrency
<< ", sampling_avg_latency:" << avg_latency << "us"
<< ", failed_punish:" << failed_punish << "us"
<< ", ema_qps:" << _ema_qps
<< ", succ sample count" << _sw.succ_count
<< ", failed sample count" << _sw.failed_count
<< ", current_concurrency:" << current_concurrency
<< ", next_max_concurrency:" << next_concurrency;
if (next_concurrency != max_concurrency) {
_max_concurrency.store(next_concurrency, butil::memory_order_relaxed);
}
}
} // namespace policy
} // namespace brpc
<|endoftext|>
|
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL/PIXHAWK PROJECT
<http://www.qgroundcontrol.org>
<http://pixhawk.ethz.ch>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCParamWidget
* @author Lorenz Meier <mail@qgroundcontrol.org>
*/
#include <QGridLayout>
#include <QPushButton>
#include "QGCParamWidget.h"
#include "UASInterface.h"
#include <QDebug>
/**
* @param uas MAV to set the parameters on
* @param parent Parent widget
*/
QGCParamWidget::QGCParamWidget(UASInterface* uas, QWidget *parent) :
QWidget(parent),
mav(uas),
components(new QMap<int, QTreeWidgetItem*>()),
changedValues()//QMap<int, QMap<QString, float>* >())
{
// Create tree widget
tree = new QTreeWidget(this);
tree->setColumnWidth(0, 150);
// Set tree widget as widget onto this component
QGridLayout* horizontalLayout;
//form->setAutoFillBackground(false);
horizontalLayout = new QGridLayout(this);
horizontalLayout->setSpacing(6);
horizontalLayout->setMargin(0);
horizontalLayout->setSizeConstraint(QLayout::SetMinimumSize);
horizontalLayout->addWidget(tree, 0, 0, 1, 3);
QPushButton* readButton = new QPushButton(tr("Read"));
connect(readButton, SIGNAL(clicked()), this, SLOT(requestParameterList()));
horizontalLayout->addWidget(readButton, 1, 0);
QPushButton* setButton = new QPushButton(tr("Set (RAM)"));
connect(setButton, SIGNAL(clicked()), this, SLOT(setParameters()));
horizontalLayout->addWidget(setButton, 1, 1);
QPushButton* writeButton = new QPushButton(tr("Write (Disk)"));
connect(writeButton, SIGNAL(clicked()), this, SLOT(writeParameters()));
horizontalLayout->addWidget(writeButton, 1, 2);
// Set layout
this->setLayout(horizontalLayout);
// Set header
QStringList headerItems;
headerItems.append("Parameter");
headerItems.append("Value");
tree->setHeaderLabels(headerItems);
tree->setColumnCount(2);
// Connect signals/slots
connect(this, SIGNAL(parameterChanged(int,QString,float)), mav, SLOT(setParameter(int,QString,float)));
connect(tree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(parameterItemChanged(QTreeWidgetItem*,int)));
// New parameters from UAS
connect(uas, SIGNAL(parameterChanged(int,int,QString,float)), this, SLOT(addParameter(int,int,QString,float)));
}
/**
* @return The MAV of this widget. Unless the MAV object has been destroyed, this
* pointer is never zero.
*/
UASInterface* QGCParamWidget::getUAS()
{
return mav;
}
/**
*
* @param uas System which has the component
* @param component id of the component
* @param componentName human friendly name of the component
*/
void QGCParamWidget::addComponent(int uas, int component, QString componentName)
{
Q_UNUSED(uas);
QStringList list;
list.append(componentName);
list.append(QString::number(component));
QTreeWidgetItem* comp = new QTreeWidgetItem(list);
bool updated = false;
if (components->contains(component)) updated = true;
components->insert(component, comp);
if (!updated)
{
tree->addTopLevelItem(comp);
tree->update();
}
}
/**
* @param uas System which has the component
* @param component id of the component
* @param parameterName human friendly name of the parameter
*/
void QGCParamWidget::addParameter(int uas, int component, QString parameterName, float value)
{
Q_UNUSED(uas);
// Insert parameter into map
//tree->appendParam(component, parameterName, value);
QStringList plist;
plist.append(parameterName);
plist.append(QString::number(value));
QTreeWidgetItem* item = new QTreeWidgetItem(plist);
// Get component
if (!components->contains(component))
{
addComponent(uas, component, "Component #" + QString::number(component));
}
bool found = false;
QTreeWidgetItem* parent = components->value(component);
for (int i = 0; i < parent->childCount(); i++)
{
QTreeWidgetItem* child = parent->child(i);
QString key = child->data(0, Qt::DisplayRole).toString();
if (key == parameterName)
{
child->setData(1, Qt::DisplayRole, value);
found = true;
}
}
if (!found)
{
components->value(component)->addChild(item);
item->setFlags(item->flags() | Qt::ItemIsEditable);
}
//connect(item, SIGNAL())
tree->expandAll();
tree->update();
}
/**
* Send a request to deliver the list of onboard parameters
* to the MAV.
*/
void QGCParamWidget::requestParameterList()
{
// Clear view and request param list
clear();
mav->requestParameters();
}
void QGCParamWidget::parameterItemChanged(QTreeWidgetItem* current, int column)
{
if (current && column > 0)
{
QTreeWidgetItem* parent = current->parent();
while (parent->parent() != NULL)
{
parent = parent->parent();
}
// Parent is now top-level component
int key = components->key(parent);
if (!changedValues.contains(key))
{
changedValues.insert(key, new QMap<QString, float>());
}
QMap<QString, float>* map = changedValues.value(key, NULL);
if (map)
{
bool ok;
QString str = current->data(0, Qt::DisplayRole).toString();
float value = current->data(1, Qt::DisplayRole).toDouble(&ok);
// Send parameter to MAV
if (ok)
{
if (ok)
{
qDebug() << "PARAM CHANGED: COMP:" << key << "KEY:" << str << "VALUE:" << value;
map->insert(str, value);
}
}
}
}
}
/**
* @param component the subsystem which has the parameter
* @param parameterName name of the parameter, as delivered by the system
* @param value value of the parameter
*/
void QGCParamWidget::setParameter(int component, QString parameterName, float value)
{
emit parameterChanged(component, parameterName, value);
}
/**
* Set all parameter in the parameter tree on the MAV
*/
void QGCParamWidget::setParameters()
{
// Iterate through all components, through all parameters and emit them
QMap<int, QMap<QString, float>*>::iterator i;
for (i = changedValues.begin(); i != changedValues.end(); ++i)
{
// Iterate through the parameters of the component
int compid = i.key();
QMap<QString, float>* comp = i.value();
{
QMap<QString, float>::iterator j;
for (j = comp->begin(); j != comp->end(); ++j)
{
emit parameterChanged(compid, j.key(), j.value());
}
}
}
/*
//mav->setParameter(component, parameterName, value);
// Iterate through all components, through all parameters and emit them
QMap<int, QTreeWidgetItem*>::iterator i;
// Iterate through all components / subsystems
for (i = components->begin(); i != components->end(); ++i)
{
// Get all parameters of this component
int compid = i.key();
QTreeWidgetItem* item = i.value();
for (int j = 0; j < item->childCount(); ++j)
{
QTreeWidgetItem* param = item->child(j);
// First column is name, second column value
bool ok = true;
QString key = param->data(0, Qt::DisplayRole).toString();
float value = param->data(1, Qt::DisplayRole).toDouble(&ok);
// Send parameter to MAV
if (ok)
{
emit parameterChanged(compid, key, value);
qDebug() << " SET PARAM: KEY:" << key << "VALUE:" << value;
}
else
{
qDebug() << __FILE__ << __LINE__ << "CONVERSION ERROR!";
}
}
}
// TODO Instead of clearing, keep parameter list and wait for individual update messages
clear();
*/
//mav->requestParameters();
qDebug() << __FILE__ << __LINE__ << "SETTING ALL PARAMETERS";
}
/**
* Write the current onboard parameters from RAM into
* permanent storage, e.g. EEPROM or harddisk
*/
void QGCParamWidget::writeParameters()
{
mav->writeParameters();
}
/**
* Clear all data in the parameter widget
*/
void QGCParamWidget::clear()
{
tree->clear();
components->clear();
}
<commit_msg>Param interface fully working now<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL/PIXHAWK PROJECT
<http://www.qgroundcontrol.org>
<http://pixhawk.ethz.ch>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCParamWidget
* @author Lorenz Meier <mail@qgroundcontrol.org>
*/
#include <QGridLayout>
#include <QPushButton>
#include "QGCParamWidget.h"
#include "UASInterface.h"
#include <QDebug>
/**
* @param uas MAV to set the parameters on
* @param parent Parent widget
*/
QGCParamWidget::QGCParamWidget(UASInterface* uas, QWidget *parent) :
QWidget(parent),
mav(uas),
components(new QMap<int, QTreeWidgetItem*>()),
changedValues()//QMap<int, QMap<QString, float>* >())
{
// Create tree widget
tree = new QTreeWidget(this);
tree->setColumnWidth(0, 150);
// Set tree widget as widget onto this component
QGridLayout* horizontalLayout;
//form->setAutoFillBackground(false);
horizontalLayout = new QGridLayout(this);
horizontalLayout->setSpacing(6);
horizontalLayout->setMargin(0);
horizontalLayout->setSizeConstraint(QLayout::SetMinimumSize);
horizontalLayout->addWidget(tree, 0, 0, 1, 3);
QPushButton* readButton = new QPushButton(tr("Read"));
connect(readButton, SIGNAL(clicked()), this, SLOT(requestParameterList()));
horizontalLayout->addWidget(readButton, 1, 0);
QPushButton* setButton = new QPushButton(tr("Set (RAM)"));
connect(setButton, SIGNAL(clicked()), this, SLOT(setParameters()));
horizontalLayout->addWidget(setButton, 1, 1);
QPushButton* writeButton = new QPushButton(tr("Write (Disk)"));
connect(writeButton, SIGNAL(clicked()), this, SLOT(writeParameters()));
horizontalLayout->addWidget(writeButton, 1, 2);
// Set layout
this->setLayout(horizontalLayout);
// Set header
QStringList headerItems;
headerItems.append("Parameter");
headerItems.append("Value");
tree->setHeaderLabels(headerItems);
tree->setColumnCount(2);
// Connect signals/slots
connect(this, SIGNAL(parameterChanged(int,QString,float)), mav, SLOT(setParameter(int,QString,float)));
connect(tree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(parameterItemChanged(QTreeWidgetItem*,int)));
// New parameters from UAS
connect(uas, SIGNAL(parameterChanged(int,int,QString,float)), this, SLOT(addParameter(int,int,QString,float)));
}
/**
* @return The MAV of this widget. Unless the MAV object has been destroyed, this
* pointer is never zero.
*/
UASInterface* QGCParamWidget::getUAS()
{
return mav;
}
/**
*
* @param uas System which has the component
* @param component id of the component
* @param componentName human friendly name of the component
*/
void QGCParamWidget::addComponent(int uas, int component, QString componentName)
{
Q_UNUSED(uas);
QStringList list;
list.append(componentName);
list.append(QString::number(component));
QTreeWidgetItem* comp = new QTreeWidgetItem(list);
bool updated = false;
if (components->contains(component)) updated = true;
components->insert(component, comp);
if (!updated)
{
tree->addTopLevelItem(comp);
tree->update();
}
}
/**
* @param uas System which has the component
* @param component id of the component
* @param parameterName human friendly name of the parameter
*/
void QGCParamWidget::addParameter(int uas, int component, QString parameterName, float value)
{
Q_UNUSED(uas);
// Insert parameter into map
//tree->appendParam(component, parameterName, value);
QStringList plist;
plist.append(parameterName);
plist.append(QString::number(value));
QTreeWidgetItem* item = new QTreeWidgetItem(plist);
// Get component
if (!components->contains(component))
{
addComponent(uas, component, "Component #" + QString::number(component));
}
bool found = false;
QTreeWidgetItem* parent = components->value(component);
for (int i = 0; i < parent->childCount(); i++)
{
QTreeWidgetItem* child = parent->child(i);
QString key = child->data(0, Qt::DisplayRole).toString();
if (key == parameterName)
{
qDebug() << "UPDATED CHILD";
child->setData(1, Qt::DisplayRole, value);
found = true;
}
}
if (!found)
{
components->value(component)->addChild(item);
item->setFlags(item->flags() | Qt::ItemIsEditable);
}
//connect(item, SIGNAL())
tree->expandAll();
tree->update();
}
/**
* Send a request to deliver the list of onboard parameters
* to the MAV.
*/
void QGCParamWidget::requestParameterList()
{
// Clear view and request param list
clear();
mav->requestParameters();
}
void QGCParamWidget::parameterItemChanged(QTreeWidgetItem* current, int column)
{
if (current && column > 0)
{
QTreeWidgetItem* parent = current->parent();
while (parent->parent() != NULL)
{
parent = parent->parent();
}
// Parent is now top-level component
int key = components->key(parent);
if (!changedValues.contains(key))
{
changedValues.insert(key, new QMap<QString, float>());
}
QMap<QString, float>* map = changedValues.value(key, NULL);
if (map)
{
bool ok;
QString str = current->data(0, Qt::DisplayRole).toString();
float value = current->data(1, Qt::DisplayRole).toDouble(&ok);
// Send parameter to MAV
if (ok)
{
if (ok)
{
qDebug() << "PARAM CHANGED: COMP:" << key << "KEY:" << str << "VALUE:" << value;
map->insert(str, value);
}
}
}
}
}
/**
* @param component the subsystem which has the parameter
* @param parameterName name of the parameter, as delivered by the system
* @param value value of the parameter
*/
void QGCParamWidget::setParameter(int component, QString parameterName, float value)
{
emit parameterChanged(component, parameterName, value);
}
/**
* Set all parameter in the parameter tree on the MAV
*/
void QGCParamWidget::setParameters()
{
// Iterate through all components, through all parameters and emit them
QMap<int, QMap<QString, float>*>::iterator i;
for (i = changedValues.begin(); i != changedValues.end(); ++i)
{
// Iterate through the parameters of the component
int compid = i.key();
QMap<QString, float>* comp = i.value();
{
QMap<QString, float>::iterator j;
for (j = comp->begin(); j != comp->end(); ++j)
{
emit parameterChanged(compid, j.key(), j.value());
}
}
}
changedValues.clear();
qDebug() << __FILE__ << __LINE__ << "SETTING ALL PARAMETERS";
}
/**
* Write the current onboard parameters from RAM into
* permanent storage, e.g. EEPROM or harddisk
*/
void QGCParamWidget::writeParameters()
{
mav->writeParameters();
}
/**
* Clear all data in the parameter widget
*/
void QGCParamWidget::clear()
{
tree->clear();
components->clear();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInputStream.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkInputStream.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkInputStream);
//----------------------------------------------------------------------------
vtkInputStream::vtkInputStream()
{
this->Stream = 0;
}
//----------------------------------------------------------------------------
vtkInputStream::~vtkInputStream()
{
this->SetStream(0);
}
//----------------------------------------------------------------------------
void vtkInputStream::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Stream: " << (this->Stream? "set" : "none") << "\n";
}
//----------------------------------------------------------------------------
void vtkInputStream::StartReading()
{
if(!this->Stream)
{
vtkErrorMacro("StartReading() called with no Stream set.");
}
this->StreamStartPosition = this->Stream->tellg();
}
//----------------------------------------------------------------------------
void vtkInputStream::EndReading()
{
}
//----------------------------------------------------------------------------
int vtkInputStream::Seek(vtkTypeInt64 offset)
{
std::streamoff off =
static_cast<std::streamoff>(this->StreamStartPosition+offset);
return (this->Stream->seekg(off, std::ios::beg)? 1:0);
}
//----------------------------------------------------------------------------
size_t vtkInputStream::Read(void* data, size_t length)
{
return this->ReadStream(static_cast<char*>(data), length);
}
//----------------------------------------------------------------------------
size_t vtkInputStream::ReadStream(char* data, size_t length)
{
this->Stream->read(data, length);
return this->Stream->gcount();
}
<commit_msg>Fixed null deref found by clang analyzer<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInputStream.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkInputStream.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkInputStream);
//----------------------------------------------------------------------------
vtkInputStream::vtkInputStream()
{
this->Stream = 0;
}
//----------------------------------------------------------------------------
vtkInputStream::~vtkInputStream()
{
this->SetStream(0);
}
//----------------------------------------------------------------------------
void vtkInputStream::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Stream: " << (this->Stream? "set" : "none") << "\n";
}
//----------------------------------------------------------------------------
void vtkInputStream::StartReading()
{
if(!this->Stream)
{
vtkErrorMacro("StartReading() called with no Stream set.");
return;
}
this->StreamStartPosition = this->Stream->tellg();
}
//----------------------------------------------------------------------------
void vtkInputStream::EndReading()
{
}
//----------------------------------------------------------------------------
int vtkInputStream::Seek(vtkTypeInt64 offset)
{
std::streamoff off =
static_cast<std::streamoff>(this->StreamStartPosition+offset);
return (this->Stream->seekg(off, std::ios::beg)? 1:0);
}
//----------------------------------------------------------------------------
size_t vtkInputStream::Read(void* data, size_t length)
{
return this->ReadStream(static_cast<char*>(data), length);
}
//----------------------------------------------------------------------------
size_t vtkInputStream::ReadStream(char* data, size_t length)
{
this->Stream->read(data, length);
return this->Stream->gcount();
}
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Rainer Gericke
// =============================================================================
//
// WVP TMeasy tire subsystem
//
// =============================================================================
#include <algorithm>
#include <cmath>
#include "chrono_models/vehicle/wvp/WVP_TMeasyTire.h"
#include "chrono_vehicle/ChVehicleModelData.h"
namespace chrono {
namespace vehicle {
namespace wvp {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const std::string WVP_TMeasyTire::m_meshName = "hmmwv_tire_POV_geom";
const std::string WVP_TMeasyTire::m_meshFile = "hmmwv/hmmwv_tire.obj";
const double WVP_TMeasyTire::m_mass = 71.1;
const ChVector<> WVP_TMeasyTire::m_inertia(9.62, 16.84, 9.62);
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
WVP_TMeasyTire::WVP_TMeasyTire(const std::string& name) : ChTMeasyTire(name) {
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WVP_TMeasyTire::SetTMeasyParams() {
// Set Handling Charecteristics as close as possible to Pacejka89 model data
m_TMeasyCoeff.pn = GetTireMaxLoad(152)/2.0;
m_TMeasyCoeff.mu_0 = 0.8;
// Set nonlinear vertical stiffness
std::vector<double> disp, force;
disp.push_back(0.01); force.push_back(3276.0);
disp.push_back(0.02); force.push_back(6729.0);
disp.push_back(0.03); force.push_back(10361.0);
disp.push_back(0.04); force.push_back(14171.0);
disp.push_back(0.05); force.push_back(18159.0);
disp.push_back(0.06); force.push_back(22325.0);
disp.push_back(0.07); force.push_back(26670.0);
disp.push_back(0.08); force.push_back(31192.0);
disp.push_back(0.09); force.push_back(35893.0);
disp.push_back(0.10); force.push_back(40772.0);
SetVerticalStiffness(disp,force);
m_width = 0.372;
m_unloaded_radius = 1.096 / 2.0;
m_rolling_resistance = 0.015;
m_TMeasyCoeff.mu_0 = 0.8;
// Simple damping model from single mass oscilator
double xi = 0.05; // tire damping ratio
double C1 = 1000.0*sqrt(pow(m_a1,2)+4.0*m_a2*m_TMeasyCoeff.pn/1000);
double C2 = 1000.0*sqrt(pow(m_a1,2)+8.0*m_a2*m_TMeasyCoeff.pn/1000);
double CZM = (C1 + C2) / 2.0;
m_TMeasyCoeff.dz = 2.0 * xi * sqrt(CZM * WVP_TMeasyTire::m_mass);
m_TMeasyCoeff.dfx0_pn = 242.678443;
m_TMeasyCoeff.sxm_pn = 0.134552;
m_TMeasyCoeff.fxm_pn = 13.832671;
m_TMeasyCoeff.sxs_pn = 0.500000;
m_TMeasyCoeff.fxs_pn = 12.387002;
m_TMeasyCoeff.dfx0_p2n = 664.223777;
m_TMeasyCoeff.sxm_p2n = 0.109770;
m_TMeasyCoeff.fxm_p2n = 24.576280;
m_TMeasyCoeff.sxs_p2n = 0.800000;
m_TMeasyCoeff.fxs_p2n = 22.079064;
m_TMeasyCoeff.dfy0_pn = 168.715739;
m_TMeasyCoeff.sym_pn = 0.258411;
m_TMeasyCoeff.fym_pn = 13.038949;
m_TMeasyCoeff.sys_pn = 0.800000;
m_TMeasyCoeff.fys_pn = 12.387002;
m_TMeasyCoeff.dfy0_p2n = 320.100587;
m_TMeasyCoeff.sym_p2n = 0.238826;
m_TMeasyCoeff.fym_p2n = 23.241121;
m_TMeasyCoeff.sys_p2n = 1.000000;
m_TMeasyCoeff.fys_p2n = 22.079064;
m_TMeasyCoeff.nto0_pn = 0.160000;
m_TMeasyCoeff.synto0_pn = 0.200000;
m_TMeasyCoeff.syntoE_pn = 0.480000;
m_TMeasyCoeff.nto0_p2n = 0.170000;
m_TMeasyCoeff.synto0_p2n = 0.200000;
m_TMeasyCoeff.syntoE_p2n = 0.500000;
if(CheckParameters()) {
std::cout << "Parameter Set seems to be ok." << std::endl;
} else {
std::cout << "Badly formed parameter set." << std::endl;
}
if(GetName().compare("FL") == 0) {
GenerateCharacteristicPlots("../");
}
}
void WVP_TMeasyTire::GenerateCharacteristicPlots(const std::string& dirname) {
// Write a plot file (gnuplot) to check the tire characteristics.
// Inside gnuplot use the command load 'filename'
std::string filename = dirname + "/365_80R20_" + GetName() + ".gpl";
WritePlots(filename, "365/80R20 152K");
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WVP_TMeasyTire::AddVisualizationAssets(VisualizationType vis) {
if (vis == VisualizationType::MESH) {
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(vehicle::GetDataFile(m_meshFile), false, false);
m_trimesh_shape = std::make_shared<ChTriangleMeshShape>();
m_trimesh_shape->SetMesh(trimesh);
m_trimesh_shape->SetName(m_meshName);
m_wheel->AddAsset(m_trimesh_shape);
} else {
ChTMeasyTire::AddVisualizationAssets(vis);
}
}
void WVP_TMeasyTire::RemoveVisualizationAssets() {
ChTMeasyTire::RemoveVisualizationAssets();
// Make sure we only remove the assets added by WVP_FialaTire::AddVisualizationAssets.
// This is important for the ChTire object because a wheel may add its own assets
// to the same body (the spindle/wheel).
auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_trimesh_shape);
if (it != m_wheel->GetAssets().end())
m_wheel->GetAssets().erase(it);
}
} // end namespace wvp
} // end namespace vehicle
} // end namespace chrono
<commit_msg>Fine tuning of longitudinal tire parameters.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Rainer Gericke
// =============================================================================
//
// WVP TMeasy tire subsystem
//
// =============================================================================
#include <algorithm>
#include <cmath>
#include "chrono_models/vehicle/wvp/WVP_TMeasyTire.h"
#include "chrono_vehicle/ChVehicleModelData.h"
namespace chrono {
namespace vehicle {
namespace wvp {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const std::string WVP_TMeasyTire::m_meshName = "hmmwv_tire_POV_geom";
const std::string WVP_TMeasyTire::m_meshFile = "hmmwv/hmmwv_tire.obj";
const double WVP_TMeasyTire::m_mass = 71.1;
const ChVector<> WVP_TMeasyTire::m_inertia(9.62, 16.84, 9.62);
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
WVP_TMeasyTire::WVP_TMeasyTire(const std::string& name) : ChTMeasyTire(name) {
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WVP_TMeasyTire::SetTMeasyParams() {
// Set Handling Charecteristics as close as possible to Pacejka89 model data
m_TMeasyCoeff.pn = GetTireMaxLoad(152)/2.0;
m_TMeasyCoeff.mu_0 = 0.8;
// Set nonlinear vertical stiffness
std::vector<double> disp, force;
disp.push_back(0.01); force.push_back(3276.0);
disp.push_back(0.02); force.push_back(6729.0);
disp.push_back(0.03); force.push_back(10361.0);
disp.push_back(0.04); force.push_back(14171.0);
disp.push_back(0.05); force.push_back(18159.0);
disp.push_back(0.06); force.push_back(22325.0);
disp.push_back(0.07); force.push_back(26670.0);
disp.push_back(0.08); force.push_back(31192.0);
disp.push_back(0.09); force.push_back(35893.0);
disp.push_back(0.10); force.push_back(40772.0);
SetVerticalStiffness(disp,force);
m_width = 0.372;
m_unloaded_radius = 1.096 / 2.0;
m_rolling_resistance = 0.015;
m_TMeasyCoeff.mu_0 = 0.8;
// Simple damping model from single mass oscilator
double xi = 0.05; // tire damping ratio
double C1 = 1000.0*sqrt(pow(m_a1,2)+4.0*m_a2*m_TMeasyCoeff.pn/1000);
double C2 = 1000.0*sqrt(pow(m_a1,2)+8.0*m_a2*m_TMeasyCoeff.pn/1000);
double CZM = (C1 + C2) / 2.0;
m_TMeasyCoeff.dz = 2.0 * xi * sqrt(CZM * WVP_TMeasyTire::m_mass);
m_TMeasyCoeff.dfx0_pn = 215.013101;
m_TMeasyCoeff.sxm_pn = 0.139216;
m_TMeasyCoeff.fxm_pn = 13.832671;
m_TMeasyCoeff.sxs_pn = 0.500000;
m_TMeasyCoeff.fxs_pn = 12.387002;
m_TMeasyCoeff.dfx0_p2n = 615.071218;
m_TMeasyCoeff.sxm_p2n = 0.112538;
m_TMeasyCoeff.fxm_p2n = 24.576280;
m_TMeasyCoeff.sxs_p2n = 0.800000;
m_TMeasyCoeff.fxs_p2n = 22.079064;
m_TMeasyCoeff.dfy0_pn = 168.715739;
m_TMeasyCoeff.sym_pn = 0.258411;
m_TMeasyCoeff.fym_pn = 13.038949;
m_TMeasyCoeff.sys_pn = 0.800000;
m_TMeasyCoeff.fys_pn = 12.387002;
m_TMeasyCoeff.dfy0_p2n = 320.100587;
m_TMeasyCoeff.sym_p2n = 0.238826;
m_TMeasyCoeff.fym_p2n = 23.241121;
m_TMeasyCoeff.sys_p2n = 1.000000;
m_TMeasyCoeff.fys_p2n = 22.079064;
m_TMeasyCoeff.nto0_pn = 0.160000;
m_TMeasyCoeff.synto0_pn = 0.180000;
m_TMeasyCoeff.syntoE_pn = 0.480000;
m_TMeasyCoeff.nto0_p2n = 0.170000;
m_TMeasyCoeff.synto0_p2n = 0.160000;
m_TMeasyCoeff.syntoE_p2n = 0.500000;
if(CheckParameters()) {
std::cout << "Parameter Set seems to be ok." << std::endl;
} else {
std::cout << "Badly formed parameter set." << std::endl;
}
if(GetName().compare("FL") == 0) {
GenerateCharacteristicPlots("../");
}
}
void WVP_TMeasyTire::GenerateCharacteristicPlots(const std::string& dirname) {
// Write a plot file (gnuplot) to check the tire characteristics.
// Inside gnuplot use the command load 'filename'
std::string filename = dirname + "/365_80R20_" + GetName() + ".gpl";
WritePlots(filename, "365/80R20 152K");
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WVP_TMeasyTire::AddVisualizationAssets(VisualizationType vis) {
if (vis == VisualizationType::MESH) {
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(vehicle::GetDataFile(m_meshFile), false, false);
m_trimesh_shape = std::make_shared<ChTriangleMeshShape>();
m_trimesh_shape->SetMesh(trimesh);
m_trimesh_shape->SetName(m_meshName);
m_wheel->AddAsset(m_trimesh_shape);
} else {
ChTMeasyTire::AddVisualizationAssets(vis);
}
}
void WVP_TMeasyTire::RemoveVisualizationAssets() {
ChTMeasyTire::RemoveVisualizationAssets();
// Make sure we only remove the assets added by WVP_FialaTire::AddVisualizationAssets.
// This is important for the ChTire object because a wheel may add its own assets
// to the same body (the spindle/wheel).
auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_trimesh_shape);
if (it != m_wheel->GetAssets().end())
m_wheel->GetAssets().erase(it);
}
} // end namespace wvp
} // end namespace vehicle
} // end namespace chrono
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: excimp8.hxx,v $
*
* $Revision: 1.62 $
*
* last change: $Author: hr $ $Date: 2005-09-28 11:56:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXCIMP8_HXX
#define _EXCIMP8_HXX
#include <string.h>
#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif
#ifndef _EXCSCEN_HXX
#include "excscen.hxx"
#endif
#ifndef _EXCDEFS_HXX
#include "excdefs.hxx"
#endif
#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
class SotStorage;
class ScBaseCell;
class ScRangeList;
class ScDBData;
class ScfSimpleProgressBar;
class XclImpStream;
class ImportExcel8 : public ImportExcel
{
protected:
ExcScenarioList aScenList;
BOOL bObjSection;
BOOL bHasBasic;
void RecString( void ); // 0x07
void Calccount( void ); // 0x0C
void Precision( void ); // 0x0E
void Delta( void ); // 0x10
void Iteration( void ); // 0x11
void Note( void ); // 0x1C
void WinProtection( void ); // 0x19
void Cont( void ); // 0x3C
void Obj( void ); // 0x5D
void Boundsheet( void ); // 0x85
void FilterMode( void ); // 0x9B
void AutoFilterInfo( void ); // 0x9D
void AutoFilter( void ); // 0x9E
void Scenman( void ); // 0xAE
void Scenario( void ); // 0xAF
void ReadBasic( void ); // 0xD3
void Cellmerging( void ); // 0xE5 geraten...
void Msodrawinggroup( void ); // 0xEB
void Msodrawing( void ); // 0xEC
void Msodrawingselection( void ); // 0xED
void Labelsst( void ); // 0xFD
void Txo( void ); // 0x01B6
void Hlink( void ); // 0x01B8
void Codename( BOOL bWBGlobals ); // 0x01BA
void Dimensions( void ); // 0x0200
void EndSheet( void );
virtual void EndAllChartObjects( void ); // -> excobj.cxx
virtual void PostDocLoad( void );
/** Post processes all Escher objects, and inserts them into the document. */
void ApplyEscherObjects();
public:
ImportExcel8( XclImpRootData& rImpData );
virtual ~ImportExcel8( void );
virtual FltError Read( void );
};
//___________________________________________________________________
// classes AutoFilterData, AutoFilterBuffer
class XclImpAutoFilterData : private ExcRoot
{
private:
ScDBData* pCurrDBData;
ScQueryParam aParam;
SCSIZE nFirstEmpty;
BOOL bActive;
BOOL bHasConflict;
BOOL bCriteria;
BOOL bAutoOrAdvanced;
ScRange aCriteriaRange;
String aFilterName;
void CreateFromDouble( String& rStr, double fVal );
void SetCellAttribs();
void InsertQueryParam();
void AmendAFName(const BOOL bUseUnNamed);
protected:
public:
XclImpAutoFilterData(
RootData* pRoot,
const ScRange& rRange,
const String& rName );
inline bool IsActive() const { return bActive; }
inline SCTAB Tab() const { return aParam.nTab; }
inline SCCOL StartCol() const { return aParam.nCol1; }
inline SCROW StartRow() const { return aParam.nRow1; }
inline SCCOL EndCol() const { return aParam.nCol2; }
inline SCROW EndRow() const { return aParam.nRow2; }
void ReadAutoFilter( XclImpStream& rStrm );
inline void Activate() { bActive = TRUE; }
void SetAdvancedRange( const ScRange* pRange );
void SetExtractPos( const ScAddress& rAddr );
inline void SetAutoOrAdvanced() { bAutoOrAdvanced = TRUE; }
void Apply( const BOOL bUseUnNamed = FALSE );
void CreateScDBData( const BOOL bUseUnNamed );
void EnableRemoveFilter();
};
class XclImpAutoFilterBuffer : private List
{
private:
UINT16 nAFActiveCount;
inline XclImpAutoFilterData* _First() { return (XclImpAutoFilterData*) List::First(); }
inline XclImpAutoFilterData* _Next() { return (XclImpAutoFilterData*) List::Next(); }
inline void Append( XclImpAutoFilterData* pData )
{ List::Insert( pData, LIST_APPEND ); }
protected:
public:
XclImpAutoFilterBuffer();
virtual ~XclImpAutoFilterBuffer();
void Insert( RootData* pRoot, const ScRange& rRange,
const String& rName );
void AddAdvancedRange( const ScRange& rRange );
void AddExtractPos( const ScRange& rRange );
void Apply();
XclImpAutoFilterData* GetByTab( SCTAB nTab );
inline void IncrementActiveAF() { nAFActiveCount++; }
inline BOOL UseUnNamed() { return nAFActiveCount == 1; }
};
#endif
<commit_msg>INTEGRATION: CWS dr43 (1.62.24); FILE MERGED 2005/11/17 09:57:17 dr 1.62.24.1: #i55192# first set row height and flags, then insert drawing objects<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: excimp8.hxx,v $
*
* $Revision: 1.63 $
*
* last change: $Author: rt $ $Date: 2006-01-13 16:59:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXCIMP8_HXX
#define _EXCIMP8_HXX
#include <string.h>
#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif
#ifndef _EXCSCEN_HXX
#include "excscen.hxx"
#endif
#ifndef _EXCDEFS_HXX
#include "excdefs.hxx"
#endif
#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
class SotStorage;
class ScBaseCell;
class ScRangeList;
class ScDBData;
class ScfSimpleProgressBar;
class XclImpStream;
class ImportExcel8 : public ImportExcel
{
protected:
ExcScenarioList aScenList;
BOOL bObjSection;
BOOL bHasBasic;
void RecString( void ); // 0x07
void Calccount( void ); // 0x0C
void Precision( void ); // 0x0E
void Delta( void ); // 0x10
void Iteration( void ); // 0x11
void Note( void ); // 0x1C
void WinProtection( void ); // 0x19
void Cont( void ); // 0x3C
void Obj( void ); // 0x5D
void Boundsheet( void ); // 0x85
void FilterMode( void ); // 0x9B
void AutoFilterInfo( void ); // 0x9D
void AutoFilter( void ); // 0x9E
void Scenman( void ); // 0xAE
void Scenario( void ); // 0xAF
void ReadBasic( void ); // 0xD3
void Cellmerging( void ); // 0xE5 geraten...
void Msodrawinggroup( void ); // 0xEB
void Msodrawing( void ); // 0xEC
void Msodrawingselection( void ); // 0xED
void Labelsst( void ); // 0xFD
void Txo( void ); // 0x01B6
void Hlink( void ); // 0x01B8
void Codename( BOOL bWBGlobals ); // 0x01BA
void Dimensions( void ); // 0x0200
void EndSheet( void );
virtual void EndAllChartObjects( void ); // -> excobj.cxx
virtual void PostDocLoad( void );
public:
ImportExcel8( XclImpRootData& rImpData );
virtual ~ImportExcel8( void );
virtual FltError Read( void );
};
//___________________________________________________________________
// classes AutoFilterData, AutoFilterBuffer
class XclImpAutoFilterData : private ExcRoot
{
private:
ScDBData* pCurrDBData;
ScQueryParam aParam;
SCSIZE nFirstEmpty;
BOOL bActive;
BOOL bHasConflict;
BOOL bCriteria;
BOOL bAutoOrAdvanced;
ScRange aCriteriaRange;
String aFilterName;
void CreateFromDouble( String& rStr, double fVal );
void SetCellAttribs();
void InsertQueryParam();
void AmendAFName(const BOOL bUseUnNamed);
protected:
public:
XclImpAutoFilterData(
RootData* pRoot,
const ScRange& rRange,
const String& rName );
inline bool IsActive() const { return bActive; }
inline SCTAB Tab() const { return aParam.nTab; }
inline SCCOL StartCol() const { return aParam.nCol1; }
inline SCROW StartRow() const { return aParam.nRow1; }
inline SCCOL EndCol() const { return aParam.nCol2; }
inline SCROW EndRow() const { return aParam.nRow2; }
void ReadAutoFilter( XclImpStream& rStrm );
inline void Activate() { bActive = TRUE; }
void SetAdvancedRange( const ScRange* pRange );
void SetExtractPos( const ScAddress& rAddr );
inline void SetAutoOrAdvanced() { bAutoOrAdvanced = TRUE; }
void Apply( const BOOL bUseUnNamed = FALSE );
void CreateScDBData( const BOOL bUseUnNamed );
void EnableRemoveFilter();
};
class XclImpAutoFilterBuffer : private List
{
private:
UINT16 nAFActiveCount;
inline XclImpAutoFilterData* _First() { return (XclImpAutoFilterData*) List::First(); }
inline XclImpAutoFilterData* _Next() { return (XclImpAutoFilterData*) List::Next(); }
inline void Append( XclImpAutoFilterData* pData )
{ List::Insert( pData, LIST_APPEND ); }
protected:
public:
XclImpAutoFilterBuffer();
virtual ~XclImpAutoFilterBuffer();
void Insert( RootData* pRoot, const ScRange& rRange,
const String& rName );
void AddAdvancedRange( const ScRange& rRange );
void AddExtractPos( const ScRange& rRange );
void Apply();
XclImpAutoFilterData* GetByTab( SCTAB nTab );
inline void IncrementActiveAF() { nAFActiveCount++; }
inline BOOL UseUnNamed() { return nAFActiveCount == 1; }
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>translated German comments<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: csvtablebox.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:33:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef _SC_CSVTABLEBOX_HXX
#define _SC_CSVTABLEBOX_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _SC_CSVRULER_HXX
#include "csvruler.hxx"
#endif
#ifndef _SC_CSVGRID_HXX
#include "csvgrid.hxx"
#endif
class ListBox;
class ScAsciiOptions;
/* ============================================================================
Position: Positions between the characters (the dots in the ruler).
Character: The characters (the range from one position to the next).
Split: Positions which contain a split to divide characters into groups (columns).
Column: The range between two splits.
============================================================================ */
/** The control in the CSV import dialog that contains a ruler and a data grid
to visualize and modify the current import settings. */
class SC_DLLPUBLIC ScCsvTableBox : public ScCsvControl
{
private:
ScCsvLayoutData maData; /// Current layout data of the controls.
ScCsvRuler maRuler; /// The ruler for fixed width mode.
ScCsvGrid maGrid; /// Calc-like data table for fixed width mode.
ScrollBar maHScroll; /// Horizontal scroll bar.
ScrollBar maVScroll; /// Vertical scroll bar.
ScrollBarBox maScrollBox; /// For the bottom right edge.
Link maUpdateTextHdl; /// Updates all cell texts.
Link maColTypeHdl; /// Handler for exporting the column type.
ScCsvColStateVec maFixColStates; /// Column states in fixed width mode.
ScCsvColStateVec maSepColStates; /// Column states in separators mode.
sal_Int32 mnFixedWidth; /// Cached total width for fixed width mode.
bool mbFixedMode; /// false = Separators, true = Fixed width.
// ------------------------------------------------------------------------
public:
explicit ScCsvTableBox( Window* pParent );
explicit ScCsvTableBox( Window* pParent, const ResId& rResId );
// common table box handling ----------------------------------------------
public:
/** Sets the control to separators mode. */
void SetSeparatorsMode();
/** Sets the control to fixed width mode. */
void SetFixedWidthMode();
private:
/** Initialisation on construction. */
SC_DLLPRIVATE void Init();
/** Initializes the children controls (pos/size, scroll bars, ...). */
SC_DLLPRIVATE void InitControls();
/** Initializes size and position data of horizontal scrollbar. */
SC_DLLPRIVATE void InitHScrollBar();
/** Initializes size and position data of vertical scrollbar. */
SC_DLLPRIVATE void InitVScrollBar();
/** Calculates and sets valid position offset nearest to nPos. */
SC_DLLPRIVATE inline void ImplSetPosOffset( sal_Int32 nPos )
{ maData.mnPosOffset = Max( Min( nPos, GetMaxPosOffset() ), 0L ); }
/** Calculates and sets valid line offset nearest to nLine. */
SC_DLLPRIVATE inline void ImplSetLineOffset( sal_Int32 nLine )
{ maData.mnLineOffset = Max( Min( nLine, GetMaxLineOffset() ), 0L ); }
/** Moves controls (not cursors!) so that nPos becomes visible. */
SC_DLLPRIVATE void MakePosVisible( sal_Int32 nPos );
// cell contents ----------------------------------------------------------
public:
/** Fills all cells of all lines with the passed texts (Unicode strings). */
void SetUniStrings(
const String* pTextLines, const String& rSepChars,
sal_Unicode cTextSep, bool bMergeSep );
/** Fills all cells of all lines with the passed texts (ByteStrings). */
void SetByteStrings(
const ByteString* pLineTexts, CharSet eCharSet,
const String& rSepChars, sal_Unicode cTextSep, bool bMergeSep );
// column settings --------------------------------------------------------
public:
/** Reads UI strings for data types from the list box. */
void InitTypes( const ListBox& rListBox );
/** Returns the data type of the selected columns. */
inline sal_Int32 GetSelColumnType() const { return maGrid.GetSelColumnType(); }
/** Fills the options object with current column data. */
void FillColumnData( ScAsciiOptions& rOptions ) const;
// event handling ---------------------------------------------------------
public:
/** Sets a new handler for "update cell texts" requests. */
inline void SetUpdateTextHdl( const Link& rHdl ) { maUpdateTextHdl = rHdl; }
/** Returns the handler for "update cell texts" requests. */
inline const Link& GetUpdateTextHdl() const { return maUpdateTextHdl; }
/** Sets a new handler for "column selection changed" events. */
inline void SetColTypeHdl( const Link& rHdl ) { maColTypeHdl = rHdl; }
/** Returns the handler for "column selection changed" events. */
inline const Link& GetColTypeHdl() const { return maColTypeHdl; }
protected:
virtual void Resize();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
private:
SC_DLLPRIVATE DECL_LINK( CsvCmdHdl, ScCsvControl* );
SC_DLLPRIVATE DECL_LINK( ScrollHdl, ScrollBar* );
SC_DLLPRIVATE DECL_LINK( ScrollEndHdl, ScrollBar* );
// accessibility ----------------------------------------------------------
public:
/** Creates and returns the accessible object of this control. */
virtual XAccessibleRef CreateAccessible();
protected:
/** Creates a new accessible object. */
virtual ScAccessibleCsvControl* ImplCreateAccessible();
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.344); FILE MERGED 2005/09/05 15:05:14 rt 1.5.344.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: csvtablebox.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:18:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// ============================================================================
#ifndef _SC_CSVTABLEBOX_HXX
#define _SC_CSVTABLEBOX_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _SC_CSVRULER_HXX
#include "csvruler.hxx"
#endif
#ifndef _SC_CSVGRID_HXX
#include "csvgrid.hxx"
#endif
class ListBox;
class ScAsciiOptions;
/* ============================================================================
Position: Positions between the characters (the dots in the ruler).
Character: The characters (the range from one position to the next).
Split: Positions which contain a split to divide characters into groups (columns).
Column: The range between two splits.
============================================================================ */
/** The control in the CSV import dialog that contains a ruler and a data grid
to visualize and modify the current import settings. */
class SC_DLLPUBLIC ScCsvTableBox : public ScCsvControl
{
private:
ScCsvLayoutData maData; /// Current layout data of the controls.
ScCsvRuler maRuler; /// The ruler for fixed width mode.
ScCsvGrid maGrid; /// Calc-like data table for fixed width mode.
ScrollBar maHScroll; /// Horizontal scroll bar.
ScrollBar maVScroll; /// Vertical scroll bar.
ScrollBarBox maScrollBox; /// For the bottom right edge.
Link maUpdateTextHdl; /// Updates all cell texts.
Link maColTypeHdl; /// Handler for exporting the column type.
ScCsvColStateVec maFixColStates; /// Column states in fixed width mode.
ScCsvColStateVec maSepColStates; /// Column states in separators mode.
sal_Int32 mnFixedWidth; /// Cached total width for fixed width mode.
bool mbFixedMode; /// false = Separators, true = Fixed width.
// ------------------------------------------------------------------------
public:
explicit ScCsvTableBox( Window* pParent );
explicit ScCsvTableBox( Window* pParent, const ResId& rResId );
// common table box handling ----------------------------------------------
public:
/** Sets the control to separators mode. */
void SetSeparatorsMode();
/** Sets the control to fixed width mode. */
void SetFixedWidthMode();
private:
/** Initialisation on construction. */
SC_DLLPRIVATE void Init();
/** Initializes the children controls (pos/size, scroll bars, ...). */
SC_DLLPRIVATE void InitControls();
/** Initializes size and position data of horizontal scrollbar. */
SC_DLLPRIVATE void InitHScrollBar();
/** Initializes size and position data of vertical scrollbar. */
SC_DLLPRIVATE void InitVScrollBar();
/** Calculates and sets valid position offset nearest to nPos. */
SC_DLLPRIVATE inline void ImplSetPosOffset( sal_Int32 nPos )
{ maData.mnPosOffset = Max( Min( nPos, GetMaxPosOffset() ), 0L ); }
/** Calculates and sets valid line offset nearest to nLine. */
SC_DLLPRIVATE inline void ImplSetLineOffset( sal_Int32 nLine )
{ maData.mnLineOffset = Max( Min( nLine, GetMaxLineOffset() ), 0L ); }
/** Moves controls (not cursors!) so that nPos becomes visible. */
SC_DLLPRIVATE void MakePosVisible( sal_Int32 nPos );
// cell contents ----------------------------------------------------------
public:
/** Fills all cells of all lines with the passed texts (Unicode strings). */
void SetUniStrings(
const String* pTextLines, const String& rSepChars,
sal_Unicode cTextSep, bool bMergeSep );
/** Fills all cells of all lines with the passed texts (ByteStrings). */
void SetByteStrings(
const ByteString* pLineTexts, CharSet eCharSet,
const String& rSepChars, sal_Unicode cTextSep, bool bMergeSep );
// column settings --------------------------------------------------------
public:
/** Reads UI strings for data types from the list box. */
void InitTypes( const ListBox& rListBox );
/** Returns the data type of the selected columns. */
inline sal_Int32 GetSelColumnType() const { return maGrid.GetSelColumnType(); }
/** Fills the options object with current column data. */
void FillColumnData( ScAsciiOptions& rOptions ) const;
// event handling ---------------------------------------------------------
public:
/** Sets a new handler for "update cell texts" requests. */
inline void SetUpdateTextHdl( const Link& rHdl ) { maUpdateTextHdl = rHdl; }
/** Returns the handler for "update cell texts" requests. */
inline const Link& GetUpdateTextHdl() const { return maUpdateTextHdl; }
/** Sets a new handler for "column selection changed" events. */
inline void SetColTypeHdl( const Link& rHdl ) { maColTypeHdl = rHdl; }
/** Returns the handler for "column selection changed" events. */
inline const Link& GetColTypeHdl() const { return maColTypeHdl; }
protected:
virtual void Resize();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
private:
SC_DLLPRIVATE DECL_LINK( CsvCmdHdl, ScCsvControl* );
SC_DLLPRIVATE DECL_LINK( ScrollHdl, ScrollBar* );
SC_DLLPRIVATE DECL_LINK( ScrollEndHdl, ScrollBar* );
// accessibility ----------------------------------------------------------
public:
/** Creates and returns the accessible object of this control. */
virtual XAccessibleRef CreateAccessible();
protected:
/** Creates a new accessible object. */
virtual ScAccessibleCsvControl* ImplCreateAccessible();
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>#include <TFile.h>
#include <TH1.h>
#include <TH2.h>
#include "AliGeomManager.h"
#include "AliITSDetTypeRec.h"
#include "AliITSInitGeometry.h"
#include "AliITSMeanVertexer.h"
#include "AliITSLoader.h"
#include "AliLog.h"
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliRawReaderRoot.h"
#include "AliRunLoader.h"
#include "AliITSVertexer3D.h"
#include "AliITSVertexer3DTapan.h"
#include "AliESDVertex.h"
#include "AliMeanVertex.h"
#include "AliMultiplicity.h"
ClassImp(AliITSMeanVertexer)
///////////////////////////////////////////////////////////////////////
// //
// Class to compute vertex position using SPD local reconstruction //
// An average vertex position using all the events //
// is built and saved //
// Individual vertices can be optionally stored //
// Origin: M.Masera (masera@to.infn.it) //
// Usage:
// AliITSMeanVertexer mv("RawDataFileName");
// mv.SetGeometryFileName("FileWithGeometry.root"); // def. geometry.root
// .... optional setters ....
// mv.Reconstruct(); // SPD local reconstruction
// mv.DoVertices();
// Resulting AliMeanVertex object is stored in a file named fMVFileName
///////////////////////////////////////////////////////////////////////
/* $Id$ */
//______________________________________________________________________
AliITSMeanVertexer::AliITSMeanVertexer():TObject(),
fDetTypeRec(NULL),
fVertexXY(NULL),
fVertexZ(NULL),
fNoEventsContr(0),
fTotTracklets(0.),
fAverTracklets(0.),
fTotTrackletsSq(0.),
fSigmaOnAverTracks(0.),
fFilterOnContributors(0),
fFilterOnTracklets(0)
{
// Default Constructor
for(Int_t i=0;i<3;i++){
fWeighPosSum[i] = 0.;
fWeighSigSum[i] = 0.;
fAverPosSum[i] = 0.;
fWeighPos[i] = 0.;
fWeighSig[i] = 0.;
fAverPos[i] = 0.;
for(Int_t j=0; j<3;j++)fAverPosSq[i][j] = 0.;
for(Int_t j=0; j<3;j++)fAverPosSqSum[i][j] = 0.;
}
// Histograms initialization
const Float_t xLimit = 5.0, yLimit = 5.0, zLimit = 50.0;
const Float_t xDelta = 0.02, yDelta = 0.02, zDelta = 0.2;
fVertexXY = new TH2F("VertexXY","Vertex Diamond (Y vs X)",
2*(Int_t)(xLimit/xDelta),-xLimit,xLimit,
2*(Int_t)(yLimit/yDelta),-yLimit,yLimit);
fVertexXY->SetXTitle("X , cm");
fVertexXY->SetYTitle("Y , cm");
fVertexXY->SetOption("colz");
fVertexZ = new TH1F("VertexZ"," Longitudinal Vertex Profile",
2*(Int_t)(zLimit/zDelta),-zLimit,zLimit);
fVertexZ->SetXTitle("Z , cm");
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Init() {
// Initialize filters
// Initialize geometry
// Initialize ITS classes
AliGeomManager::LoadGeometry();
if (!AliGeomManager::ApplyAlignObjsFromCDB("ITS")) return kFALSE;
AliITSInitGeometry initgeom;
AliITSgeom *geom = initgeom.CreateAliITSgeom();
if (!geom) return kFALSE;
printf("Geometry name: %s \n",(initgeom.GetGeometryName()).Data());
fDetTypeRec = new AliITSDetTypeRec();
fDetTypeRec->SetLoadOnlySPDCalib(kTRUE);
fDetTypeRec->SetITSgeom(geom);
fDetTypeRec->SetDefaults();
fDetTypeRec->SetDefaultClusterFindersV2(kTRUE);
// Initialize filter values to their defaults
SetFilterOnContributors();
SetFilterOnTracklets();
return kTRUE;
}
//______________________________________________________________________
AliITSMeanVertexer::~AliITSMeanVertexer() {
// Destructor
delete fDetTypeRec;
delete fVertexXY;
delete fVertexZ;
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Reconstruct(AliRawReader *rawReader, Bool_t mode){
// Performs SPD local reconstruction
// and vertex finding
// returns true in case a vertex is found
// Run SPD cluster finder
TTree* clustersTree = new TTree("TreeR", "Reconstructed Points Container"); //make a tree
fDetTypeRec->DigitsToRecPoints(rawReader,clustersTree,"SPD");
Bool_t vtxOK = kFALSE;
AliESDVertex *vtx = NULL;
// Run Tapan's vertex-finder
if (!mode) {
AliITSVertexer3DTapan *vertexer1 = new AliITSVertexer3DTapan(1000);
vtx = vertexer1->FindVertexForCurrentEvent(clustersTree);
delete vertexer1;
if (TMath::Abs(vtx->GetChi2()) < 0.1) vtxOK = kTRUE;
}
else {
// Run standard vertexer3d
AliITSVertexer3D *vertexer2 = new AliITSVertexer3D();
vtx = vertexer2->FindVertexForCurrentEvent(clustersTree);
AliMultiplicity *mult = vertexer2->GetMultiplicity();
delete vertexer2;
if(Filter(vtx,mult)) vtxOK = kTRUE;
}
delete clustersTree;
if (vtxOK) AddToMean(vtx);
if (vtx) delete vtx;
return vtxOK;
}
//______________________________________________________________________
void AliITSMeanVertexer::WriteVertices(const char *filename){
// Compute mean vertex and
// store it along with the histograms
// in a file
TFile fmv(filename,"update");
if(ComputeMean()){
Double_t cov[6];
cov[0] = fAverPosSq[0][0]; // variance x
cov[1] = fAverPosSq[0][1]; // cov xy
cov[2] = fAverPosSq[1][1]; // variance y
cov[3] = fAverPosSq[0][2]; // cov xz
cov[4] = fAverPosSq[1][2]; // cov yz
cov[5] = fAverPosSq[2][2]; // variance z
AliMeanVertex mv(fWeighPos,fWeighSig,cov,fNoEventsContr,fTotTracklets,fAverTracklets,fSigmaOnAverTracks);
mv.SetTitle("Mean Vertex");
mv.SetName("MeanVertex");
AliDebug(1,Form("Contrib av. trk = %10.2f ",mv.GetAverageNumbOfTracklets()));
AliDebug(1,Form("Sigma %10.4f ",mv.GetSigmaOnAvNumbOfTracks()));
// we have to add chi2 here
AliESDVertex vtx(fWeighPos,cov,0,TMath::Nint(fAverTracklets),"MeanVertexPos");
mv.Write(mv.GetName(),TObject::kOverwrite);
vtx.Write(vtx.GetName(),TObject::kOverwrite);
}
else {
AliError(Form("Evaluation of mean vertex not possible. Number of used events = %d",fNoEventsContr));
}
fVertexXY->Write(fVertexXY->GetName(),TObject::kOverwrite);
fVertexZ->Write(fVertexZ->GetName(),TObject::kOverwrite);
fmv.Close();
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Filter(AliESDVertex *vert,AliMultiplicity *mult){
// Apply selection criteria to events
Bool_t status = kFALSE;
if(!vert || !mult)return status;
// Remove vertices reconstructed with vertexerZ
if(strcmp(vert->GetName(),"SPDVertexZ") == 0) return status;
Int_t ncontr = vert->GetNContributors();
Int_t ntracklets = mult->GetNumberOfTracklets();
AliDebug(1,Form("Number of contributors = %d",ncontr));
AliDebug(1,Form("Number of tracklets = %d",ntracklets));
if(ncontr>fFilterOnContributors && ntracklets > fFilterOnTracklets) status = kTRUE;
fTotTracklets += ntracklets;
fTotTrackletsSq += ntracklets*ntracklets;
return status;
}
//______________________________________________________________________
void AliITSMeanVertexer::AddToMean(AliESDVertex *vert){
// update mean vertex
Double_t currentPos[3],currentSigma[3];
vert->GetXYZ(currentPos);
vert->GetSigmaXYZ(currentSigma);
Bool_t goon = kTRUE;
for(Int_t i=0;i<3;i++)if(currentSigma[i] == 0.)goon = kFALSE;
if(!goon)return;
for(Int_t i=0;i<3;i++){
fWeighPosSum[i]+=currentPos[i]/currentSigma[i]/currentSigma[i];
fWeighSigSum[i]+=1./currentSigma[i]/currentSigma[i];
fAverPosSum[i]+=currentPos[i];
}
for(Int_t i=0;i<3;i++){
for(Int_t j=i;j<3;j++){
fAverPosSqSum[i][j] += currentPos[i] * currentPos[j];
}
}
fVertexXY->Fill(currentPos[0],currentPos[1]);
fVertexZ->Fill(currentPos[2]);
fNoEventsContr++;
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::ComputeMean(){
// compute mean vertex
if(fNoEventsContr < 2) return kFALSE;
Double_t nevents = fNoEventsContr;
for(Int_t i=0;i<3;i++){
fWeighPos[i] = fWeighPosSum[i]/fWeighSigSum[i];
fWeighSig[i] = 1./TMath::Sqrt(fWeighSigSum[i]);
fAverPos[i] = fAverPosSum[i]/nevents;
}
for(Int_t i=0;i<3;i++){
for(Int_t j=i;j<3;j++){
fAverPosSq[i][j] = fAverPosSqSum[i][j]/(nevents -1.);
fAverPosSq[i][j] -= nevents/(nevents -1.)*fAverPos[i]*fAverPos[j];
}
}
fAverTracklets = fTotTracklets/nevents;
fSigmaOnAverTracks = fTotTrackletsSq/(nevents - 1);
fSigmaOnAverTracks -= nevents/(nevents -1.)*fAverTracklets*fAverTracklets;
fSigmaOnAverTracks = TMath::Sqrt(fSigmaOnAverTracks);
return kTRUE;
}
<commit_msg>Fix to the updated interface of the vertexer (Thanks Annalisa for spotting it).<commit_after>#include <TFile.h>
#include <TH1.h>
#include <TH2.h>
#include "AliGeomManager.h"
#include "AliITSDetTypeRec.h"
#include "AliITSInitGeometry.h"
#include "AliITSMeanVertexer.h"
#include "AliITSLoader.h"
#include "AliLog.h"
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliRawReaderRoot.h"
#include "AliRunLoader.h"
#include "AliITSVertexer3D.h"
#include "AliITSVertexer3DTapan.h"
#include "AliESDVertex.h"
#include "AliMeanVertex.h"
#include "AliMultiplicity.h"
ClassImp(AliITSMeanVertexer)
///////////////////////////////////////////////////////////////////////
// //
// Class to compute vertex position using SPD local reconstruction //
// An average vertex position using all the events //
// is built and saved //
// Individual vertices can be optionally stored //
// Origin: M.Masera (masera@to.infn.it) //
// Usage:
// AliITSMeanVertexer mv("RawDataFileName");
// mv.SetGeometryFileName("FileWithGeometry.root"); // def. geometry.root
// .... optional setters ....
// mv.Reconstruct(); // SPD local reconstruction
// mv.DoVertices();
// Resulting AliMeanVertex object is stored in a file named fMVFileName
///////////////////////////////////////////////////////////////////////
/* $Id$ */
//______________________________________________________________________
AliITSMeanVertexer::AliITSMeanVertexer():TObject(),
fDetTypeRec(NULL),
fVertexXY(NULL),
fVertexZ(NULL),
fNoEventsContr(0),
fTotTracklets(0.),
fAverTracklets(0.),
fTotTrackletsSq(0.),
fSigmaOnAverTracks(0.),
fFilterOnContributors(0),
fFilterOnTracklets(0)
{
// Default Constructor
for(Int_t i=0;i<3;i++){
fWeighPosSum[i] = 0.;
fWeighSigSum[i] = 0.;
fAverPosSum[i] = 0.;
fWeighPos[i] = 0.;
fWeighSig[i] = 0.;
fAverPos[i] = 0.;
for(Int_t j=0; j<3;j++)fAverPosSq[i][j] = 0.;
for(Int_t j=0; j<3;j++)fAverPosSqSum[i][j] = 0.;
}
// Histograms initialization
const Float_t xLimit = 5.0, yLimit = 5.0, zLimit = 50.0;
const Float_t xDelta = 0.02, yDelta = 0.02, zDelta = 0.2;
fVertexXY = new TH2F("VertexXY","Vertex Diamond (Y vs X)",
2*(Int_t)(xLimit/xDelta),-xLimit,xLimit,
2*(Int_t)(yLimit/yDelta),-yLimit,yLimit);
fVertexXY->SetXTitle("X , cm");
fVertexXY->SetYTitle("Y , cm");
fVertexXY->SetOption("colz");
fVertexZ = new TH1F("VertexZ"," Longitudinal Vertex Profile",
2*(Int_t)(zLimit/zDelta),-zLimit,zLimit);
fVertexZ->SetXTitle("Z , cm");
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Init() {
// Initialize filters
// Initialize geometry
// Initialize ITS classes
AliGeomManager::LoadGeometry();
if (!AliGeomManager::ApplyAlignObjsFromCDB("ITS")) return kFALSE;
AliITSInitGeometry initgeom;
AliITSgeom *geom = initgeom.CreateAliITSgeom();
if (!geom) return kFALSE;
printf("Geometry name: %s \n",(initgeom.GetGeometryName()).Data());
fDetTypeRec = new AliITSDetTypeRec();
fDetTypeRec->SetLoadOnlySPDCalib(kTRUE);
fDetTypeRec->SetITSgeom(geom);
fDetTypeRec->SetDefaults();
fDetTypeRec->SetDefaultClusterFindersV2(kTRUE);
// Initialize filter values to their defaults
SetFilterOnContributors();
SetFilterOnTracklets();
return kTRUE;
}
//______________________________________________________________________
AliITSMeanVertexer::~AliITSMeanVertexer() {
// Destructor
delete fDetTypeRec;
delete fVertexXY;
delete fVertexZ;
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Reconstruct(AliRawReader *rawReader, Bool_t mode){
// Performs SPD local reconstruction
// and vertex finding
// returns true in case a vertex is found
// Run SPD cluster finder
TTree* clustersTree = new TTree("TreeR", "Reconstructed Points Container"); //make a tree
fDetTypeRec->DigitsToRecPoints(rawReader,clustersTree,"SPD");
Bool_t vtxOK = kFALSE;
AliESDVertex *vtx = NULL;
// Run Tapan's vertex-finder
if (!mode) {
AliITSVertexer3DTapan *vertexer1 = new AliITSVertexer3DTapan(1000);
vtx = vertexer1->FindVertexForCurrentEvent(clustersTree);
delete vertexer1;
if (TMath::Abs(vtx->GetChi2()) < 0.1) vtxOK = kTRUE;
}
else {
// Run standard vertexer3d
AliITSVertexer3D *vertexer2 = new AliITSVertexer3D();
vertexer2->SetDetTypeRec(fDetTypeRec);
vtx = vertexer2->FindVertexForCurrentEvent(clustersTree);
AliMultiplicity *mult = vertexer2->GetMultiplicity();
delete vertexer2;
if(Filter(vtx,mult)) vtxOK = kTRUE;
}
delete clustersTree;
if (vtxOK) AddToMean(vtx);
if (vtx) delete vtx;
return vtxOK;
}
//______________________________________________________________________
void AliITSMeanVertexer::WriteVertices(const char *filename){
// Compute mean vertex and
// store it along with the histograms
// in a file
TFile fmv(filename,"update");
if(ComputeMean()){
Double_t cov[6];
cov[0] = fAverPosSq[0][0]; // variance x
cov[1] = fAverPosSq[0][1]; // cov xy
cov[2] = fAverPosSq[1][1]; // variance y
cov[3] = fAverPosSq[0][2]; // cov xz
cov[4] = fAverPosSq[1][2]; // cov yz
cov[5] = fAverPosSq[2][2]; // variance z
AliMeanVertex mv(fWeighPos,fWeighSig,cov,fNoEventsContr,fTotTracklets,fAverTracklets,fSigmaOnAverTracks);
mv.SetTitle("Mean Vertex");
mv.SetName("MeanVertex");
AliDebug(1,Form("Contrib av. trk = %10.2f ",mv.GetAverageNumbOfTracklets()));
AliDebug(1,Form("Sigma %10.4f ",mv.GetSigmaOnAvNumbOfTracks()));
// we have to add chi2 here
AliESDVertex vtx(fWeighPos,cov,0,TMath::Nint(fAverTracklets),"MeanVertexPos");
mv.Write(mv.GetName(),TObject::kOverwrite);
vtx.Write(vtx.GetName(),TObject::kOverwrite);
}
else {
AliError(Form("Evaluation of mean vertex not possible. Number of used events = %d",fNoEventsContr));
}
fVertexXY->Write(fVertexXY->GetName(),TObject::kOverwrite);
fVertexZ->Write(fVertexZ->GetName(),TObject::kOverwrite);
fmv.Close();
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::Filter(AliESDVertex *vert,AliMultiplicity *mult){
// Apply selection criteria to events
Bool_t status = kFALSE;
if(!vert || !mult)return status;
// Remove vertices reconstructed with vertexerZ
if(strcmp(vert->GetName(),"SPDVertexZ") == 0) return status;
Int_t ncontr = vert->GetNContributors();
Int_t ntracklets = mult->GetNumberOfTracklets();
AliDebug(1,Form("Number of contributors = %d",ncontr));
AliDebug(1,Form("Number of tracklets = %d",ntracklets));
if(ncontr>fFilterOnContributors && ntracklets > fFilterOnTracklets) status = kTRUE;
fTotTracklets += ntracklets;
fTotTrackletsSq += ntracklets*ntracklets;
return status;
}
//______________________________________________________________________
void AliITSMeanVertexer::AddToMean(AliESDVertex *vert){
// update mean vertex
Double_t currentPos[3],currentSigma[3];
vert->GetXYZ(currentPos);
vert->GetSigmaXYZ(currentSigma);
Bool_t goon = kTRUE;
for(Int_t i=0;i<3;i++)if(currentSigma[i] == 0.)goon = kFALSE;
if(!goon)return;
for(Int_t i=0;i<3;i++){
fWeighPosSum[i]+=currentPos[i]/currentSigma[i]/currentSigma[i];
fWeighSigSum[i]+=1./currentSigma[i]/currentSigma[i];
fAverPosSum[i]+=currentPos[i];
}
for(Int_t i=0;i<3;i++){
for(Int_t j=i;j<3;j++){
fAverPosSqSum[i][j] += currentPos[i] * currentPos[j];
}
}
fVertexXY->Fill(currentPos[0],currentPos[1]);
fVertexZ->Fill(currentPos[2]);
fNoEventsContr++;
}
//______________________________________________________________________
Bool_t AliITSMeanVertexer::ComputeMean(){
// compute mean vertex
if(fNoEventsContr < 2) return kFALSE;
Double_t nevents = fNoEventsContr;
for(Int_t i=0;i<3;i++){
fWeighPos[i] = fWeighPosSum[i]/fWeighSigSum[i];
fWeighSig[i] = 1./TMath::Sqrt(fWeighSigSum[i]);
fAverPos[i] = fAverPosSum[i]/nevents;
}
for(Int_t i=0;i<3;i++){
for(Int_t j=i;j<3;j++){
fAverPosSq[i][j] = fAverPosSqSum[i][j]/(nevents -1.);
fAverPosSq[i][j] -= nevents/(nevents -1.)*fAverPos[i]*fAverPos[j];
}
}
fAverTracklets = fTotTracklets/nevents;
fSigmaOnAverTracks = fTotTrackletsSq/(nevents - 1);
fSigmaOnAverTracks -= nevents/(nevents -1.)*fAverTracklets*fAverTracklets;
fSigmaOnAverTracks = TMath::Sqrt(fSigmaOnAverTracks);
return kTRUE;
}
<|endoftext|>
|
<commit_before>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2012 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <assert.h>
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::vector<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
if(!event->State)
{
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0 && event->AutoReset)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
return result;
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
return result;
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
bool done = false;
waitIndex = -1;
for(int i = 0; i < count; ++i)
{
waitInfo.WaitIndex = i;
if(WaitForEvent(events[i], 0) == 0)
{
wfmo->EventStatus[i] = true;
if(!waitAll)
{
waitIndex = i;
done = true;
break;
}
}
else
{
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
return result;
events[i]->RegisteredWaits.push_back(waitInfo);
++wfmo->RefCount;
pthread_mutex_unlock(&events[i]->Mutex);
}
}
timespec ts;
if(!done && milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
while(!done)
{
//One (or more) of the events we're monitoring has been triggered?
//If we're waiting for all events, assume we're done and check if there's an event that hasn't fired
//But if we're waiting for just one event, assume we're not done until we find a fired event
done = waitAll;
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
done = false;
break;
}
}
if(!done)
{
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
}
}
wfmo->StillWaiting = false;
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.back();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_back();
continue;
}
event->State = false;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
result = pthread_cond_signal(&i->Waiter->CVariable);
pthread_mutex_unlock(&i->Waiter->Mutex);
event->RegisteredWaits.pop_back();
break;
}
#endif
//event->State can be false if compiled with WFMO support
if(event->State)
{
result = pthread_cond_signal(&event->CVariable);
}
}
else
{
#ifdef WFMO
for(int i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_cond_signal(&info->Waiter->CVariable);
pthread_mutex_unlock(&info->Waiter->Mutex);
}
event->RegisteredWaits.clear();
#endif
result = pthread_cond_broadcast(&event->CVariable);
}
pthread_mutex_unlock(&event->Mutex);
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<commit_msg>Fixed possible deadlock in WFMO Thanks to Ashwin Chandra <achandra@panologic.com> for pointing out a deadlock that existed if a call to SetEvent came in the middle of a WaitForMultipleEvents call, in particular if SetEvent happened after WaitForMultipleEvents' usage of WaitForEvent and before the RegisteredWaits push_back took place.<commit_after>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2012 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <assert.h>
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::vector<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int UnlockedWaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = 0;
if(!event->State)
{
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0 && event->AutoReset)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
return result;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
result = UnlockedWaitForEvent(event, milliseconds);
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
return result;
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
return result;
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
bool done = false;
waitIndex = -1;
for(int i = 0; i < count; ++i)
{
waitInfo.WaitIndex = i;
//Must not release lock until RegisteredWait is potentially added
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
return result;
if(UnlockedWaitForEvent(events[i], 0) == 0)
{
pthread_mutex_unlock(&events[i]->Mutex);
wfmo->EventStatus[i] = true;
if(!waitAll)
{
waitIndex = i;
done = true;
break;
}
}
else
{
events[i]->RegisteredWaits.push_back(waitInfo);
++wfmo->RefCount;
pthread_mutex_unlock(&events[i]->Mutex);
}
}
timespec ts;
if(!done && milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
while(!done)
{
//One (or more) of the events we're monitoring has been triggered?
//If we're waiting for all events, assume we're done and check if there's an event that hasn't fired
//But if we're waiting for just one event, assume we're not done until we find a fired event
done = waitAll;
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
done = false;
break;
}
}
if(!done)
{
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
}
}
wfmo->StillWaiting = false;
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.back();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_back();
continue;
}
event->State = false;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
result = pthread_cond_signal(&i->Waiter->CVariable);
pthread_mutex_unlock(&i->Waiter->Mutex);
event->RegisteredWaits.pop_back();
break;
}
#endif
//event->State can be false if compiled with WFMO support
if(event->State)
{
result = pthread_cond_signal(&event->CVariable);
}
}
else
{
#ifdef WFMO
for(int i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_cond_signal(&info->Waiter->CVariable);
pthread_mutex_unlock(&info->Waiter->Mutex);
}
event->RegisteredWaits.clear();
#endif
result = pthread_cond_broadcast(&event->CVariable);
}
pthread_mutex_unlock(&event->Mutex);
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<|endoftext|>
|
<commit_before>/// @brief provides
#ifndef INC_UNDERFLOW_POLICY_HPP_
#define iNC_UNDERFLOW_POLICY_HPP_
#include <boost/cstdint.hpp>
#include <limits>
#include <string>
#include <stdexcept>
namespace utils {
/// @brief underflow policy for fixed-point arithmetics
class underflow_policy
{
public:
/// @brief policy to throw an exception in case the underflow has occured
class exception
{
public:
/// @brief checks if any floating-point/another fixed-point value
/// can be represented in current fixed-point format. If it is not it
/// will throw underflow exceptions.
/// @throw boost::numeric::positive_overflow
/// @throw boost::numeric::negative_overflow
template<typename fixed_point, typename T>
static inline typename fixed_point::value_type checked_convert(T val)
{
static std::string const m("the value is too small to be captured with fixed-point type");
if (val != T(0) && as_native(fixed_point(val)) == 0) {
throw std::underflow_error(m);
}
return static_cast<typename fixed_point::value_type>(val);
}
};
/// @brief policy to do nothing in case the underflow has occured
class just_do
{
public:
/// @brief converts integer to fixed point value type. If it is does not
/// fit fixed point value type range than it performs by modulus computing.
template<typename fixed_point, typename T>
static inline typename fixed_point::value_type checked_convert(T val)
{
return static_cast<typename fixed_point::value_type>(val %
fixed_point::bounds::max);
}
};
};
}
#endif
<commit_msg>underflow_policy.hpp: just_do is a kind of id mapping<commit_after>/// @brief provides
#ifndef INC_UNDERFLOW_POLICY_HPP_
#define iNC_UNDERFLOW_POLICY_HPP_
#include <boost/cstdint.hpp>
#include <limits>
#include <string>
#include <stdexcept>
namespace utils {
/// @brief underflow policy for fixed-point arithmetics
class underflow_policy
{
public:
/// @brief policy to throw an exception in case the underflow has occured
class exception
{
public:
/// @brief checks if any floating-point/another fixed-point value
/// can be represented in current fixed-point format. If it is not it
/// will throw underflow exceptions.
/// @throw boost::numeric::positive_overflow
/// @throw boost::numeric::negative_overflow
template<typename fixed_point, typename T>
static inline typename fixed_point::value_type checked_convert(T val)
{
static std::string const m("the value is too small to be captured with fixed-point type");
if (val != T(0) && as_native(fixed_point(val)) == 0) {
throw std::underflow_error(m);
}
return static_cast<typename fixed_point::value_type>(val);
}
};
/// @brief policy to do nothing in case the underflow has occured
class just_do
{
public:
/// @brief converts integer to fixed point value type. If it is does not
/// fit fixed point value type range than it performs by modulus computing.
template<typename fixed_point, typename T>
static inline typename fixed_point::value_type checked_convert(T val)
{
return static_cast<typename fixed_point::value_type>(val);
}
};
};
}
#endif
<|endoftext|>
|
<commit_before>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013 Due date: 30 NOV 2013
Problem:
Write a program that plays the game of HANGMAN(guessing a
mystery word). Read a word to be guessed from a file into
successive elements of the array WORD. The player must
guess the letters belonging to WORD. A single guessing
session should be terminated when either all letters have
been guessed correctly (player wins) or a specified number
of incorrect guesses have been made (computer wins). A run
must consist of at least two sessions: one player wins and
one computer wins. The player decides whether or not to
start a new session.
***************************************************************/
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
ifstream inFile; // define ifstream to inFile command
ofstream outFile; // define outfile2
int main()
{
// variables
//char guess = ' '; // guess from user
string dictionary[20]; // 20 words to load from file
int random20 = 0; // random number
string word = ""; // word to be read from file (the solution)
unsigned long wordLength = 0; // length of word
string solution = ""; // solution (guessed by user)
inFile.open("Words4Hangman.txt"); // open input file
while (inFile.good())
{
for (int i = 0; i < 20; i++)
{
inFile >> dictionary[i]; // load file and fill dict
}
}
inFile.close(); // close the file
srand((int)time(NULL)); // initialize random seed
random20 = (rand() % 20); // set random to 20 +-
word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
cout << "Random word: -------- " << word << endl; // test
wordLength = word.size();
cout << "Word length: " << wordLength << endl; // test
solution.assign(wordLength, '*');
cout << "Solution: " << solution << endl;
return 0;
}<commit_msg>initialize in function<commit_after>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013 Due date: 30 NOV 2013
Problem:
Write a program that plays the game of HANGMAN(guessing a
mystery word). Read a word to be guessed from a file into
successive elements of the array WORD. The player must
guess the letters belonging to WORD. A single guessing
session should be terminated when either all letters have
been guessed correctly (player wins) or a specified number
of incorrect guesses have been made (computer wins). A run
must consist of at least two sessions: one player wins and
one computer wins. The player decides whether or not to
start a new session.
***************************************************************/
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
ifstream inFile; // define ifstream to inFile command
ofstream outFile; // define outfile2
void initialize(unsigned long); // function to initalize everything
// global variables
char guess; // guess from user
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
// functions
int main() // reads in the file and sets the functions in motion
{
int random20 = 0; // random number
unsigned long wordLength; // length of word
string dictionary[20]; // 20 words to load from file
inFile.open("Words4Hangman.txt"); // open input file
while (inFile.good())
{
for (int i = 0; i < 20; i++)
{
inFile >> dictionary[i]; // load file and fill dict
}
}
inFile.close(); // close the file
srand((int)time(NULL)); // initialize random seed
random20 = (rand() % 20); // set random to 20 +-
word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
wordLength = word.size(); // size (length) of the string
initialize(wordLength); // sends length of word to initialize function
return 0;
}
void initialize(unsigned long wordLength)
{
solution.assign(wordLength, '*');
cout << "Solution: " << solution << endl; // test
}<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
/*
This code tests the sin_to_string() function implementation.
*/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "internet.h"
#include "function_test_driver.h"
#include "unit_test_utils.h"
#include "emit.h"
static bool test_normal_case(void);
bool FTEST_string_to_hostname(void) {
// beginning junk for getPortFromAddr()
e.emit_function("string_to_hostname(const char*)");
e.emit_comment("Converts a sinful string to a hostname.");
e.emit_problem("None");
// driver to run the tests and all required setup
FunctionDriver driver;
driver.register_function(test_normal_case);
// run the tests
bool test_result = driver.do_all_functions();
e.emit_function_break();
return test_result;
}
static bool test_normal_case() {
e.emit_test("Is normal input converted correctly?");
char instring[35];
char* input = &instring[0];
char* host_to_test = strdup( "north.cs.wisc.edu" );
struct hostent *h;
h = gethostbyname(host_to_test);
free(host_to_test);
e.emit_input_header();
sprintf(instring, "<%s:100>",inet_ntoa(*((in_addr*) h->h_addr)));
e.emit_param("IP", instring);
e.emit_output_expected_header();
char expected[30];
sprintf(expected, "north.cs.wisc.edu");
e.emit_retval(expected);
e.emit_output_actual_header();
char* hostname = string_to_hostname(input);
e.emit_retval(hostname);
if(strcmp(&expected[0], hostname) != 0) {
free(expected);
e.emit_result_failure(__LINE__);
return false;
}
e.emit_result_success(__LINE__);
return true;
}
<commit_msg>Remove free of a local array<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
/*
This code tests the sin_to_string() function implementation.
*/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "internet.h"
#include "function_test_driver.h"
#include "unit_test_utils.h"
#include "emit.h"
static bool test_normal_case(void);
bool FTEST_string_to_hostname(void) {
// beginning junk for getPortFromAddr()
e.emit_function("string_to_hostname(const char*)");
e.emit_comment("Converts a sinful string to a hostname.");
e.emit_problem("None");
// driver to run the tests and all required setup
FunctionDriver driver;
driver.register_function(test_normal_case);
// run the tests
bool test_result = driver.do_all_functions();
e.emit_function_break();
return test_result;
}
static bool test_normal_case() {
e.emit_test("Is normal input converted correctly?");
char instring[35];
char* input = &instring[0];
char* host_to_test = strdup( "north.cs.wisc.edu" );
struct hostent *h;
h = gethostbyname(host_to_test);
free(host_to_test);
e.emit_input_header();
sprintf(instring, "<%s:100>",inet_ntoa(*((in_addr*) h->h_addr)));
e.emit_param("IP", instring);
e.emit_output_expected_header();
char expected[30];
sprintf(expected, "north.cs.wisc.edu");
e.emit_retval(expected);
e.emit_output_actual_header();
char* hostname = string_to_hostname(input);
e.emit_retval(hostname);
if(strcmp(&expected[0], hostname) != 0) {
e.emit_result_failure(__LINE__);
return false;
}
e.emit_result_success(__LINE__);
return true;
}
<|endoftext|>
|
<commit_before>/*
* GridMapVisual.cpp
*
* Created on: Aug 3, 2016
* Author: Philipp Krüsi, Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include <rviz/uniform_string_stream.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
#include <OGRE/OgreTechnique.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreManualObject.h>
#include <rviz/ogre_helpers/billboard_line.h>
#include <grid_map_ros/grid_map_ros.hpp>
#include <grid_map_core/GridMapMath.hpp>
#include "grid_map_rviz_plugin/GridMapVisual.hpp"
namespace grid_map_rviz_plugin {
GridMapVisual::GridMapVisual(Ogre::SceneManager* sceneManager, Ogre::SceneNode* parentNode)
: manualObject_(0),
haveMap_(false)
{
sceneManager_ = sceneManager;
frameNode_ = parentNode->createChildSceneNode();
// Create BillboardLine object.
meshLines_.reset(new rviz::BillboardLine(sceneManager_, frameNode_));
}
GridMapVisual::~GridMapVisual()
{
// Destroy the ManualObject.
sceneManager_->destroyManualObject(manualObject_);
material_->unload();
Ogre::MaterialManager::getSingleton().remove(material_->getName());
// Destroy the frame node.
sceneManager_->destroySceneNode(frameNode_);
}
void GridMapVisual::setMessage(const grid_map_msgs::GridMap::ConstPtr& msg)
{
// Convert grid map message.
grid_map::GridMapRosConverter::fromMessage(*msg, map_);
haveMap_ = true;
}
void GridMapVisual::computeVisualization(float alpha, bool showGridLines, bool flatTerrain,
std::string heightLayer, bool flatColor,
Ogre::ColourValue meshColor,
bool mapLayerColor, std::string colorLayer,
bool useRainbow, bool invertRainbow,
Ogre::ColourValue minColor, Ogre::ColourValue maxColor,
bool autocomputeIntensity,
float minIntensity, float maxIntensity)
{
if (!haveMap_) {
ROS_DEBUG("Unable to visualize grid map, no map data. Use setMessage() first!");
return;
}
// Get list of layers and check if the requested ones are present.
std::vector<std::string> layerNames = map_.getLayers();
if (layerNames.size() < 1) {
ROS_DEBUG("Unable to visualize grid map, map must contain at least one layer.");
return;
}
if ((!flatTerrain && !map_.exists(heightLayer)) || (!flatColor && !map_.exists(colorLayer))) {
ROS_DEBUG("Unable to visualize grid map, requested layer(s) not available.");
return;
}
// Convert to simple format, makes things easier.
map_.convertToDefaultStartIndex();
// basic grid map data
size_t rows = map_.getSize()(0);
size_t cols = map_.getSize()(1);
if (rows < 2 || cols < 2) {
ROS_DEBUG("GridMap has not enough cells.");
return;
}
double resolution = map_.getResolution();
const grid_map::Matrix& heightData = map_[flatTerrain ? layerNames[0] : heightLayer];
const grid_map::Matrix& colorData = map_[flatColor ? layerNames[0] : colorLayer];
// initialize ManualObject
if (!manualObject_) {
static uint32_t count = 0;
rviz::UniformStringStream ss;
ss << "Mesh" << count++;
manualObject_ = sceneManager_->createManualObject(ss.str());
frameNode_->attachObject(manualObject_);
ss << "Material";
materialName_ = ss.str();
material_ = Ogre::MaterialManager::getSingleton().create(materialName_, "rviz");
material_->setReceiveShadows(false);
material_->getTechnique(0)->setLightingEnabled(true);
material_->setCullingMode(Ogre::CULL_NONE);
}
manualObject_->clear();
size_t nVertices = 4 + 6 * (cols * rows - cols - rows);
manualObject_->estimateVertexCount(nVertices);
manualObject_->begin(materialName_, Ogre::RenderOperation::OT_TRIANGLE_LIST);
meshLines_->clear();
if (showGridLines) {
meshLines_->setColor(0.0, 0.0, 0.0, alpha);
meshLines_->setLineWidth(resolution / 10.0);
meshLines_->setMaxPointsPerLine(2);
size_t nLines = rows * (cols - 1) + cols * (rows - 1);
meshLines_->setNumLines(nLines);
}
bool plottedFirstLine = false;
// Determine max and min intensity.
if (autocomputeIntensity && !flatColor && !mapLayerColor) {
minIntensity = colorData.minCoeffOfFinites();
maxIntensity = colorData.maxCoeffOfFinites();
}
if (!map_.hasBasicLayers()) map_.setBasicLayers({heightLayer});
// Plot mesh.
for (size_t i = 0; i < rows - 1; ++i) {
for (size_t j = 0; j < cols - 1; ++j) {
bool left_valid = true;
bool right_valid = true;
std::vector<Ogre::Vector3> vertices;
std::vector<Ogre::ColourValue> colors;
for (size_t k = 0; k < 2; k++) {
for (size_t l = 0; l < 2; l++) {
grid_map::Position position;
grid_map::Index index(i + k, j + l);
map_.getPosition(index, position);
float height = heightData(index(0), index(1));
if (!map_.isValid(index)) {
if ((k + l) <= 1) left_valid = false;
if ((k + l) >= 1) right_valid = false;
vertices.push_back(Ogre::Vector3());
colors.push_back(Ogre::ColourValue());
} else {
vertices.push_back(
Ogre::Vector3(position(0), position(1), flatTerrain ? 0.0 : height));
if (!flatColor) {
float color = colorData(index(0), index(1));
Ogre::ColourValue colorValue;
if (mapLayerColor) {
Eigen::Vector3f colorVectorRGB;
grid_map::colorValueToVector(color, colorVectorRGB);
colorValue = Ogre::ColourValue(colorVectorRGB(0), colorVectorRGB(1), colorVectorRGB(2));
} else {
normalizeIntensity(color, minIntensity, maxIntensity);
colorValue =
useRainbow ? (invertRainbow ? getRainbowColor(1.0 - color) : getRainbowColor(color)) :
getInterpolatedColor(color, minColor, maxColor);
}
colors.push_back(colorValue);
}
}
}
}
// upper left triangle
if (left_valid) {
Ogre::Vector3 normal1 = (vertices[1] - vertices[0]).crossProduct(vertices[2] - vertices[0]);
normal1.normalise();
for (size_t m = 0; m < 3; m++) {
manualObject_->position(vertices[m]);
manualObject_->normal(normal1);
Ogre::ColourValue color = flatColor ? meshColor : colors[m];
manualObject_->colour(color.r, color.g, color.b, alpha);
}
}
// lower right triangle
if (right_valid) {
Ogre::Vector3 normal2 = (vertices[2] - vertices[1]).crossProduct(vertices[3] - vertices[1]);
normal2.normalise();
for (size_t m = 1; m < 4; m++) {
manualObject_->position(vertices[m]);
manualObject_->normal(normal2);
Ogre::ColourValue color = flatColor ? meshColor : colors[m];
manualObject_->colour(color.r, color.g, color.b, alpha);
}
}
// plot grid lines
if (showGridLines) {
if (left_valid) {
// right line
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[0]);
meshLines_->addPoint(vertices[1]);
plottedFirstLine = true;
// down line
meshLines_->newLine();
meshLines_->addPoint(vertices[0]);
meshLines_->addPoint(vertices[2]);
}
if (i == rows - 2 && right_valid) {
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[2]);
meshLines_->addPoint(vertices[3]);
plottedFirstLine = true;
}
if (j == cols - 2 && right_valid) {
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[1]);
meshLines_->addPoint(vertices[3]);
plottedFirstLine = true;
}
}
}
}
manualObject_->end();
material_->getTechnique(0)->setLightingEnabled(false);
if ( alpha < 0.9998 )
{
material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );
material_->getTechnique(0)->setDepthWriteEnabled( false );
}
else
{
material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE );
material_->getTechnique(0)->setDepthWriteEnabled( true );
}
}
void GridMapVisual::setFramePosition(const Ogre::Vector3& position)
{
frameNode_->setPosition(position);
}
void GridMapVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frameNode_->setOrientation(orientation);
}
std::vector<std::string> GridMapVisual::getLayerNames()
{
return map_.getLayers();
}
// Compute intensity value in the interval [0,1].
void GridMapVisual::normalizeIntensity(float& intensity, float min_intensity, float max_intensity)
{
intensity = std::min(intensity, max_intensity);
intensity = std::max(intensity, min_intensity);
intensity = (intensity - min_intensity) / (max_intensity - min_intensity);
}
// Copied from rviz/src/rviz/default_plugin/point_cloud_transformers.cpp.
Ogre::ColourValue GridMapVisual::getRainbowColor(float intensity)
{
intensity = std::min(intensity, 1.0f);
intensity = std::max(intensity, 0.0f);
float h = intensity * 5.0f + 1.0f;
int i = floor(h);
float f = h - i;
if (!(i & 1)) f = 1 - f; // if i is even
float n = 1 - f;
Ogre::ColourValue color;
if (i <= 1) color[0] = n, color[1] = 0, color[2] = 1;
else if (i == 2) color[0] = 0, color[1] = n, color[2] = 1;
else if (i == 3) color[0] = 0, color[1] = 1, color[2] = n;
else if (i == 4) color[0] = n, color[1] = 1, color[2] = 0;
else if (i >= 5) color[0] = 1, color[1] = n, color[2] = 0;
return color;
}
// Get interpolated color value.
Ogre::ColourValue GridMapVisual::getInterpolatedColor(float intensity, Ogre::ColourValue min_color,
Ogre::ColourValue max_color)
{
intensity = std::min(intensity, 1.0f);
intensity = std::max(intensity, 0.0f);
Ogre::ColourValue color;
color.r = intensity * (max_color.r - min_color.r) + min_color.r;
color.g = intensity * (max_color.g - min_color.g) + min_color.g;
color.b = intensity * (max_color.b - min_color.b) + min_color.b;
return color;
}
} // namespace
<commit_msg>Fixing formatting.<commit_after>/*
* GridMapVisual.cpp
*
* Created on: Aug 3, 2016
* Author: Philipp Krüsi, Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include <rviz/uniform_string_stream.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
#include <OGRE/OgreTechnique.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreManualObject.h>
#include <rviz/ogre_helpers/billboard_line.h>
#include <grid_map_ros/grid_map_ros.hpp>
#include <grid_map_core/GridMapMath.hpp>
#include "grid_map_rviz_plugin/GridMapVisual.hpp"
namespace grid_map_rviz_plugin {
GridMapVisual::GridMapVisual(Ogre::SceneManager* sceneManager, Ogre::SceneNode* parentNode)
: manualObject_(0),
haveMap_(false)
{
sceneManager_ = sceneManager;
frameNode_ = parentNode->createChildSceneNode();
// Create BillboardLine object.
meshLines_.reset(new rviz::BillboardLine(sceneManager_, frameNode_));
}
GridMapVisual::~GridMapVisual()
{
// Destroy the ManualObject.
sceneManager_->destroyManualObject(manualObject_);
material_->unload();
Ogre::MaterialManager::getSingleton().remove(material_->getName());
// Destroy the frame node.
sceneManager_->destroySceneNode(frameNode_);
}
void GridMapVisual::setMessage(const grid_map_msgs::GridMap::ConstPtr& msg)
{
// Convert grid map message.
grid_map::GridMapRosConverter::fromMessage(*msg, map_);
haveMap_ = true;
}
void GridMapVisual::computeVisualization(float alpha, bool showGridLines, bool flatTerrain,
std::string heightLayer, bool flatColor,
Ogre::ColourValue meshColor,
bool mapLayerColor, std::string colorLayer,
bool useRainbow, bool invertRainbow,
Ogre::ColourValue minColor, Ogre::ColourValue maxColor,
bool autocomputeIntensity,
float minIntensity, float maxIntensity)
{
if (!haveMap_) {
ROS_DEBUG("Unable to visualize grid map, no map data. Use setMessage() first!");
return;
}
// Get list of layers and check if the requested ones are present.
std::vector<std::string> layerNames = map_.getLayers();
if (layerNames.size() < 1) {
ROS_DEBUG("Unable to visualize grid map, map must contain at least one layer.");
return;
}
if ((!flatTerrain && !map_.exists(heightLayer)) || (!flatColor && !map_.exists(colorLayer))) {
ROS_DEBUG("Unable to visualize grid map, requested layer(s) not available.");
return;
}
// Convert to simple format, makes things easier.
map_.convertToDefaultStartIndex();
// basic grid map data
size_t rows = map_.getSize()(0);
size_t cols = map_.getSize()(1);
if (rows < 2 || cols < 2) {
ROS_DEBUG("GridMap has not enough cells.");
return;
}
double resolution = map_.getResolution();
const grid_map::Matrix& heightData = map_[flatTerrain ? layerNames[0] : heightLayer];
const grid_map::Matrix& colorData = map_[flatColor ? layerNames[0] : colorLayer];
// initialize ManualObject
if (!manualObject_) {
static uint32_t count = 0;
rviz::UniformStringStream ss;
ss << "Mesh" << count++;
manualObject_ = sceneManager_->createManualObject(ss.str());
frameNode_->attachObject(manualObject_);
ss << "Material";
materialName_ = ss.str();
material_ = Ogre::MaterialManager::getSingleton().create(materialName_, "rviz");
material_->setReceiveShadows(false);
material_->getTechnique(0)->setLightingEnabled(true);
material_->setCullingMode(Ogre::CULL_NONE);
}
manualObject_->clear();
size_t nVertices = 4 + 6 * (cols * rows - cols - rows);
manualObject_->estimateVertexCount(nVertices);
manualObject_->begin(materialName_, Ogre::RenderOperation::OT_TRIANGLE_LIST);
meshLines_->clear();
if (showGridLines) {
meshLines_->setColor(0.0, 0.0, 0.0, alpha);
meshLines_->setLineWidth(resolution / 10.0);
meshLines_->setMaxPointsPerLine(2);
size_t nLines = rows * (cols - 1) + cols * (rows - 1);
meshLines_->setNumLines(nLines);
}
bool plottedFirstLine = false;
// Determine max and min intensity.
if (autocomputeIntensity && !flatColor && !mapLayerColor) {
minIntensity = colorData.minCoeffOfFinites();
maxIntensity = colorData.maxCoeffOfFinites();
}
if (!map_.hasBasicLayers()) map_.setBasicLayers({heightLayer});
// Plot mesh.
for (size_t i = 0; i < rows - 1; ++i) {
for (size_t j = 0; j < cols - 1; ++j) {
bool left_valid = true;
bool right_valid = true;
std::vector<Ogre::Vector3> vertices;
std::vector<Ogre::ColourValue> colors;
for (size_t k = 0; k < 2; k++) {
for (size_t l = 0; l < 2; l++) {
grid_map::Position position;
grid_map::Index index(i + k, j + l);
map_.getPosition(index, position);
float height = heightData(index(0), index(1));
if (!map_.isValid(index)) {
if ((k + l) <= 1) left_valid = false;
if ((k + l) >= 1) right_valid = false;
vertices.push_back(Ogre::Vector3());
colors.push_back(Ogre::ColourValue());
} else {
vertices.push_back(
Ogre::Vector3(position(0), position(1), flatTerrain ? 0.0 : height));
if (!flatColor) {
float color = colorData(index(0), index(1));
Ogre::ColourValue colorValue;
if (mapLayerColor) {
Eigen::Vector3f colorVectorRGB;
grid_map::colorValueToVector(color, colorVectorRGB);
colorValue = Ogre::ColourValue(colorVectorRGB(0), colorVectorRGB(1), colorVectorRGB(2));
} else {
normalizeIntensity(color, minIntensity, maxIntensity);
colorValue =
useRainbow ? (invertRainbow ? getRainbowColor(1.0 - color) : getRainbowColor(color)) :
getInterpolatedColor(color, minColor, maxColor);
}
colors.push_back(colorValue);
}
}
}
}
// upper left triangle
if (left_valid) {
Ogre::Vector3 normal1 = (vertices[1] - vertices[0]).crossProduct(vertices[2] - vertices[0]);
normal1.normalise();
for (size_t m = 0; m < 3; m++) {
manualObject_->position(vertices[m]);
manualObject_->normal(normal1);
Ogre::ColourValue color = flatColor ? meshColor : colors[m];
manualObject_->colour(color.r, color.g, color.b, alpha);
}
}
// lower right triangle
if (right_valid) {
Ogre::Vector3 normal2 = (vertices[2] - vertices[1]).crossProduct(vertices[3] - vertices[1]);
normal2.normalise();
for (size_t m = 1; m < 4; m++) {
manualObject_->position(vertices[m]);
manualObject_->normal(normal2);
Ogre::ColourValue color = flatColor ? meshColor : colors[m];
manualObject_->colour(color.r, color.g, color.b, alpha);
}
}
// plot grid lines
if (showGridLines) {
if (left_valid) {
// right line
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[0]);
meshLines_->addPoint(vertices[1]);
plottedFirstLine = true;
// down line
meshLines_->newLine();
meshLines_->addPoint(vertices[0]);
meshLines_->addPoint(vertices[2]);
}
if (i == rows - 2 && right_valid) {
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[2]);
meshLines_->addPoint(vertices[3]);
plottedFirstLine = true;
}
if (j == cols - 2 && right_valid) {
if (plottedFirstLine) meshLines_->newLine();
meshLines_->addPoint(vertices[1]);
meshLines_->addPoint(vertices[3]);
plottedFirstLine = true;
}
}
}
}
manualObject_->end();
material_->getTechnique(0)->setLightingEnabled(false);
if (alpha < 0.9998) {
material_->getTechnique(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
material_->getTechnique(0)->setDepthWriteEnabled(false);
} else {
material_->getTechnique(0)->setSceneBlending(Ogre::SBT_REPLACE);
material_->getTechnique(0)->setDepthWriteEnabled(true);
}
}
void GridMapVisual::setFramePosition(const Ogre::Vector3& position)
{
frameNode_->setPosition(position);
}
void GridMapVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frameNode_->setOrientation(orientation);
}
std::vector<std::string> GridMapVisual::getLayerNames()
{
return map_.getLayers();
}
// Compute intensity value in the interval [0,1].
void GridMapVisual::normalizeIntensity(float& intensity, float min_intensity, float max_intensity)
{
intensity = std::min(intensity, max_intensity);
intensity = std::max(intensity, min_intensity);
intensity = (intensity - min_intensity) / (max_intensity - min_intensity);
}
// Copied from rviz/src/rviz/default_plugin/point_cloud_transformers.cpp.
Ogre::ColourValue GridMapVisual::getRainbowColor(float intensity)
{
intensity = std::min(intensity, 1.0f);
intensity = std::max(intensity, 0.0f);
float h = intensity * 5.0f + 1.0f;
int i = floor(h);
float f = h - i;
if (!(i & 1)) f = 1 - f; // if i is even
float n = 1 - f;
Ogre::ColourValue color;
if (i <= 1) color[0] = n, color[1] = 0, color[2] = 1;
else if (i == 2) color[0] = 0, color[1] = n, color[2] = 1;
else if (i == 3) color[0] = 0, color[1] = 1, color[2] = n;
else if (i == 4) color[0] = n, color[1] = 1, color[2] = 0;
else if (i >= 5) color[0] = 1, color[1] = n, color[2] = 0;
return color;
}
// Get interpolated color value.
Ogre::ColourValue GridMapVisual::getInterpolatedColor(float intensity, Ogre::ColourValue min_color,
Ogre::ColourValue max_color)
{
intensity = std::min(intensity, 1.0f);
intensity = std::max(intensity, 0.0f);
Ogre::ColourValue color;
color.r = intensity * (max_color.r - min_color.r) + min_color.r;
color.g = intensity * (max_color.g - min_color.g) + min_color.g;
color.b = intensity * (max_color.b - min_color.b) + min_color.b;
return color;
}
} // namespace
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <getopt.h>
#include <libgen.h> // FIXME
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <map>
#include "cppunit-header.h"
namespace config {
bool verbose = false;
};
#if 0
typedef std::map<std::string, CppUnit::Outputter *> OutputterMap;
typedef std::map<std::string, CppUnit::TestListener *> ListenerMap;
#else
typedef std::map<std::string, std::shared_ptr<CppUnit::Outputter>>
OutputterMap;
typedef std::map<std::string, std::shared_ptr<CppUnit::TestListener>>
ListenerMap;
#endif
//////////////////////////////////////////////////////////////////////
void usage(const char * name)
{
std::cerr << "usage: " << name
<< " "
"[-r repeatnumber] "
"[-t testname] "
"[-o {compiler|text|xml|none}] "
"[-p {dots|brief|verbose|none}] [-l] [-h]"
<< std::endl;
}
//////////////////////////////////////////////////////////////////////
void dump(CppUnit::Test * test)
{
if (test)
{
std::cout << test->getName() << std::endl;
if (test->getChildTestCount())
{
for (int i = 0; i < test->getChildTestCount(); i++)
{
dump(test->getChildTestAt(i));
}
}
}
}
//////////////////////////////////////////////////////////////////////
CppUnit::Test * find(CppUnit::Test * root, const std::string & name)
{
CppUnit::Test * found = nullptr;
if (root)
{
if (name == root->getName())
found = root;
else if (root->getChildTestCount())
{
for (int i = 0; (!found) && i < root->getChildTestCount(); ++i)
found = find(root->getChildTestAt(i), name);
}
}
return found;
}
//////////////////////////////////////////////////////////////////////
int main(int argc, char ** argv)
{
CppUnit::TestResult result;
CppUnit::TestResultCollector collector;
result.addListener(&collector);
using std::make_shared;
using CppUnit::CompilerOutputter;
using CppUnit::TextOutputter;
using CppUnit::XmlOutputter;
using CppUnit::TextTestProgressListener;
using CppUnit::BriefTestProgressListener;
using CppUnit::BriefTestProgressListener;
OutputterMap allOutputters{
{ "compiler", make_shared<CompilerOutputter>(&collector, std::cout)},
{ "text", make_shared<TextOutputter>(&collector, std::cout) },
{ "xml", make_shared<XmlOutputter>(&collector, std::cout) },
{"none", nullptr },
};
ListenerMap allListeners{
{ "dots", std::make_shared<CppUnit::TextTestProgressListener>() },
{ "brief", std::make_shared<CppUnit::BriefTestProgressListener>() },
{ "verbose", std::make_shared<CppUnit::BriefTestProgressListener>() },
{ "none", nullptr },
};
std::shared_ptr<CppUnit::Outputter> outputter =
allOutputters.find("compiler")->second;
std::shared_ptr<CppUnit::TestListener> listener =
allListeners.find("dots")->second;
char flag = 0;
std::string runTest = basename(argv[0]);
if (!find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest))
{
runTest = "All Tests";
}
int repeat = 1;
while ((flag = getopt(argc, argv, "r:t:o:p:lh")) != -1)
{
switch(flag)
{
case 'r':
repeat = atoi(optarg);
break;
case 'o':
{
OutputterMap::const_iterator it = allOutputters.find(optarg);
if (it == allOutputters.end())
{
std::cerr << "Unknown outputter: " << optarg << std::endl;
return 1;
}
outputter = it->second;
}
break;
case 'p':
{
std::string progress(optarg);
if (progress == "verbose")
{
progress = "brief";
config::verbose = true;
}
ListenerMap::const_iterator it = allListeners.find(optarg);
if (it == allListeners.end())
{
std::cerr << "Unknown listener: " << optarg << std::endl;
return 1;
}
listener = it->second;
}
break;
case 'l':
dump(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
return 0;
break; // not reached
case 't':
runTest = optarg;
break;
case 'h':
default:
usage(argv[0]);
return 1;
break; // not reached
}
}
if (listener != nullptr)
result.addListener(listener.get());
CppUnit::Test * run =
find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest);
if (run == nullptr)
{
std::cerr << "Unknown test case: " << runTest << std::endl;
return 1;
}
CppUnit::TestRunner runner;
runner.addTest(run);
for (int i = 0; i < repeat; i++) {
runner.run(result);
}
if (outputter) outputter->write();
allOutputters.clear();
allListeners.clear();
return collector.testErrors() + collector.testFailures();
}
<commit_msg>cleanup and elimination of a dependency<commit_after>#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <map>
#include "cppunit-header.h"
namespace config {
bool verbose = false;
};
typedef std::map<std::string, std::shared_ptr<CppUnit::Outputter>>
OutputterMap;
typedef std::map<std::string, std::shared_ptr<CppUnit::TestListener>>
ListenerMap;
//////////////////////////////////////////////////////////////////////
void usage(const char * name)
{
std::cerr << "usage: " << name
<< " "
"[-r repeatnumber] "
"[-t testname] "
"[-o {compiler|text|xml|none}] "
"[-p {dots|brief|verbose|none}] [-l] [-h]"
<< std::endl;
}
//////////////////////////////////////////////////////////////////////
void dump(CppUnit::Test * test)
{
if (test)
{
std::cout << test->getName() << std::endl;
if (test->getChildTestCount())
{
for (int i = 0; i < test->getChildTestCount(); i++)
{
dump(test->getChildTestAt(i));
}
}
}
}
//////////////////////////////////////////////////////////////////////
CppUnit::Test * find(CppUnit::Test * root, const std::string & name)
{
CppUnit::Test * found = nullptr;
if (root)
{
if (name == root->getName())
found = root;
else if (root->getChildTestCount())
{
for (int i = 0; (!found) && i < root->getChildTestCount(); ++i)
found = find(root->getChildTestAt(i), name);
}
}
return found;
}
//////////////////////////////////////////////////////////////////////
int main(int argc, char ** argv)
{
CppUnit::TestResult result;
CppUnit::TestResultCollector collector;
result.addListener(&collector);
using std::make_shared;
using CppUnit::CompilerOutputter;
using CppUnit::TextOutputter;
using CppUnit::XmlOutputter;
using CppUnit::TextTestProgressListener;
using CppUnit::BriefTestProgressListener;
using CppUnit::BriefTestProgressListener;
OutputterMap allOutputters{
{ "compiler", make_shared<CompilerOutputter>(&collector, std::cout)},
{ "text", make_shared<TextOutputter>(&collector, std::cout) },
{ "xml", make_shared<XmlOutputter>(&collector, std::cout) },
{"none", nullptr },
};
ListenerMap allListeners{
{ "dots", std::make_shared<CppUnit::TextTestProgressListener>() },
{ "brief", std::make_shared<CppUnit::BriefTestProgressListener>() },
{ "verbose", std::make_shared<CppUnit::BriefTestProgressListener>() },
{ "none", nullptr },
};
std::shared_ptr<CppUnit::Outputter> outputter =
allOutputters.find("compiler")->second;
std::shared_ptr<CppUnit::TestListener> listener =
allListeners.find("dots")->second;
char flag = 0;
std::string runTest = argv[0];
std::string::size_type n = 0;
if ((n = runTest.find_last_of('/')) != std::string::npos)
runTest = runTest.substr(n + 1);
if (!find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest))
{
runTest = "All Tests";
}
int repeat = 1;
while ((flag = getopt(argc, argv, "r:t:o:p:lh")) != -1)
{
switch(flag)
{
case 'r':
repeat = atoi(optarg);
break;
case 'o':
{
OutputterMap::const_iterator it = allOutputters.find(optarg);
if (it == allOutputters.end())
{
std::cerr << "Unknown outputter: " << optarg << std::endl;
return 1;
}
outputter = it->second;
}
break;
case 'p':
{
std::string progress(optarg);
if (progress == "verbose")
{
progress = "brief";
config::verbose = true;
}
ListenerMap::const_iterator it = allListeners.find(optarg);
if (it == allListeners.end())
{
std::cerr << "Unknown listener: " << optarg << std::endl;
return 1;
}
listener = it->second;
}
break;
case 'l':
dump(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
return 0;
break; // not reached
case 't':
runTest = optarg;
break;
case 'h':
default:
usage(argv[0]);
return 1;
break; // not reached
}
}
if (listener != nullptr)
result.addListener(listener.get());
CppUnit::Test * run =
find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest);
if (run == nullptr)
{
std::cerr << "Unknown test case: " << runTest << std::endl;
return 1;
}
CppUnit::TestRunner runner;
runner.addTest(run);
for (int i = 0; i < repeat; i++)
{
runner.run(result);
}
if (outputter) outputter->write();
allOutputters.clear();
allListeners.clear();
return collector.testErrors() + collector.testFailures();
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "..\stdafx.h"
#include "RecipientRowStream.h"
#include "..\String.h"
//#include "SmartView.h"
RecipientRowStream::RecipientRowStream(ULONG cbBin, _In_count_(cbBin) LPBYTE lpBin) : SmartViewParser(cbBin, lpBin)
{
m_cVersion = 0;
m_cRowCount = 0;
m_lpAdrEntry = 0;
}
RecipientRowStream::~RecipientRowStream()
{
if (m_lpAdrEntry && m_cRowCount)
{
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
DeleteSPropVal(m_lpAdrEntry[i].cValues, m_lpAdrEntry[i].rgPropVals);
}
}
delete[] m_lpAdrEntry;
}
void RecipientRowStream::Parse()
{
m_Parser.GetDWORD(&m_cVersion);
m_Parser.GetDWORD(&m_cRowCount);
if (m_cRowCount && m_cRowCount < _MaxEntriesSmall)
m_lpAdrEntry = new ADRENTRY[m_cRowCount];
if (m_lpAdrEntry)
{
memset(m_lpAdrEntry, 0, sizeof(ADRENTRY)*m_cRowCount);
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
m_Parser.GetDWORD(&m_lpAdrEntry[i].cValues);
m_Parser.GetDWORD(&m_lpAdrEntry[i].ulReserved1);
if (m_lpAdrEntry[i].cValues && m_lpAdrEntry[i].cValues < _MaxEntriesSmall)
{
m_lpAdrEntry[i].rgPropVals = BinToSPropValue(
m_lpAdrEntry[i].cValues,
false);
}
}
}
}
_Check_return_ wstring RecipientRowStream::ToStringInternal()
{
wstring szRecipientRowStream;
wstring szTmp;
szRecipientRowStream= formatmessage(
IDS_RECIPIENTROWSTREAMHEADER,
m_cVersion,
m_cRowCount);
if (m_lpAdrEntry && m_cRowCount)
{
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
szTmp= formatmessage(
IDS_RECIPIENTROWSTREAMROW,
i,
m_lpAdrEntry[i].cValues,
m_lpAdrEntry[i].ulReserved1);
szRecipientRowStream += szTmp;
PropertyStruct psPropStruct = { 0 };
psPropStruct.PropCount = m_lpAdrEntry[i].cValues;
psPropStruct.Prop = m_lpAdrEntry[i].rgPropVals;
LPWSTR szProps = PropertyStructToString(&psPropStruct);
szRecipientRowStream += szProps;
delete[] szProps;
}
}
return szRecipientRowStream;
}<commit_msg>Problem: Bad version of RecipientRowCache.cpp Fix: Uncomment line<commit_after>#include "stdafx.h"
#include "..\stdafx.h"
#include "RecipientRowStream.h"
#include "..\String.h"
#include "SmartView.h"
RecipientRowStream::RecipientRowStream(ULONG cbBin, _In_count_(cbBin) LPBYTE lpBin) : SmartViewParser(cbBin, lpBin)
{
m_cVersion = 0;
m_cRowCount = 0;
m_lpAdrEntry = 0;
}
RecipientRowStream::~RecipientRowStream()
{
if (m_lpAdrEntry && m_cRowCount)
{
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
DeleteSPropVal(m_lpAdrEntry[i].cValues, m_lpAdrEntry[i].rgPropVals);
}
}
delete[] m_lpAdrEntry;
}
void RecipientRowStream::Parse()
{
m_Parser.GetDWORD(&m_cVersion);
m_Parser.GetDWORD(&m_cRowCount);
if (m_cRowCount && m_cRowCount < _MaxEntriesSmall)
m_lpAdrEntry = new ADRENTRY[m_cRowCount];
if (m_lpAdrEntry)
{
memset(m_lpAdrEntry, 0, sizeof(ADRENTRY)*m_cRowCount);
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
m_Parser.GetDWORD(&m_lpAdrEntry[i].cValues);
m_Parser.GetDWORD(&m_lpAdrEntry[i].ulReserved1);
if (m_lpAdrEntry[i].cValues && m_lpAdrEntry[i].cValues < _MaxEntriesSmall)
{
m_lpAdrEntry[i].rgPropVals = BinToSPropValue(
m_lpAdrEntry[i].cValues,
false);
}
}
}
}
_Check_return_ wstring RecipientRowStream::ToStringInternal()
{
wstring szRecipientRowStream;
wstring szTmp;
szRecipientRowStream= formatmessage(
IDS_RECIPIENTROWSTREAMHEADER,
m_cVersion,
m_cRowCount);
if (m_lpAdrEntry && m_cRowCount)
{
ULONG i = 0;
for (i = 0; i < m_cRowCount; i++)
{
szTmp= formatmessage(
IDS_RECIPIENTROWSTREAMROW,
i,
m_lpAdrEntry[i].cValues,
m_lpAdrEntry[i].ulReserved1);
szRecipientRowStream += szTmp;
PropertyStruct psPropStruct = { 0 };
psPropStruct.PropCount = m_lpAdrEntry[i].cValues;
psPropStruct.Prop = m_lpAdrEntry[i].rgPropVals;
LPWSTR szProps = PropertyStructToString(&psPropStruct);
szRecipientRowStream += szProps;
delete[] szProps;
}
}
return szRecipientRowStream;
}<|endoftext|>
|
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#include <iterator>
#include <memory>
#include <string>
#include <windows.h>
#include <winnt.h>
#include <winternl.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/winternl.hpp>
#include <hadesmem/detail/last_error.hpp>
#include <hadesmem/find_procedure.hpp>
#include <hadesmem/module.hpp>
#include <hadesmem/patcher.hpp>
#include <hadesmem/process.hpp>
#include "main.hpp"
namespace winternl = hadesmem::detail::winternl;
namespace
{
std::unique_ptr<hadesmem::PatchDetour>& GetNtQuerySystemInformationDetour()
{
static std::unique_ptr<hadesmem::PatchDetour> detour;
return detour;
}
class SystemProcessInformationEnum
{
public:
explicit SystemProcessInformationEnum(
winternl::SYSTEM_INFORMATION_CLASS info_class,
void* buffer) HADESMEM_DETAIL_NOEXCEPT
: buffer_(GetRealBuffer(info_class, buffer)),
prev_(nullptr),
info_class_(info_class),
unlinked_(false)
{
HADESMEM_DETAIL_ASSERT(buffer_);
HADESMEM_DETAIL_ASSERT(
info_class == winternl::SystemProcessInformation ||
info_class == winternl::SystemExtendedProcessInformation ||
info_class == winternl::SystemSessionProcessInformation ||
info_class == winternl::SystemFullProcessInformation);
}
SystemProcessInformationEnum(SystemProcessInformationEnum const&) = delete;
SystemProcessInformationEnum& operator=(SystemProcessInformationEnum const&) =
delete;
void Advance() HADESMEM_DETAIL_NOEXCEPT
{
if (!unlinked_)
{
prev_ = buffer_;
}
unlinked_ = false;
if (buffer_->NextEntryOffset)
{
buffer_ = reinterpret_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(
reinterpret_cast<DWORD_PTR>(buffer_) + buffer_->NextEntryOffset);
}
else
{
buffer_ = nullptr;
}
}
bool Valid() const HADESMEM_DETAIL_NOEXCEPT
{
return buffer_ != nullptr;
}
// TODO: Handle case where we unlink all processes. This should be detected
// and reported to the caller so they can zero out the entire buffer, update
// the return length, or fail, etc. (Whatever should happen, needs more
// investigation).
void Unlink() HADESMEM_DETAIL_NOEXCEPT
{
HADESMEM_DETAIL_ASSERT(buffer_);
HADESMEM_DETAIL_ASSERT(!unlinked_);
if (prev_)
{
if (buffer_->NextEntryOffset)
{
prev_->NextEntryOffset += buffer_->NextEntryOffset;
}
else
{
prev_->NextEntryOffset = 0UL;
}
unlinked_ = true;
}
else
{
// Unlinking the first process is unsupported.
// TODO: Fix this. Will also require reporting a new return length to
// the API (if appliciable) due to the buffer effectively changing size.
HADESMEM_DETAIL_ASSERT(false);
}
}
bool HasName() const HADESMEM_DETAIL_NOEXCEPT
{
// Check whether buffer is valid or it's the first process in the list
// (which is always System Idle Process).
return (buffer_->ImageName.Buffer != nullptr &&
buffer_->ImageName.Length) ||
prev_ == nullptr;
}
std::wstring GetName() const
{
// First process is always System Idle Process.
if (!prev_)
{
return {L"System Idle Process"};
}
auto const str_end =
std::find(buffer_->ImageName.Buffer,
buffer_->ImageName.Buffer + buffer_->ImageName.Length,
L'\0');
// SystemFullProcessInformation returns the full path rather than just the
// image name.
if (info_class_ == winternl::SystemFullProcessInformation)
{
auto const name_beg =
std::find(std::reverse_iterator<wchar_t*>(str_end),
std::reverse_iterator<wchar_t*>(buffer_->ImageName.Buffer),
L'\\');
return {name_beg.base(), str_end};
}
else
{
return {buffer_->ImageName.Buffer, str_end};
}
}
private:
winternl::SYSTEM_PROCESS_INFORMATION*
GetRealBuffer(winternl::SYSTEM_INFORMATION_CLASS info_class,
void* buffer) const HADESMEM_DETAIL_NOEXCEPT
{
if (info_class == winternl::SystemProcessInformation ||
info_class == winternl::SystemExtendedProcessInformation ||
info_class == winternl::SystemFullProcessInformation)
{
return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(buffer);
}
else if (info_class == winternl::SystemSessionProcessInformation)
{
return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(
static_cast<winternl::SYSTEM_SESSION_PROCESS_INFORMATION*>(buffer)
->Buffer);
}
else
{
HADESMEM_DETAIL_ASSERT(false);
return nullptr;
}
}
winternl::SYSTEM_PROCESS_INFORMATION* buffer_;
winternl::SYSTEM_PROCESS_INFORMATION* prev_;
winternl::SYSTEM_INFORMATION_CLASS info_class_;
bool unlinked_;
};
extern "C" NTSTATUS WINAPI NtQuerySystemInformationHk(
winternl::SYSTEM_INFORMATION_CLASS system_information_class,
PVOID system_information,
ULONG system_information_length,
PULONG return_length) HADESMEM_DETAIL_NOEXCEPT
{
hadesmem::detail::LastErrorPreserver last_error;
HADESMEM_DETAIL_TRACE_FORMAT_A("Args: [%d] [%p] [%u] [%p].",
system_information_class,
system_information,
system_information_length,
return_length);
auto& detour = GetNtQuerySystemInformationDetour();
auto const nt_query_system_information =
detour->GetTrampoline<decltype(&NtQuerySystemInformationHk)>();
last_error.Revert();
auto const ret = nt_query_system_information(system_information_class,
system_information,
system_information_length,
return_length);
last_error.Update();
HADESMEM_DETAIL_TRACE_FORMAT_A("Ret: [%ld].", ret);
// TODO: Handle SystemProcessIdInformation (88).
if (system_information_class != winternl::SystemProcessInformation &&
system_information_class != winternl::SystemExtendedProcessInformation &&
system_information_class != winternl::SystemSessionProcessInformation &&
system_information_class != winternl::SystemFullProcessInformation)
{
HADESMEM_DETAIL_TRACE_A("Unhandled information class.");
return ret;
}
if (!NT_SUCCESS(ret))
{
HADESMEM_DETAIL_TRACE_A("Trampoline returned failure.");
return ret;
}
try
{
HADESMEM_DETAIL_TRACE_A("Enumerating processes.");
for (SystemProcessInformationEnum process_info{system_information_class,
system_information};
process_info.Valid();
process_info.Advance())
{
if (process_info.HasName())
{
auto const process_name = process_info.GetName();
HADESMEM_DETAIL_TRACE_FORMAT_W(L"Name: [%s].", process_name.c_str());
if (process_name == L"hades.exe")
{
HADESMEM_DETAIL_TRACE_A("Unlinking process.");
process_info.Unlink();
}
}
else
{
HADESMEM_DETAIL_TRACE_A("WARNING! Invalid name.");
}
}
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
}
return ret;
}
}
void HookNtQuerySystemInformation()
{
hadesmem::Module const ntdll(GetThisProcess(), L"ntdll.dll");
auto const nt_query_system_information = hadesmem::FindProcedure(
GetThisProcess(), ntdll, "NtQuerySystemInformation");
auto const nt_query_system_information_ptr =
hadesmem::detail::UnionCast<void*>(nt_query_system_information);
auto const nt_query_system_information_hk =
hadesmem::detail::UnionCast<void*>(&NtQuerySystemInformationHk);
auto& detour = GetNtQuerySystemInformationDetour();
detour.reset(new hadesmem::PatchDetour(GetThisProcess(),
nt_query_system_information_ptr,
nt_query_system_information_hk));
detour->Apply();
HADESMEM_DETAIL_TRACE_A("NtQuerySystemInformationHk detoured.");
}
<commit_msg>* [Cerberus] Another note to self...<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#include <iterator>
#include <memory>
#include <string>
#include <windows.h>
#include <winnt.h>
#include <winternl.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/winternl.hpp>
#include <hadesmem/detail/last_error.hpp>
#include <hadesmem/find_procedure.hpp>
#include <hadesmem/module.hpp>
#include <hadesmem/patcher.hpp>
#include <hadesmem/process.hpp>
#include "main.hpp"
namespace winternl = hadesmem::detail::winternl;
namespace
{
std::unique_ptr<hadesmem::PatchDetour>& GetNtQuerySystemInformationDetour()
{
static std::unique_ptr<hadesmem::PatchDetour> detour;
return detour;
}
class SystemProcessInformationEnum
{
public:
explicit SystemProcessInformationEnum(
winternl::SYSTEM_INFORMATION_CLASS info_class,
void* buffer) HADESMEM_DETAIL_NOEXCEPT
: buffer_(GetRealBuffer(info_class, buffer)),
prev_(nullptr),
info_class_(info_class),
unlinked_(false)
{
HADESMEM_DETAIL_ASSERT(buffer_);
HADESMEM_DETAIL_ASSERT(
info_class == winternl::SystemProcessInformation ||
info_class == winternl::SystemExtendedProcessInformation ||
info_class == winternl::SystemSessionProcessInformation ||
info_class == winternl::SystemFullProcessInformation);
}
SystemProcessInformationEnum(SystemProcessInformationEnum const&) = delete;
SystemProcessInformationEnum& operator=(SystemProcessInformationEnum const&) =
delete;
void Advance() HADESMEM_DETAIL_NOEXCEPT
{
if (!unlinked_)
{
prev_ = buffer_;
}
unlinked_ = false;
if (buffer_->NextEntryOffset)
{
buffer_ = reinterpret_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(
reinterpret_cast<DWORD_PTR>(buffer_) + buffer_->NextEntryOffset);
}
else
{
buffer_ = nullptr;
}
}
bool Valid() const HADESMEM_DETAIL_NOEXCEPT
{
return buffer_ != nullptr;
}
// TODO: Handle case where we unlink all processes. This should be detected
// and reported to the caller so they can zero out the entire buffer, update
// the return length, or fail, etc. (Whatever should happen, needs more
// investigation).
void Unlink() HADESMEM_DETAIL_NOEXCEPT
{
HADESMEM_DETAIL_ASSERT(buffer_);
HADESMEM_DETAIL_ASSERT(!unlinked_);
if (prev_)
{
if (buffer_->NextEntryOffset)
{
// TODO: Investigate whether this is sufficient. For cases where callers
// actually use the extra information beyond the end of the base
// SYSTEM_PROCESS_INFORMATION struct, do they know exactly how many
// objects are in the array, or is it a linked list, or could we
// potentially be causing callers to read bogus data by simply
// pretending that the entry is longer than it actually is?
prev_->NextEntryOffset += buffer_->NextEntryOffset;
}
else
{
prev_->NextEntryOffset = 0UL;
}
unlinked_ = true;
}
else
{
// Unlinking the first process is unsupported.
// TODO: Fix this. Will also require reporting a new return length to
// the API (if appliciable) due to the buffer effectively changing size.
HADESMEM_DETAIL_ASSERT(false);
}
}
bool HasName() const HADESMEM_DETAIL_NOEXCEPT
{
// Check whether buffer is valid or it's the first process in the list
// (which is always System Idle Process).
return (buffer_->ImageName.Buffer != nullptr &&
buffer_->ImageName.Length) ||
prev_ == nullptr;
}
std::wstring GetName() const
{
// First process is always System Idle Process.
if (!prev_)
{
return {L"System Idle Process"};
}
auto const str_end =
std::find(buffer_->ImageName.Buffer,
buffer_->ImageName.Buffer + buffer_->ImageName.Length,
L'\0');
// SystemFullProcessInformation returns the full path rather than just the
// image name.
if (info_class_ == winternl::SystemFullProcessInformation)
{
auto const name_beg =
std::find(std::reverse_iterator<wchar_t*>(str_end),
std::reverse_iterator<wchar_t*>(buffer_->ImageName.Buffer),
L'\\');
return {name_beg.base(), str_end};
}
else
{
return {buffer_->ImageName.Buffer, str_end};
}
}
private:
winternl::SYSTEM_PROCESS_INFORMATION*
GetRealBuffer(winternl::SYSTEM_INFORMATION_CLASS info_class,
void* buffer) const HADESMEM_DETAIL_NOEXCEPT
{
if (info_class == winternl::SystemProcessInformation ||
info_class == winternl::SystemExtendedProcessInformation ||
info_class == winternl::SystemFullProcessInformation)
{
return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(buffer);
}
else if (info_class == winternl::SystemSessionProcessInformation)
{
return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(
static_cast<winternl::SYSTEM_SESSION_PROCESS_INFORMATION*>(buffer)
->Buffer);
}
else
{
HADESMEM_DETAIL_ASSERT(false);
return nullptr;
}
}
winternl::SYSTEM_PROCESS_INFORMATION* buffer_;
winternl::SYSTEM_PROCESS_INFORMATION* prev_;
winternl::SYSTEM_INFORMATION_CLASS info_class_;
bool unlinked_;
};
extern "C" NTSTATUS WINAPI NtQuerySystemInformationHk(
winternl::SYSTEM_INFORMATION_CLASS system_information_class,
PVOID system_information,
ULONG system_information_length,
PULONG return_length) HADESMEM_DETAIL_NOEXCEPT
{
hadesmem::detail::LastErrorPreserver last_error;
HADESMEM_DETAIL_TRACE_FORMAT_A("Args: [%d] [%p] [%u] [%p].",
system_information_class,
system_information,
system_information_length,
return_length);
auto& detour = GetNtQuerySystemInformationDetour();
auto const nt_query_system_information =
detour->GetTrampoline<decltype(&NtQuerySystemInformationHk)>();
last_error.Revert();
auto const ret = nt_query_system_information(system_information_class,
system_information,
system_information_length,
return_length);
last_error.Update();
HADESMEM_DETAIL_TRACE_FORMAT_A("Ret: [%ld].", ret);
// TODO: Handle SystemProcessIdInformation (88).
if (system_information_class != winternl::SystemProcessInformation &&
system_information_class != winternl::SystemExtendedProcessInformation &&
system_information_class != winternl::SystemSessionProcessInformation &&
system_information_class != winternl::SystemFullProcessInformation)
{
HADESMEM_DETAIL_TRACE_A("Unhandled information class.");
return ret;
}
if (!NT_SUCCESS(ret))
{
HADESMEM_DETAIL_TRACE_A("Trampoline returned failure.");
return ret;
}
try
{
HADESMEM_DETAIL_TRACE_A("Enumerating processes.");
for (SystemProcessInformationEnum process_info{system_information_class,
system_information};
process_info.Valid();
process_info.Advance())
{
if (process_info.HasName())
{
auto const process_name = process_info.GetName();
HADESMEM_DETAIL_TRACE_FORMAT_W(L"Name: [%s].", process_name.c_str());
if (process_name == L"hades.exe")
{
HADESMEM_DETAIL_TRACE_A("Unlinking process.");
process_info.Unlink();
}
}
else
{
HADESMEM_DETAIL_TRACE_A("WARNING! Invalid name.");
}
}
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
}
return ret;
}
}
void HookNtQuerySystemInformation()
{
hadesmem::Module const ntdll(GetThisProcess(), L"ntdll.dll");
auto const nt_query_system_information = hadesmem::FindProcedure(
GetThisProcess(), ntdll, "NtQuerySystemInformation");
auto const nt_query_system_information_ptr =
hadesmem::detail::UnionCast<void*>(nt_query_system_information);
auto const nt_query_system_information_hk =
hadesmem::detail::UnionCast<void*>(&NtQuerySystemInformationHk);
auto& detour = GetNtQuerySystemInformationDetour();
detour.reset(new hadesmem::PatchDetour(GetThisProcess(),
nt_query_system_information_ptr,
nt_query_system_information_hk));
detour->Apply();
HADESMEM_DETAIL_TRACE_A("NtQuerySystemInformationHk detoured.");
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Google
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <gtest/gtest.h>
#include <iostream>
#include "base/trie.hh"
#include "base/types.hh"
namespace {
static inline uint32_t *ptr(uintptr_t val)
{
return (uint32_t *)val;
}
} // anonymous namespace
class TrieTestData : public testing::Test
{
protected:
typedef Trie<Addr, uint32_t> TrieType;
TrieType trie;
};
TEST_F(TrieTestData, Empty)
{
EXPECT_EQ(trie.lookup(0x123456701234567), nullptr);
}
TEST_F(TrieTestData, SingleEntry)
{
trie.insert(0x0123456789abcdef, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x123456701234567), nullptr);
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(1));
}
TEST_F(TrieTestData, TwoOverlappingEntries)
{
trie.insert(0x0123456789abcdef, 40, ptr(1));
trie.insert(0x0123456789abcdef, 36, ptr(2));
EXPECT_EQ(trie.lookup(0x123456700000000), nullptr);
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(2));
}
TEST_F(TrieTestData, TwoOverlappingEntriesReversed)
{
trie.insert(0x0123456789abcdef, 36, ptr(2));
trie.insert(0x0123456789abcdef, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x123456700000000), nullptr);
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(2));
}
TEST_F(TrieTestData, TwoIndependentEntries)
{
trie.insert(0x0123456789abcdef, 40, ptr(2));
trie.insert(0x0123456776543210, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(2));
EXPECT_EQ(trie.lookup(0x0123456776000000), ptr(1));
EXPECT_EQ(trie.lookup(0x0123456700000000), nullptr);
}
TEST_F(TrieTestData, TwoEntries)
{
trie.insert(0x0123456789000000, 40, ptr(4));
trie.insert(0x0123000000000000, 40, ptr(1));
trie.insert(0x0123456780000000, 40, ptr(3));
trie.insert(0x0123456700000000, 40, ptr(2));
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1));
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(2));
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4));
}
TEST_F(TrieTestData, RemovingEntries)
{
TrieType::Handle node1, node2;
trie.insert(0x0123456789000000, 40, ptr(4));
trie.insert(0x0123000000000000, 40, ptr(1));
trie.insert(0x0123456780000000, 40, ptr(3));
node1 = trie.insert(0x0123456700000000, 40, ptr(2));
node2 = trie.insert(0x0123456700000000, 32, ptr(10));
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1));
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(10));
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(10));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(10));
trie.remove(node2);
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1));
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(2));
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4));
trie.remove(node1);
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1));
EXPECT_EQ(trie.lookup(0x0123456700000000), nullptr);
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4));
}
<commit_msg>tests: Plumb dumps of the test trie into the gtest macros.<commit_after>/*
* Copyright (c) 2012 Google
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <gtest/gtest.h>
#include <iostream>
#include <sstream>
#include <string>
#include "base/trie.hh"
#include "base/types.hh"
namespace {
static inline uint32_t *ptr(uintptr_t val)
{
return (uint32_t *)val;
}
} // anonymous namespace
class TrieTestData : public testing::Test
{
protected:
typedef Trie<Addr, uint32_t> TrieType;
TrieType trie;
std::string
dumpTrie()
{
std::stringstream ss;
trie.dump("test trie", ss);
return ss.str();
}
};
TEST_F(TrieTestData, Empty)
{
EXPECT_EQ(trie.lookup(0x123456701234567), nullptr) << dumpTrie();
}
TEST_F(TrieTestData, SingleEntry)
{
trie.insert(0x0123456789abcdef, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x123456701234567), nullptr) << dumpTrie();
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(1)) << dumpTrie();
}
TEST_F(TrieTestData, TwoOverlappingEntries)
{
trie.insert(0x0123456789abcdef, 40, ptr(1));
trie.insert(0x0123456789abcdef, 36, ptr(2));
EXPECT_EQ(trie.lookup(0x123456700000000), nullptr) << dumpTrie();
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(2)) << dumpTrie();
}
TEST_F(TrieTestData, TwoOverlappingEntriesReversed)
{
trie.insert(0x0123456789abcdef, 36, ptr(2));
trie.insert(0x0123456789abcdef, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x123456700000000), nullptr) << dumpTrie();
EXPECT_EQ(trie.lookup(0x123456789ab0000), ptr(2)) << dumpTrie();
}
TEST_F(TrieTestData, TwoIndependentEntries)
{
trie.insert(0x0123456789abcdef, 40, ptr(2));
trie.insert(0x0123456776543210, 40, ptr(1));
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(2)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456776000000), ptr(1)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456700000000), nullptr) << dumpTrie();
}
TEST_F(TrieTestData, TwoEntries)
{
trie.insert(0x0123456789000000, 40, ptr(4));
trie.insert(0x0123000000000000, 40, ptr(1));
trie.insert(0x0123456780000000, 40, ptr(3));
trie.insert(0x0123456700000000, 40, ptr(2));
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(2)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4)) << dumpTrie();
}
TEST_F(TrieTestData, RemovingEntries)
{
TrieType::Handle node1, node2;
trie.insert(0x0123456789000000, 40, ptr(4));
trie.insert(0x0123000000000000, 40, ptr(1));
trie.insert(0x0123456780000000, 40, ptr(3));
node1 = trie.insert(0x0123456700000000, 40, ptr(2));
node2 = trie.insert(0x0123456700000000, 32, ptr(10));
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(10)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(10)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(10)) << dumpTrie();
trie.remove(node2);
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456700000000), ptr(2)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4)) << dumpTrie();
trie.remove(node1);
EXPECT_EQ(trie.lookup(0x0123000000000000), ptr(1)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456700000000), nullptr) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456780000000), ptr(3)) << dumpTrie();
EXPECT_EQ(trie.lookup(0x0123456789000000), ptr(4)) << dumpTrie();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// The language menu consists of 3 parts (in this order):
//
// (1) XKB layout names and IME languages names. The size of the list is
// always >= 1.
// (2) IME properties. This list might be empty.
// (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME... (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//
namespace {
// Constants to specify the type of items in |model_|.
enum {
COMMAND_ID_LANGUAGES = 0, // US, Anthy, PinYin, ...
COMMAND_ID_IME_PROPERTIES, // Hiragana, Katakana, ...
COMMAND_ID_CONFIGURE_IME, // The "Configure IME..." button.
};
// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";
// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
const chromeos::InputLanguage& language, bool for_menu) {
std::string formatted = language.display_name;
if (formatted.empty()) {
formatted = language.id;
}
if (for_menu) {
switch (language.category) {
case chromeos::LANGUAGE_CATEGORY_XKB:
// TODO(yusukes): Use message catalog.
formatted += " (Layout)";
break;
case chromeos::LANGUAGE_CATEGORY_IME:
// TODO(yusukes): Use message catalog.
formatted += " (IME)";
break;
}
} else {
// For status area. Trim the string.
formatted = formatted.substr(0, kMaxLanguageNameLen);
// TODO(yusukes): Simple substr() does not work for non-ASCII string.
// TODO(yusukes): How can we ensure that the trimmed string does not
// overflow the area?
}
return formatted;
}
} // namespace
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton
LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
: MenuButton(NULL, std::wstring(), this, false),
language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
model_(NULL),
// Be aware that the constructor of |language_menu_| calls GetItemCount()
// in this class. Therefore, GetItemCount() have to return 0 when
// |model_| is NULL.
ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
host_(host) {
DCHECK(language_list_.get() && !language_list_->empty());
// Update the model
RebuildModel();
// Grab the real estate.
UpdateIcon(kSpacer);
// Display the default XKB name (usually "US").
const std::string name = FormatInputLanguage(language_list_->at(0), false);
UpdateIcon(UTF8ToWide(name));
LanguageLibrary::Get()->AddObserver(this);
}
LanguageMenuButton::~LanguageMenuButton() {
LanguageLibrary::Get()->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:
int LanguageMenuButton::GetCommandIdAt(int index) const {
return 0; // dummy
}
bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
// Menu content for the language button could change time by time.
return true;
}
bool LanguageMenuButton::GetAcceleratorAt(
int index, menus::Accelerator* accelerator) const {
// Views for Chromium OS does not support accelerators yet.
return false;
}
bool LanguageMenuButton::IsItemCheckedAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexIsInLanguageList(index)) {
const InputLanguage& language = language_list_->at(index);
return language == LanguageLibrary::Get()->current_language();
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).is_selection_item_checked;
}
// Separator(s) or the "Configure IME" button.
return false;
}
int LanguageMenuButton::GetGroupIdAt(int index) const {
DCHECK_GE(index, 0);
if (IndexIsInLanguageList(index)) {
return kRadioGroupLanguage;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).selection_item_id;
}
return kRadioGroupNone;
}
bool LanguageMenuButton::HasIcons() const {
// TODO(yusukes): Display IME icons.
return false;
}
bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
// TODO(yusukes): Display IME icons.
return false;
}
bool LanguageMenuButton::IsEnabledAt(int index) const {
// Just return true so all IMEs, XKB layouts, and IME properties could be
// clicked.
return true;
}
menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
// We don't use nested menus.
return NULL;
}
void LanguageMenuButton::HighlightChangedTo(int index) {
// Views for Chromium OS does not support this interface yet.
}
void LanguageMenuButton::MenuWillShow() {
// Views for Chromium OS does not support this interface yet.
}
int LanguageMenuButton::GetItemCount() const {
if (!model_.get()) {
// Model is not constructed yet. This means that LanguageMenuButton is
// being constructed. Return zero.
return 0;
}
return model_->GetItemCount();
}
menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
DCHECK_GE(index, 0);
if (IndexPointsToConfigureImeMenuItem(index)) {
return menus::MenuModel::TYPE_COMMAND; // "Configure IME"
}
if (IndexIsInLanguageList(index)) {
return menus::MenuModel::TYPE_RADIO;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (property_list.at(index).is_selection_item) {
return menus::MenuModel::TYPE_RADIO;
}
return menus::MenuModel::TYPE_COMMAND;
}
return menus::MenuModel::TYPE_SEPARATOR;
}
string16 LanguageMenuButton::GetLabelAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
// TODO(yusukes): Use message catalog.
return WideToUTF16(L"Configure IME...");
}
std::string name;
if (IndexIsInLanguageList(index)) {
name = FormatInputLanguage(language_list_->at(index), true);
} else if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
name = property_list.at(index).label;
}
return UTF8ToUTF16(name);
}
void LanguageMenuButton::ActivatedAt(int index) {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
host_->OpenButtonOptions(this);
return;
}
if (IndexIsInLanguageList(index)) {
// Inter-IME switching or IME-XKB switching.
const InputLanguage& language = language_list_->at(index);
LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
return;
}
if (GetPropertyIndex(index, &index)) {
// Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
const std::string key = property_list.at(index).key;
if (property_list.at(index).is_selection_item) {
// Radio button is clicked.
const int id = property_list.at(index).selection_item_id;
// First, deactivate all other properties in the same radio group.
for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
if (i != index && id == property_list.at(i).selection_item_id) {
LanguageLibrary::Get()->DeactivateImeProperty(
property_list.at(i).key);
}
}
// Then, activate the property clicked.
LanguageLibrary::Get()->ActivateImeProperty(key);
} else {
// Command button like "Switch to half punctuation mode" is clicked.
// We can always use "Deactivate" for command buttons.
LanguageLibrary::Get()->DeactivateImeProperty(key);
}
return;
}
// Separators are not clickable.
NOTREACHED();
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:
void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
RebuildModel();
language_menu_.Rebuild();
language_menu_.UpdateStates();
language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:
void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
const std::string name = FormatInputLanguage(obj->current_language(), false);
UpdateIcon(UTF8ToWide(name));
}
void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
RebuildModel();
}
void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
set_border(NULL);
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
SetText(name);
// TODO(yusukes): Show icon on the status area?
set_alignment(TextButton::ALIGN_RIGHT);
SchedulePaint();
}
void LanguageMenuButton::RebuildModel() {
model_.reset(new menus::SimpleMenuModel(NULL));
string16 dummy_label = UTF8ToUTF16("");
// Indicates if separator's needed before each section.
bool need_separator = false;
if (!language_list_->empty()) {
// We "abuse" the command_id and group_id arguments of AddRadioItem method.
// A COMMAND_ID_XXX enum value is passed as command_id, and array index of
// |language_list_| or |property_list| is passed as group_id.
for (size_t i = 0; i < language_list_->size(); ++i) {
model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
}
need_separator = true;
}
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (!property_list.empty()) {
if (need_separator)
model_->AddSeparator();
for (size_t i = 0; i < property_list.size(); ++i) {
model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
}
need_separator = true;
}
if (host_->ShouldOpenButtonOptions(this)) {
// Note: We use AddSeparator() for separators, and AddRadioItem() for all
// other items even if an item is not actually a radio item.
if (need_separator)
model_->AddSeparator();
model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
}
}
bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}
bool LanguageMenuButton::GetPropertyIndex(
int index, int* property_index) const {
DCHECK_GE(index, 0);
DCHECK(property_index);
DCHECK(model_.get());
if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
*property_index = model_->GetGroupIdAt(index);
return true;
}
return false;
}
bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}
// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?
} // namespace chromeos
<commit_msg>Remove obsolete TODOs. No code change.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// The language menu consists of 3 parts (in this order):
//
// (1) XKB layout names and IME languages names. The size of the list is
// always >= 1.
// (2) IME properties. This list might be empty.
// (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME... (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//
namespace {
// Constants to specify the type of items in |model_|.
enum {
COMMAND_ID_LANGUAGES = 0, // US, Anthy, PinYin, ...
COMMAND_ID_IME_PROPERTIES, // Hiragana, Katakana, ...
COMMAND_ID_CONFIGURE_IME, // The "Configure IME..." button.
};
// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";
// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
const chromeos::InputLanguage& language, bool for_menu) {
std::string formatted = language.display_name;
if (formatted.empty()) {
formatted = language.id;
}
if (for_menu) {
switch (language.category) {
case chromeos::LANGUAGE_CATEGORY_XKB:
// TODO(yusukes): Use message catalog.
formatted += " (Layout)";
break;
case chromeos::LANGUAGE_CATEGORY_IME:
// TODO(yusukes): Use message catalog.
formatted += " (IME)";
break;
}
} else {
// For status area. Trim the string.
formatted = formatted.substr(0, kMaxLanguageNameLen);
// TODO(yusukes): Simple substr() does not work for non-ASCII string.
// TODO(yusukes): How can we ensure that the trimmed string does not
// overflow the area?
}
return formatted;
}
} // namespace
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton
LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
: MenuButton(NULL, std::wstring(), this, false),
language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
model_(NULL),
// Be aware that the constructor of |language_menu_| calls GetItemCount()
// in this class. Therefore, GetItemCount() have to return 0 when
// |model_| is NULL.
ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
host_(host) {
DCHECK(language_list_.get() && !language_list_->empty());
// Update the model
RebuildModel();
// Grab the real estate.
UpdateIcon(kSpacer);
// Display the default XKB name (usually "US").
const std::string name = FormatInputLanguage(language_list_->at(0), false);
UpdateIcon(UTF8ToWide(name));
LanguageLibrary::Get()->AddObserver(this);
}
LanguageMenuButton::~LanguageMenuButton() {
LanguageLibrary::Get()->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:
int LanguageMenuButton::GetCommandIdAt(int index) const {
return 0; // dummy
}
bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
// Menu content for the language button could change time by time.
return true;
}
bool LanguageMenuButton::GetAcceleratorAt(
int index, menus::Accelerator* accelerator) const {
// Views for Chromium OS does not support accelerators yet.
return false;
}
bool LanguageMenuButton::IsItemCheckedAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexIsInLanguageList(index)) {
const InputLanguage& language = language_list_->at(index);
return language == LanguageLibrary::Get()->current_language();
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).is_selection_item_checked;
}
// Separator(s) or the "Configure IME" button.
return false;
}
int LanguageMenuButton::GetGroupIdAt(int index) const {
DCHECK_GE(index, 0);
if (IndexIsInLanguageList(index)) {
return kRadioGroupLanguage;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).selection_item_id;
}
return kRadioGroupNone;
}
bool LanguageMenuButton::HasIcons() const {
// We don't support IME nor keyboard icons on Chrome OS.
return false;
}
bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
return false;
}
bool LanguageMenuButton::IsEnabledAt(int index) const {
// Just return true so all IMEs, XKB layouts, and IME properties could be
// clicked.
return true;
}
menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
// We don't use nested menus.
return NULL;
}
void LanguageMenuButton::HighlightChangedTo(int index) {
// Views for Chromium OS does not support this interface yet.
}
void LanguageMenuButton::MenuWillShow() {
// Views for Chromium OS does not support this interface yet.
}
int LanguageMenuButton::GetItemCount() const {
if (!model_.get()) {
// Model is not constructed yet. This means that LanguageMenuButton is
// being constructed. Return zero.
return 0;
}
return model_->GetItemCount();
}
menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
DCHECK_GE(index, 0);
if (IndexPointsToConfigureImeMenuItem(index)) {
return menus::MenuModel::TYPE_COMMAND; // "Configure IME"
}
if (IndexIsInLanguageList(index)) {
return menus::MenuModel::TYPE_RADIO;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (property_list.at(index).is_selection_item) {
return menus::MenuModel::TYPE_RADIO;
}
return menus::MenuModel::TYPE_COMMAND;
}
return menus::MenuModel::TYPE_SEPARATOR;
}
string16 LanguageMenuButton::GetLabelAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
// TODO(yusukes): Use message catalog.
return WideToUTF16(L"Configure IME...");
}
std::string name;
if (IndexIsInLanguageList(index)) {
name = FormatInputLanguage(language_list_->at(index), true);
} else if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
name = property_list.at(index).label;
}
return UTF8ToUTF16(name);
}
void LanguageMenuButton::ActivatedAt(int index) {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
host_->OpenButtonOptions(this);
return;
}
if (IndexIsInLanguageList(index)) {
// Inter-IME switching or IME-XKB switching.
const InputLanguage& language = language_list_->at(index);
LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
return;
}
if (GetPropertyIndex(index, &index)) {
// Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
const std::string key = property_list.at(index).key;
if (property_list.at(index).is_selection_item) {
// Radio button is clicked.
const int id = property_list.at(index).selection_item_id;
// First, deactivate all other properties in the same radio group.
for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
if (i != index && id == property_list.at(i).selection_item_id) {
LanguageLibrary::Get()->DeactivateImeProperty(
property_list.at(i).key);
}
}
// Then, activate the property clicked.
LanguageLibrary::Get()->ActivateImeProperty(key);
} else {
// Command button like "Switch to half punctuation mode" is clicked.
// We can always use "Deactivate" for command buttons.
LanguageLibrary::Get()->DeactivateImeProperty(key);
}
return;
}
// Separators are not clickable.
NOTREACHED();
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:
void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
RebuildModel();
language_menu_.Rebuild();
language_menu_.UpdateStates();
language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:
void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
const std::string name = FormatInputLanguage(obj->current_language(), false);
UpdateIcon(UTF8ToWide(name));
}
void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
RebuildModel();
}
void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
set_border(NULL);
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
SetText(name);
set_alignment(TextButton::ALIGN_RIGHT);
SchedulePaint();
}
void LanguageMenuButton::RebuildModel() {
model_.reset(new menus::SimpleMenuModel(NULL));
string16 dummy_label = UTF8ToUTF16("");
// Indicates if separator's needed before each section.
bool need_separator = false;
if (!language_list_->empty()) {
// We "abuse" the command_id and group_id arguments of AddRadioItem method.
// A COMMAND_ID_XXX enum value is passed as command_id, and array index of
// |language_list_| or |property_list| is passed as group_id.
for (size_t i = 0; i < language_list_->size(); ++i) {
model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
}
need_separator = true;
}
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (!property_list.empty()) {
if (need_separator)
model_->AddSeparator();
for (size_t i = 0; i < property_list.size(); ++i) {
model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
}
need_separator = true;
}
if (host_->ShouldOpenButtonOptions(this)) {
// Note: We use AddSeparator() for separators, and AddRadioItem() for all
// other items even if an item is not actually a radio item.
if (need_separator)
model_->AddSeparator();
model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
}
}
bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}
bool LanguageMenuButton::GetPropertyIndex(
int index, int* property_index) const {
DCHECK_GE(index, 0);
DCHECK(property_index);
DCHECK(model_.get());
if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
*property_index = model_->GetGroupIdAt(index);
return true;
}
return false;
}
bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}
// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?
} // namespace chromeos
<|endoftext|>
|
<commit_before>/**
* \file HTTPClient.hxx - simple HTTP client engine for SimHear
*/
// Written by James Turner
//
// Copyright (C) 2013 James Turner <zakalawe@mac.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library 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.
//
#ifndef SG_HTTP_CLIENT_HXX
#define SG_HTTP_CLIENT_HXX
#include <simgear/io/HTTPRequest.hxx>
namespace simgear
{
namespace HTTP
{
// forward decls
class Connection;
class Client
{
public:
Client();
~Client();
void update(int waitTimeout = 0);
void makeRequest(const Request_ptr& r);
void setUserAgent(const std::string& ua);
void setProxy(const std::string& proxy, int port, const std::string& auth = "");
/**
* Specify the maximum permitted simultaneous connections
* (default value is 1)
*/
void setMaxConnections(unsigned int maxCons);
const std::string& userAgent() const;
const std::string& proxyHost() const;
const std::string& proxyAuth() const;
/**
* predicate, check if at least one connection is active, with at
* least one request active or queued.
*/
bool hasActiveRequests() const;
private:
void requestFinished(Connection* con);
friend class Connection;
friend class Request;
class ClientPrivate;
std::auto_ptr<ClientPrivate> d;
};
} // of namespace HTTP
} // of namespace simgear
#endif // of SG_HTTP_CLIENT_HXX
<commit_msg>Fix missing include for non-Mac<commit_after>/**
* \file HTTPClient.hxx - simple HTTP client engine for SimHear
*/
// Written by James Turner
//
// Copyright (C) 2013 James Turner <zakalawe@mac.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library 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.
//
#ifndef SG_HTTP_CLIENT_HXX
#define SG_HTTP_CLIENT_HXX
#include <memory> // for std::auto_ptr
#include <simgear/io/HTTPRequest.hxx>
namespace simgear
{
namespace HTTP
{
// forward decls
class Connection;
class Client
{
public:
Client();
~Client();
void update(int waitTimeout = 0);
void makeRequest(const Request_ptr& r);
void setUserAgent(const std::string& ua);
void setProxy(const std::string& proxy, int port, const std::string& auth = "");
/**
* Specify the maximum permitted simultaneous connections
* (default value is 1)
*/
void setMaxConnections(unsigned int maxCons);
const std::string& userAgent() const;
const std::string& proxyHost() const;
const std::string& proxyAuth() const;
/**
* predicate, check if at least one connection is active, with at
* least one request active or queued.
*/
bool hasActiveRequests() const;
private:
void requestFinished(Connection* con);
friend class Connection;
friend class Request;
class ClientPrivate;
std::auto_ptr<ClientPrivate> d;
};
} // of namespace HTTP
} // of namespace simgear
#endif // of SG_HTTP_CLIENT_HXX
<|endoftext|>
|
<commit_before>// Copyright (C) 2012 James Turner - zakalawe@mac.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library 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.
//
// adapted from the freealut sources, especially alutBufferData.c, alutLoader.c
// and alutCodec.c (freealut is also LGPL licensed)
#include "readwav.hxx"
#include <cassert>
#include <zlib.h> // for gzXXX functions
#include <simgear/misc/sg_path.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/misc/stdint.hxx>
#include <simgear/structure/exception.hxx>
namespace
{
class Buffer {
public:
ALvoid* data;
ALenum format;
ALsizei length;
ALfloat frequency;
SGPath path;
Buffer() : data(NULL), format(AL_NONE), length(0), frequency(0.0f) {}
~Buffer()
{
if (data) {
free(data);
}
}
};
ALenum formatConstruct(ALint numChannels, ALint bitsPerSample)
{
switch (numChannels)
{
case 1:
switch (bitsPerSample) {
case 8: return AL_FORMAT_MONO8;
case 16: return AL_FORMAT_MONO16;
}
break;
case 2:
switch (bitsPerSample) {
case 8: return AL_FORMAT_STEREO8;
case 16: return AL_FORMAT_STEREO16;
}
break;
}
return AL_NONE;
}
// function prototype for decoding audio data
typedef void Codec(Buffer* buf);
void codecLinear(Buffer* /*buf*/)
{
}
void codecPCM16 (Buffer* buf)
{
// always byte-swaps here; is this a good idea?
uint16_t *d = (uint16_t *) buf->data;
size_t i, l = buf->length / 2;
for (i = 0; i < l; i++) {
*d = sg_bswap_16(*d);
}
}
/*
* From: http://www.multimedia.cx/simpleaudio.html#tth_sEc6.1
*/
int16_t mulaw2linear (uint8_t mulawbyte)
{
static const int16_t exp_lut[8] = {
0, 132, 396, 924, 1980, 4092, 8316, 16764
};
int16_t sign, exponent, mantissa, sample;
mulawbyte = ~mulawbyte;
sign = (mulawbyte & 0x80);
exponent = (mulawbyte >> 4) & 0x07;
mantissa = mulawbyte & 0x0F;
sample = exp_lut[exponent] + (mantissa << (exponent + 3));
return sign ? -sample : sample;
}
void codecULaw (Buffer* b)
{
uint8_t *d = (uint8_t *) b->data;
size_t newLength = b->length * 2;
int16_t *buf = (int16_t *) malloc(newLength);
size_t i;
if (buf == NULL)
throw sg_exception("malloc failed decoing ULaw WAV file");
for (i = 0; i < b->length; i++) {
buf[i] = mulaw2linear(d[i]);
}
free(b->data);
b->data = buf;
b->length = newLength;
}
bool gzSkip(gzFile fd, int skipCount)
{
int r = gzseek(fd, skipCount, SEEK_CUR);
return (r >= 0);
}
const int32_t WAV_RIFF_4CC = 0x52494646; // 'RIFF'
const int32_t WAV_WAVE_4CC = 0x57415645; // 'WAVE'
const int32_t WAV_DATA_4CC = 0x64617461; // 'data'
const int32_t WAV_FORMAT_4CC = 0x666d7420; // 'fmt '
template<class T>
bool wavReadBE(gzFile fd, T& value)
{
if (gzread(fd, &value, sizeof(T)) != sizeof(T))
return false;
if (sgIsLittleEndian())
sgEndianSwap(&value);
return true;
}
template<class T>
bool wavReadLE(gzFile fd, T& value)
{
if (gzread(fd, &value, sizeof(T)) != sizeof(T))
return false;
if (sgIsBigEndian())
sgEndianSwap(&value);
return true;
}
void loadWavFile(gzFile fd, Buffer* b)
{
assert(b->data == NULL);
bool found_header = false;
uint32_t chunkLength;
int32_t magic;
uint16_t audioFormat;
uint16_t numChannels;
uint32_t samplesPerSecond;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
Codec *codec = codecLinear;
if (!wavReadBE(fd, magic))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic != WAV_RIFF_4CC) {
throw sg_io_exception("not a .wav file", b->path);
}
if (!wavReadLE(fd, chunkLength) || !wavReadBE(fd, magic))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic != WAV_WAVE_4CC) /* "WAVE" */
{
throw sg_io_exception("unrecognized WAV magic", b->path);
}
while (1) {
if (!wavReadBE(fd, magic) || !wavReadLE(fd, chunkLength))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic == WAV_FORMAT_4CC) /* "fmt " */
{
found_header = true;
if (chunkLength < 16) {
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if (!wavReadLE (fd, audioFormat) ||
!wavReadLE (fd, numChannels) ||
!wavReadLE (fd, samplesPerSecond) ||
!wavReadLE (fd, byteRate) ||
!wavReadLE (fd, blockAlign) ||
!wavReadLE (fd, bitsPerSample))
{
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if (!gzSkip(fd, chunkLength - 16))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
switch (audioFormat)
{
case 1: /* PCM */
codec = (bitsPerSample == 8 || sgIsLittleEndian()) ? codecLinear : codecPCM16;
break;
case 7: /* uLaw */
bitsPerSample *= 2; /* ToDo: ??? */
codec = codecULaw;
break;
default:
throw sg_io_exception("unsupported WAV encoding", b->path);
}
b->frequency = samplesPerSecond;
b->format = formatConstruct(numChannels, bitsPerSample);
} else if (magic == WAV_DATA_4CC) {
if (!found_header) {
/* ToDo: A bit wrong to check here, fmt chunk could come later... */
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
b->data = malloc(chunkLength);
b->length = chunkLength;
size_t read = gzread(fd, b->data, chunkLength);
if (read != chunkLength) {
throw sg_io_exception("insufficent data reading WAV file", b->path);
}
break;
} else {
if (!gzSkip(fd, chunkLength))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if ((chunkLength & 1) && !gzeof(fd) && !gzSkip(fd, 1))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
} // of file chunk parser loop
codec(b); // might throw if something really bad occurs
} // of loadWav function
} // of anonymous namespace
namespace simgear
{
ALvoid* loadWAVFromFile(const SGPath& path, ALenum& format, ALsizei& size, ALfloat& freqf)
{
if (!path.exists()) {
throw sg_io_exception("loadWAVFromFile: file not found", path);
}
Buffer b;
b.path = path;
gzFile fd;
fd = gzopen(path.c_str(), "rb");
if (!fd) {
throw sg_io_exception("loadWAVFromFile: unable to open file", path);
}
loadWavFile(fd, &b);
ALvoid* data = b.data;
b.data = NULL; // don't free when Buffer does out of scope
format = b.format;
size = b.length;
freqf = b.frequency;
gzclose(fd);
return data;
}
ALuint createBufferFromFile(const SGPath& path)
{
ALenum format;
ALsizei size;
ALfloat sampleFrequency;
ALvoid* data = loadWAVFromFile(path, format, size, sampleFrequency);
assert(data);
ALuint buffer;
alGenBuffers(1, &buffer);
if (alGetError() != AL_NO_ERROR) {
free(data);
throw sg_io_exception("OpenAL buffer allocation failed", sg_location(path.str()));
}
alBufferData (buffer, format, data, size, (ALsizei) sampleFrequency);
if (alGetError() != AL_NO_ERROR) {
alDeleteBuffers(1, &buffer);
free(data);
throw sg_io_exception("OpenAL setting buffer data failed", sg_location(path.str()));
}
return buffer;
}
} // of namespace simgear
<commit_msg>Unbreak Linux: malloc() needs <cstdlib><commit_after>// Copyright (C) 2012 James Turner - zakalawe@mac.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library 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.
//
// adapted from the freealut sources, especially alutBufferData.c, alutLoader.c
// and alutCodec.c (freealut is also LGPL licensed)
#include "readwav.hxx"
#include <cassert>
#include <cstdlib>
#include <zlib.h> // for gzXXX functions
#include <simgear/misc/sg_path.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/misc/stdint.hxx>
#include <simgear/structure/exception.hxx>
namespace
{
class Buffer {
public:
ALvoid* data;
ALenum format;
ALsizei length;
ALfloat frequency;
SGPath path;
Buffer() : data(NULL), format(AL_NONE), length(0), frequency(0.0f) {}
~Buffer()
{
if (data) {
free(data);
}
}
};
ALenum formatConstruct(ALint numChannels, ALint bitsPerSample)
{
switch (numChannels)
{
case 1:
switch (bitsPerSample) {
case 8: return AL_FORMAT_MONO8;
case 16: return AL_FORMAT_MONO16;
}
break;
case 2:
switch (bitsPerSample) {
case 8: return AL_FORMAT_STEREO8;
case 16: return AL_FORMAT_STEREO16;
}
break;
}
return AL_NONE;
}
// function prototype for decoding audio data
typedef void Codec(Buffer* buf);
void codecLinear(Buffer* /*buf*/)
{
}
void codecPCM16 (Buffer* buf)
{
// always byte-swaps here; is this a good idea?
uint16_t *d = (uint16_t *) buf->data;
size_t i, l = buf->length / 2;
for (i = 0; i < l; i++) {
*d = sg_bswap_16(*d);
}
}
/*
* From: http://www.multimedia.cx/simpleaudio.html#tth_sEc6.1
*/
int16_t mulaw2linear (uint8_t mulawbyte)
{
static const int16_t exp_lut[8] = {
0, 132, 396, 924, 1980, 4092, 8316, 16764
};
int16_t sign, exponent, mantissa, sample;
mulawbyte = ~mulawbyte;
sign = (mulawbyte & 0x80);
exponent = (mulawbyte >> 4) & 0x07;
mantissa = mulawbyte & 0x0F;
sample = exp_lut[exponent] + (mantissa << (exponent + 3));
return sign ? -sample : sample;
}
void codecULaw (Buffer* b)
{
uint8_t *d = (uint8_t *) b->data;
size_t newLength = b->length * 2;
int16_t *buf = (int16_t *) malloc(newLength);
size_t i;
if (buf == NULL)
throw sg_exception("malloc failed decoing ULaw WAV file");
for (i = 0; i < b->length; i++) {
buf[i] = mulaw2linear(d[i]);
}
free(b->data);
b->data = buf;
b->length = newLength;
}
bool gzSkip(gzFile fd, int skipCount)
{
int r = gzseek(fd, skipCount, SEEK_CUR);
return (r >= 0);
}
const int32_t WAV_RIFF_4CC = 0x52494646; // 'RIFF'
const int32_t WAV_WAVE_4CC = 0x57415645; // 'WAVE'
const int32_t WAV_DATA_4CC = 0x64617461; // 'data'
const int32_t WAV_FORMAT_4CC = 0x666d7420; // 'fmt '
template<class T>
bool wavReadBE(gzFile fd, T& value)
{
if (gzread(fd, &value, sizeof(T)) != sizeof(T))
return false;
if (sgIsLittleEndian())
sgEndianSwap(&value);
return true;
}
template<class T>
bool wavReadLE(gzFile fd, T& value)
{
if (gzread(fd, &value, sizeof(T)) != sizeof(T))
return false;
if (sgIsBigEndian())
sgEndianSwap(&value);
return true;
}
void loadWavFile(gzFile fd, Buffer* b)
{
assert(b->data == NULL);
bool found_header = false;
uint32_t chunkLength;
int32_t magic;
uint16_t audioFormat;
uint16_t numChannels;
uint32_t samplesPerSecond;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
Codec *codec = codecLinear;
if (!wavReadBE(fd, magic))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic != WAV_RIFF_4CC) {
throw sg_io_exception("not a .wav file", b->path);
}
if (!wavReadLE(fd, chunkLength) || !wavReadBE(fd, magic))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic != WAV_WAVE_4CC) /* "WAVE" */
{
throw sg_io_exception("unrecognized WAV magic", b->path);
}
while (1) {
if (!wavReadBE(fd, magic) || !wavReadLE(fd, chunkLength))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
if (magic == WAV_FORMAT_4CC) /* "fmt " */
{
found_header = true;
if (chunkLength < 16) {
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if (!wavReadLE (fd, audioFormat) ||
!wavReadLE (fd, numChannels) ||
!wavReadLE (fd, samplesPerSecond) ||
!wavReadLE (fd, byteRate) ||
!wavReadLE (fd, blockAlign) ||
!wavReadLE (fd, bitsPerSample))
{
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if (!gzSkip(fd, chunkLength - 16))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
switch (audioFormat)
{
case 1: /* PCM */
codec = (bitsPerSample == 8 || sgIsLittleEndian()) ? codecLinear : codecPCM16;
break;
case 7: /* uLaw */
bitsPerSample *= 2; /* ToDo: ??? */
codec = codecULaw;
break;
default:
throw sg_io_exception("unsupported WAV encoding", b->path);
}
b->frequency = samplesPerSecond;
b->format = formatConstruct(numChannels, bitsPerSample);
} else if (magic == WAV_DATA_4CC) {
if (!found_header) {
/* ToDo: A bit wrong to check here, fmt chunk could come later... */
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
b->data = malloc(chunkLength);
b->length = chunkLength;
size_t read = gzread(fd, b->data, chunkLength);
if (read != chunkLength) {
throw sg_io_exception("insufficent data reading WAV file", b->path);
}
break;
} else {
if (!gzSkip(fd, chunkLength))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
}
if ((chunkLength & 1) && !gzeof(fd) && !gzSkip(fd, 1))
throw sg_io_exception("corrupt or truncated WAV data", b->path);
} // of file chunk parser loop
codec(b); // might throw if something really bad occurs
} // of loadWav function
} // of anonymous namespace
namespace simgear
{
ALvoid* loadWAVFromFile(const SGPath& path, ALenum& format, ALsizei& size, ALfloat& freqf)
{
if (!path.exists()) {
throw sg_io_exception("loadWAVFromFile: file not found", path);
}
Buffer b;
b.path = path;
gzFile fd;
fd = gzopen(path.c_str(), "rb");
if (!fd) {
throw sg_io_exception("loadWAVFromFile: unable to open file", path);
}
loadWavFile(fd, &b);
ALvoid* data = b.data;
b.data = NULL; // don't free when Buffer does out of scope
format = b.format;
size = b.length;
freqf = b.frequency;
gzclose(fd);
return data;
}
ALuint createBufferFromFile(const SGPath& path)
{
ALenum format;
ALsizei size;
ALfloat sampleFrequency;
ALvoid* data = loadWAVFromFile(path, format, size, sampleFrequency);
assert(data);
ALuint buffer;
alGenBuffers(1, &buffer);
if (alGetError() != AL_NO_ERROR) {
free(data);
throw sg_io_exception("OpenAL buffer allocation failed", sg_location(path.str()));
}
alBufferData (buffer, format, data, size, (ALsizei) sampleFrequency);
if (alGetError() != AL_NO_ERROR) {
alDeleteBuffers(1, &buffer);
free(data);
throw sg_io_exception("OpenAL setting buffer data failed", sg_location(path.str()));
}
return buffer;
}
} // of namespace simgear
<|endoftext|>
|
<commit_before>// Copyright (c) 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/browser/extensions/extension_devtools_bridge.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/extensions/extension_devtools_events.h"
#include "chrome/browser/extensions/extension_devtools_manager.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/devtools_messages.h"
#include "content/browser/tab_contents/tab_contents.h"
ExtensionDevToolsBridge::ExtensionDevToolsBridge(int tab_id,
Profile* profile)
: tab_id_(tab_id),
profile_(profile),
on_page_event_name_(
ExtensionDevToolsEvents::OnPageEventNameForTab(tab_id)),
on_tab_close_event_name_(
ExtensionDevToolsEvents::OnTabCloseEventNameForTab(tab_id)) {
extension_devtools_manager_ = profile_->GetExtensionDevToolsManager();
DCHECK(extension_devtools_manager_.get());
}
ExtensionDevToolsBridge::~ExtensionDevToolsBridge() {
}
static std::string FormatDevToolsMessage(int seq,
const std::string& domain,
const std::string& command,
DictionaryValue* arguments) {
DictionaryValue message;
message.SetInteger("seq", seq);
message.SetString("domain", domain);
message.SetString("command", command);
message.Set("arguments", arguments);
std::string json;
base::JSONWriter::Write(&message, false, &json);
return json;
}
bool ExtensionDevToolsBridge::RegisterAsDevToolsClientHost() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
Browser* browser;
TabStripModel* tab_strip;
TabContentsWrapper* contents;
int tab_index;
if (ExtensionTabUtil::GetTabById(tab_id_, profile_, true,
&browser, &tab_strip,
&contents, &tab_index)) {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
if (devtools_manager->GetDevToolsClientHostFor(contents->
render_view_host()) != NULL)
return false;
devtools_manager->RegisterDevToolsClientHostFor(
contents->render_view_host(), this);
// Following messages depend on inspector protocol that is not yet
// finalized.
// 1. Set injected script content.
DictionaryValue* arguments = new DictionaryValue();
arguments->SetString("scriptSource", "'{}'");
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_DispatchOnInspectorBackend(
FormatDevToolsMessage(0,
"Inspector",
"setInjectedScriptSource",
arguments)));
// 2. Report front-end is loaded.
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_FrontendLoaded());
// 3. Do not break on exceptions.
arguments = new DictionaryValue();
arguments->SetInteger("pauseOnExceptionsState", 0);
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_DispatchOnInspectorBackend(
FormatDevToolsMessage(1,
"Debugger",
"setPauseOnExceptionsState",
arguments)));
// 4. Start timeline profiler.
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_DispatchOnInspectorBackend(
FormatDevToolsMessage(2,
"Inspector",
"startTimelineProfiler",
new DictionaryValue())));
return true;
}
return false;
}
void ExtensionDevToolsBridge::UnregisterAsDevToolsClientHost() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
NotifyCloseListener();
}
// If the tab we are looking at is going away then we fire a closing event at
// the extension.
void ExtensionDevToolsBridge::InspectedTabClosing() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
// TODO(knorton): Remove this event in favor of the standard tabs.onRemoved
// event in extensions.
std::string json("[{}]");
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
on_tab_close_event_name_, json, profile_, GURL());
// This may result in this object being destroyed.
extension_devtools_manager_->BridgeClosingForTab(tab_id_);
}
void ExtensionDevToolsBridge::SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(ExtensionDevToolsBridge, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,
OnDispatchOnInspectorFrontend);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void ExtensionDevToolsBridge::TabReplaced(TabContentsWrapper* new_tab) {
DCHECK_EQ(profile_, new_tab->profile());
// We don't update the tab id as it needs to remain the same so that we can
// properly unregister.
}
void ExtensionDevToolsBridge::OnDispatchOnInspectorFrontend(
const std::string& data) {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
std::string json = base::StringPrintf("[%s]", data.c_str());
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
on_page_event_name_, json, profile_, GURL());
}
<commit_msg>Updates special case Speed Tracer code after inspector protocol changes. Original code review: http://codereview.chromium.org/6594124/<commit_after>// Copyright (c) 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/browser/extensions/extension_devtools_bridge.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/extensions/extension_devtools_events.h"
#include "chrome/browser/extensions/extension_devtools_manager.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/devtools_messages.h"
#include "content/browser/tab_contents/tab_contents.h"
ExtensionDevToolsBridge::ExtensionDevToolsBridge(int tab_id,
Profile* profile)
: tab_id_(tab_id),
profile_(profile),
on_page_event_name_(
ExtensionDevToolsEvents::OnPageEventNameForTab(tab_id)),
on_tab_close_event_name_(
ExtensionDevToolsEvents::OnTabCloseEventNameForTab(tab_id)) {
extension_devtools_manager_ = profile_->GetExtensionDevToolsManager();
DCHECK(extension_devtools_manager_.get());
}
ExtensionDevToolsBridge::~ExtensionDevToolsBridge() {
}
static std::string FormatDevToolsMessage(int seq,
const std::string& domain,
const std::string& command,
DictionaryValue* arguments) {
DictionaryValue message;
message.SetInteger("seq", seq);
message.SetString("domain", domain);
message.SetString("command", command);
message.Set("arguments", arguments);
std::string json;
base::JSONWriter::Write(&message, false, &json);
return json;
}
bool ExtensionDevToolsBridge::RegisterAsDevToolsClientHost() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
Browser* browser;
TabStripModel* tab_strip;
TabContentsWrapper* contents;
int tab_index;
if (ExtensionTabUtil::GetTabById(tab_id_, profile_, true,
&browser, &tab_strip,
&contents, &tab_index)) {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
if (devtools_manager->GetDevToolsClientHostFor(contents->
render_view_host()) != NULL)
return false;
devtools_manager->RegisterDevToolsClientHostFor(
contents->render_view_host(), this);
// Following messages depend on inspector protocol that is not yet
// finalized.
// 1. Report front-end is loaded.
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_FrontendLoaded());
// 2. Start timeline profiler.
devtools_manager->ForwardToDevToolsAgent(
this,
DevToolsAgentMsg_DispatchOnInspectorBackend(
FormatDevToolsMessage(2,
"Timeline",
"start",
new DictionaryValue())));
return true;
}
return false;
}
void ExtensionDevToolsBridge::UnregisterAsDevToolsClientHost() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
NotifyCloseListener();
}
// If the tab we are looking at is going away then we fire a closing event at
// the extension.
void ExtensionDevToolsBridge::InspectedTabClosing() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
// TODO(knorton): Remove this event in favor of the standard tabs.onRemoved
// event in extensions.
std::string json("[{}]");
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
on_tab_close_event_name_, json, profile_, GURL());
// This may result in this object being destroyed.
extension_devtools_manager_->BridgeClosingForTab(tab_id_);
}
void ExtensionDevToolsBridge::SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(ExtensionDevToolsBridge, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,
OnDispatchOnInspectorFrontend);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void ExtensionDevToolsBridge::TabReplaced(TabContentsWrapper* new_tab) {
DCHECK_EQ(profile_, new_tab->profile());
// We don't update the tab id as it needs to remain the same so that we can
// properly unregister.
}
void ExtensionDevToolsBridge::OnDispatchOnInspectorFrontend(
const std::string& data) {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
std::string json = base::StringPrintf("[%s]", data.c_str());
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
on_page_event_name_, json, profile_, GURL());
}
<|endoftext|>
|
<commit_before>/*
* Ubitrack - Library for Ubiquitous Tracking
* Copyright 2006, Technische Universitaet Muenchen, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of individual
* contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
#include "GlobFiles.h"
#include <log4cpp/Category.hh>
#include <boost/regex.hpp>
#include <algorithm>
namespace Ubitrack { namespace Util {
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Util.GlobFiles" ) );
void globFiles( const std::string& directory, const std::string & patternString, std::list< boost::filesystem::path >& files, bool globDirectories)
{
boost::filesystem::path testPath( directory );
if ( boost::filesystem::is_directory( testPath ) && boost::filesystem::exists( testPath ) )
{
boost::regex ext( patternString.c_str() );
// iterate directory
boost::filesystem::directory_iterator dirEnd;
for ( boost::filesystem::directory_iterator it( testPath ); it != dirEnd; it++ )
{
#ifdef BOOST_FILESYSTEM_I18N
boost::filesystem::path p( it->path() );
#else
boost::filesystem::path p( *it );
#endif
// check for files with suitable extension
if ( boost::filesystem::exists( p ) && ! boost::filesystem::is_directory( p ) && boost::regex_match( p.filename().string(), ext ) )
{
LOG4CPP_TRACE( logger, "Adding file " << p << " to list" );
files.push_back( p );
}
// glob directories, if desired
else if ( globDirectories && boost::filesystem::exists( p ) && boost::filesystem::is_directory( p ) )
{
files.push_back( p );
}
}
// sort, since directory iteration is not ordered on some file systems
files.sort();
LOG4CPP_DEBUG( logger, "Sorted list of files" );
for ( std::list< boost::filesystem::path >::iterator iter = files.begin(); iter != files.end(); iter ++ )
{
LOG4CPP_DEBUG( logger, *iter );
}
}
else if ( boost::filesystem::exists( testPath ) ) {
files.push_back( testPath );
}
else {
UBITRACK_THROW( "Invalid path specified" );
}
if ( files.size() == 0 ) {
UBITRACK_THROW( "No suitable files found at the specified location" );
}
}
void globFiles( const std::string& directory, const enum FilePattern pattern, std::list< boost::filesystem::path >& files )
{
std::string patternString = "";
if ( pattern == PATTERN_DIRECTORIES )
globFiles ( directory, patternString, files, true);
else {
if ( pattern == PATTERN_OPENCV_IMAGE_FILES )
patternString = ".*\\.(jpg|JPG|png|PNG|bmp|BMP)";
else if ( pattern == PATTERN_UBITRACK_CALIBRATION_FILES )
patternString = ".*\\.(cal)";
globFiles ( directory, patternString, files, false);
}
}
} } // namespace Ubitrack::Util
<commit_msg>windows/linux filesystem<commit_after>/*
* Ubitrack - Library for Ubiquitous Tracking
* Copyright 2006, Technische Universitaet Muenchen, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of individual
* contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
#include "GlobFiles.h"
#include <log4cpp/Category.hh>
#include <boost/regex.hpp>
#include <algorithm>
namespace Ubitrack { namespace Util {
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Util.GlobFiles" ) );
void globFiles( const std::string& directory, const std::string & patternString, std::list< boost::filesystem::path >& files, bool globDirectories)
{
boost::filesystem::path testPath( directory );
if ( boost::filesystem::is_directory( testPath ) && boost::filesystem::exists( testPath ) )
{
boost::regex ext( patternString.c_str() );
// iterate directory
boost::filesystem::directory_iterator dirEnd;
for ( boost::filesystem::directory_iterator it( testPath ); it != dirEnd; it++ )
{
#ifdef BOOST_FILESYSTEM_I18N
boost::filesystem::path p( it->path() );
#else
boost::filesystem::path p( *it );
#endif
// check for files with suitable extension
#ifdef BOOST_FILESYSTEM_I18N
if ( boost::filesystem::exists( p ) && ! boost::filesystem::is_directory( p ) && boost::regex_match( p.filename().string(), ext ) )
#else
if ( boost::filesystem::exists( p ) && ! boost::filesystem::is_directory( p ) && boost::regex_match( p.filename(), ext ) )
#endif
{
LOG4CPP_TRACE( logger, "Adding file " << p << " to list" );
files.push_back( p );
}
// glob directories, if desired
else if ( globDirectories && boost::filesystem::exists( p ) && boost::filesystem::is_directory( p ) )
{
files.push_back( p );
}
}
// sort, since directory iteration is not ordered on some file systems
files.sort();
LOG4CPP_DEBUG( logger, "Sorted list of files" );
for ( std::list< boost::filesystem::path >::iterator iter = files.begin(); iter != files.end(); iter ++ )
{
LOG4CPP_DEBUG( logger, *iter );
}
}
else if ( boost::filesystem::exists( testPath ) ) {
files.push_back( testPath );
}
else {
UBITRACK_THROW( "Invalid path specified" );
}
if ( files.size() == 0 ) {
UBITRACK_THROW( "No suitable files found at the specified location" );
}
}
void globFiles( const std::string& directory, const enum FilePattern pattern, std::list< boost::filesystem::path >& files )
{
std::string patternString = "";
if ( pattern == PATTERN_DIRECTORIES )
globFiles ( directory, patternString, files, true);
else {
if ( pattern == PATTERN_OPENCV_IMAGE_FILES )
patternString = ".*\\.(jpg|JPG|png|PNG|bmp|BMP)";
else if ( pattern == PATTERN_UBITRACK_CALIBRATION_FILES )
patternString = ".*\\.(cal)";
globFiles ( directory, patternString, files, false);
}
}
} } // namespace Ubitrack::Util
<|endoftext|>
|
<commit_before>/* This file is part of the Tomographer project, which is distributed under the
* terms of the MIT license.
*
* The MIT License (MIT)
*
* Copyright (c) 2015 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** \mainpage %Tomographer C++ Framework: API Documentation
*
* The <a href="https://github.com/Tomographer/tomographer" target="_blank">%Tomographer
* C++ Framework</a> groups a set of classes and functions which allow to reliably analyze
* data from quantum experiments.
*
* <h2>%Tomographer's Components</h2>
*
* The classes and routines of the project belong to several categories:
*
* <h3>Tools</h3>
*
* These are basic tools and utilities:
*
* - most tools, e.g. C++ language utilities and matrix utilities, are located in the
* namespace \ref Tomographer::Tools;
*
* - \ref Tomographer::MAT provides a set of routines to read data from MATLAB files
* (based on the <a href="http://matio.sourceforge.net/">MatIO</a> library);
*
* - %Tomographer provides a lightweight mechanism for logging messages. See \ref
* pageLoggers;
*
* - Some more utilities are provided in \ref Tomographer::SolveCLyap and \ref
* Tomographer::SphCoords.
*
* <h3>Specifying the Quantum Tomography Problem</h3>
*
* A quantum tomography setting with measurement results is specified as following in our
* generic framework:
*
* - A type complying with the \ref pageInterfaceMatrQ specifies which C++ types to use to
* store a density matrix and parameterizations of it. For the moment this should be a
* \ref Tomographer::MatrQ instance.
*
* - A type implementing the \ref pageInterfaceTomoProblem stores the experimental data
* and is responsible for calculating the loglikelihood function. For the moment, you
* should use \ref Tomographer::IndepMeasTomoProblem.
*
* \note These type interfaces above might change in the future.
*
* <h3>Running the Metropolis-Hastings Random Walk</h3>
*
* - The \ref Tomographer::MHRandomWalk takes care of running a Metropolis-Hastings random
* walk. You need to give it a specification of the random walk parameters, including
* what the state space is, the jump function, starting point, step size, etc. in the
* form of a type implementing the \ref pageInterfaceMHWalker.
*
* - The \ref Tomographer::DMStateSpaceLLHMHWalker is a type implementing the \ref
* pageInterfaceMHWalker, which is capable of running a random walk on the space of
* quantum states represented by dense C++ Eigen matrices, and using the distribution
* proportional to the loglikelihood function on the Hilbert-Schmidt measure.
*
* - While running the random walk, you'll want to collect some form of statistics. This
* is done with objects which comply with the \ref pageInterfaceMHRWStatsCollector. For
* example, see \ref Tomographer::ValueHistogramMHRWStatsCollector and \ref
* Tomographer::ValueHistogramWithBinningMHRWStatsCollector.
*
* <h3>Multiprocessing: Running Tasks in Parallel</h3>
*
* - An abstract multiprocessing framework is specified using a set of interfaces, see
* \ref pageTaskManagerDispatcher. This requires on one hand an implementation of a
* multiprocessing environment, and on the other hand a specification of which tasks are
* to be run.
*
* - Classes in the \ref Tomographer::MultiProc::OMP namespace are an implementation of a
* multiprocessing environment using <a href="https://en.wikipedia.org/wiki/OpenMP"
* target="_blank">OpenMP</a>. This dispatches the tasks over several threads (on a
* same machine).
*
* - The \ref Tomographer::MHRWTasks namespace groups a set of classes which may be used
* to specify tasks to run which consist of abstract Metropolis-Hastings random
* walks.
*
*
* <h2>Documentation Pages</h2>
*
* <h3>Important Namespaces</h3>
*
* - \ref Tomographer — base %Tomographer namespace
* - \ref Tomographer::Tools — namespace for various tools
* - Additional tools are available in selected namespaces. See the \htmlonly <a href="namespaces.html">List of Namespaces</a>.\endhtmlonly \latexonly List of Namespaces.\endlatexonly
*
* <h3>Specific Topics</h3>
*
* - \subpage pageTypeInterfaces
* - \subpage pageTheory
* - \subpage pageParams
* - \subpage pageLoggers
*
* <h3>Other Specific Resources</h3>
*
* - \subpage pageDebugging
*/
<commit_msg>doc update<commit_after>/* This file is part of the Tomographer project, which is distributed under the
* terms of the MIT license.
*
* The MIT License (MIT)
*
* Copyright (c) 2015 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** \mainpage %Tomographer C++ Framework: API Documentation
*
* The <a href="https://github.com/Tomographer/tomographer" target="_blank">%Tomographer
* C++ Framework</a> groups a set of classes and functions which allow to reliably analyze
* data from quantum experiments. These serve in particular as components for the tomorun
* executable program.
*
* <h2>%Tomographer's Components</h2>
*
* The classes and routines of the project belong to several categories:
*
* <h3>Tools</h3>
*
* These are basic tools and utilities:
*
* - most tools, e.g. C++ language utilities and matrix utilities, are located in the
* namespace \ref Tomographer::Tools;
*
* - \ref Tomographer::MAT provides a set of routines to read data from MATLAB files
* (based on the <a href="http://matio.sourceforge.net/">MatIO</a> library);
*
* - %Tomographer provides a lightweight mechanism for logging messages. See \ref
* pageLoggers;
*
* - Some more utilities are provided in \ref Tomographer::SolveCLyap and \ref
* Tomographer::SphCoords.
*
* <h3>Specifying the Quantum Tomography Problem</h3>
*
* A quantum tomography setting with measurement results is specified as following in our
* generic framework:
*
* - A type complying with the \ref pageInterfaceMatrQ specifies which C++ types to use to
* store a density matrix and parameterizations of it. For the moment this should be a
* \ref Tomographer::MatrQ instance.
*
* - A type implementing the \ref pageInterfaceTomoProblem stores the experimental data
* and is responsible for calculating the loglikelihood function. For the moment, you
* should use \ref Tomographer::IndepMeasTomoProblem.
*
* \note These type interfaces above might change in the future.
*
* <h3>Running the Metropolis-Hastings Random Walk</h3>
*
* - The \ref Tomographer::MHRandomWalk takes care of running a Metropolis-Hastings random
* walk. You need to give it a specification of the random walk parameters, including
* what the state space is, the jump function, starting point, step size, etc. in the
* form of a type implementing the \ref pageInterfaceMHWalker.
*
* - The \ref Tomographer::DMStateSpaceLLHMHWalker is a type implementing the \ref
* pageInterfaceMHWalker, which is capable of running a random walk on the space of
* quantum states represented by dense C++ Eigen matrices, and using the distribution
* proportional to the loglikelihood function on the Hilbert-Schmidt measure.
*
* - While running the random walk, you'll want to collect some form of statistics. This
* is done with objects which comply with the \ref pageInterfaceMHRWStatsCollector. For
* example, see \ref Tomographer::ValueHistogramMHRWStatsCollector and \ref
* Tomographer::ValueHistogramWithBinningMHRWStatsCollector.
*
* <h3>Multiprocessing: Running Tasks in Parallel</h3>
*
* - An abstract multiprocessing framework is specified using a set of interfaces, see
* \ref pageTaskManagerDispatcher. This requires on one hand an implementation of a
* multiprocessing environment, and on the other hand a specification of which tasks are
* to be run.
*
* - Classes in the \ref Tomographer::MultiProc::OMP namespace are an implementation of a
* multiprocessing environment using <a href="https://en.wikipedia.org/wiki/OpenMP"
* target="_blank">OpenMP</a>. This dispatches the tasks over several threads (on a
* same machine).
*
* - The \ref Tomographer::MHRWTasks namespace groups a set of classes which may be used
* to specify tasks to run which consist of abstract Metropolis-Hastings random
* walks.
*
*
* <h2>Documentation Pages</h2>
*
* <h3>Important Namespaces</h3>
*
* - \ref Tomographer — base %Tomographer namespace
* - \ref Tomographer::Tools — namespace for various tools
* - Additional tools are available in selected namespaces. See the \htmlonly <a href="namespaces.html">List of Namespaces</a>.\endhtmlonly \latexonly List of Namespaces.\endlatexonly
*
* <h3>Specific Topics</h3>
*
* - \subpage pageTypeInterfaces
* - \subpage pageTheory
* - \subpage pageParams
* - \subpage pageLoggers
*
* <h3>Other Specific Resources</h3>
*
* - \subpage pageDebugging
*/
<|endoftext|>
|
<commit_before>#include "config.h"
#include "include/encoding.h"
#include "common/common_init.h"
#include <iostream>
#include <stdlib.h>
#include <vector>
using std::cout;
using std::cerr;
using std::string;
using std::vector;
typedef std::multimap < int, std::string > multimap_t;
typedef multimap_t::value_type val_ty;
static std::ostream& operator<<(std::ostream& oss, const multimap_t &multimap)
{
for (multimap_t::const_iterator m = multimap.begin();
m != multimap.end();
++m)
{
oss << m->first << "->" << m->second << " ";
}
return oss;
}
template < typename T >
static int test_encode_and_decode(const T& src)
{
bufferlist bl(1000000);
try {
// source
encode(src, bl);
// dest
T dst;
bufferlist::iterator i(bl.begin());
decode(dst, i);
if (src != dst) {
cout << "src = " << src << ", but dst = " << dst << std::endl;
return 1;
}
// else {
// cout << "src = " << src << ", and dst = " << dst << std::endl;
// }
}
catch (const ceph::buffer::malformed_input &e) {
cout << "got exception " << e.what() << std::endl;
return 1;
}
catch (const std::exception &e) {
cout << "got exception " << e.what() << std::endl;
return 1;
}
catch (...) {
cout << "unknown exception!" << std::endl;
return 1;
}
return 0;
}
static int test_string_sz(const char *str)
{
string my_str(str);
return test_encode_and_decode < std::string >(my_str);
}
static int multimap_tests(void)
{
multimap_t multimap;
multimap.insert( val_ty(1, "foo") );
multimap.insert( val_ty(2, "bar") );
multimap.insert( val_ty(2, "baz") );
multimap.insert( val_ty(3, "lucky number 3") );
multimap.insert( val_ty(10000, "large number") );
return test_encode_and_decode < multimap_t >(multimap);
}
int main(int argc, const char **argv)
{
int ret = 0;
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
ceph_set_default_id("admin");
common_set_defaults(false);
common_init(args, "ceph", true);
ret = test_string_sz("I am the very model of a modern major general");
if (ret)
goto done;
ret = test_string_sz("");
if (ret)
goto done;
ret = test_string_sz("foo bar baz\n");
if (ret)
goto done;
ret = multimap_tests();
if (ret)
goto done;
done:
if (ret) {
cout << "FAILURE" << std::endl;
return(EXIT_FAILURE);
}
cout << "SUCCESS" << std::endl;
return(EXIT_SUCCESS);
}
<commit_msg>TestEncoding: count number of ctor invocations<commit_after>#include "config.h"
#include "include/buffer.h"
#include "include/encoding.h"
#include "common/common_init.h"
#include <iostream>
#include <stdlib.h>
#include <stdint.h>
#include <string>
#include <sstream>
#include <vector>
using std::cout;
using std::cerr;
using std::string;
using std::vector;
static int multimap_ctor_count_tests(void);
typedef std::multimap < int, std::string > multimap_t;
typedef multimap_t::value_type my_val_ty;
static std::ostream& operator<<(std::ostream& oss, const multimap_t &multimap)
{
for (multimap_t::const_iterator m = multimap.begin();
m != multimap.end();
++m)
{
oss << m->first << "->" << m->second << " ";
}
return oss;
}
template < typename T >
static int test_encode_and_decode(const T& src)
{
bufferlist bl(1000000);
try {
// source
encode(src, bl);
// dest
T dst;
bufferlist::iterator i(bl.begin());
decode(dst, i);
if (src != dst) {
cout << "src = " << src << ", but dst = " << dst << std::endl;
return 1;
}
// else {
// cout << "src = " << src << ", and dst = " << dst << std::endl;
// }
}
catch (const ceph::buffer::malformed_input &e) {
cout << "got exception " << e.what() << std::endl;
return 1;
}
catch (const std::exception &e) {
cout << "got exception " << e.what() << std::endl;
return 1;
}
catch (...) {
cout << "unknown exception!" << std::endl;
return 1;
}
return 0;
}
static int test_string_sz(const char *str)
{
string my_str(str);
return test_encode_and_decode < std::string >(my_str);
}
static int multimap_tests(void)
{
multimap_t multimap;
multimap.insert( my_val_ty(1, "foo") );
multimap.insert( my_val_ty(2, "bar") );
multimap.insert( my_val_ty(2, "baz") );
multimap.insert( my_val_ty(3, "lucky number 3") );
multimap.insert( my_val_ty(10000, "large number") );
return test_encode_and_decode < multimap_t >(multimap);
}
int main(int argc, const char **argv)
{
int ret = 0;
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
ceph_set_default_id("admin");
common_set_defaults(false);
common_init(args, "ceph", true);
ret = test_string_sz("I am the very model of a modern major general");
if (ret)
goto done;
ret = test_string_sz("");
if (ret)
goto done;
ret = test_string_sz("foo bar baz\n");
if (ret)
goto done;
ret = multimap_tests();
if (ret)
goto done;
ret = multimap_ctor_count_tests();
if (ret)
goto done;
done:
if (ret) {
cout << "FAILURE" << std::endl;
return(EXIT_FAILURE);
}
cout << "SUCCESS" << std::endl;
return(EXIT_SUCCESS);
}
///////////////////////////////////////////////////////
// ConstructorCounter
///////////////////////////////////////////////////////
template < typename T >
int test_encode_and_decode(const T& src);
template <typename T>
class ConstructorCounter
{
public:
ConstructorCounter()
{
default_ctor++;
}
ConstructorCounter(const T& data_)
: data(data_)
{
one_arg_ctor++;
}
ConstructorCounter(const ConstructorCounter &rhs)
: data(rhs.data)
{
copy_ctor++;
}
ConstructorCounter &operator=(const ConstructorCounter &rhs)
{
data = rhs.data;
assigns++;
return *this;
}
static void init(void)
{
default_ctor = 0;
one_arg_ctor = 0;
copy_ctor = 0;
assigns = 0;
}
static std::string get_totals(void)
{
std::ostringstream oss;
oss << "default_ctor = " << default_ctor
<< ", one_arg_ctor = " << one_arg_ctor
<< ", copy_ctor = " << copy_ctor
<< ", assigns = " << assigns << std::endl;
return oss.str();
}
bool operator<(const ConstructorCounter &rhs) const
{
return data < rhs.data;
}
bool operator==(const ConstructorCounter &rhs) const
{
return data == rhs.data;
}
friend void decode(ConstructorCounter &s, bufferlist::iterator& p)
{
::decode(s.data, p);
}
friend void encode(const ConstructorCounter &s, bufferlist& p)
{
::encode(s.data, p);
}
friend ostream& operator<<(ostream &oss, const ConstructorCounter &cc)
{
oss << cc.data;
return oss;
}
T data;
private:
static int default_ctor;
static int one_arg_ctor;
static int copy_ctor;
static int assigns;
};
template class ConstructorCounter <int32_t>;
template class ConstructorCounter <int16_t>;
typedef ConstructorCounter <int32_t> my_key_t;
typedef ConstructorCounter <int16_t> my_val_t;
typedef std::multimap < my_key_t, my_val_t > multimap2_t;
typedef multimap2_t::value_type val2_ty;
template <class T> int ConstructorCounter<T>::default_ctor = 0;
template <class T> int ConstructorCounter<T>::one_arg_ctor = 0;
template <class T> int ConstructorCounter<T>::copy_ctor = 0;
template <class T> int ConstructorCounter<T>::assigns = 0;
static std::ostream& operator<<(std::ostream& oss, const multimap2_t &multimap)
{
for (multimap2_t::const_iterator m = multimap.begin();
m != multimap.end();
++m)
{
oss << m->first << "->" << m->second << " ";
}
return oss;
}
static int multimap_ctor_count_tests(void)
{
multimap2_t multimap2;
multimap2.insert( val2_ty(my_key_t(1), my_val_t(10)) );
multimap2.insert( val2_ty(my_key_t(2), my_val_t(20)) );
multimap2.insert( val2_ty(my_key_t(2), my_val_t(30)) );
multimap2.insert( val2_ty(my_key_t(3), my_val_t(40)) );
multimap2.insert( val2_ty(my_key_t(10000), my_val_t(1)) );
my_key_t::init();
my_val_t::init();
int ret = test_encode_and_decode < multimap2_t >(multimap2);
if (ret)
goto done;
cout << "totals for key type: " << my_key_t::get_totals() << std::endl;
cout << "totals for value type: " << my_val_t::get_totals() << std::endl;
my_val_t::get_totals();
done:
return ret;
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"ork/memory.hpp"
#include"glm/fwd.hpp"
namespace Json {
class Value;
}
namespace pugi {
class xml_document;
class xml_node;
}
namespace ork {
namespace json {
class ORK_ORK_API exportable {
public:
virtual ~exportable() {}//To support polymorphic hierarchies of nodes
public:
virtual void export_json(Json::Value& v) const = 0;
};
ORK_ORK_EXT(void) export_file(const string&filename, const Json::Value&root);
ORK_ORK_EXT(void) export_file(const string&filename, const exportable&object);
ORK_ORK_EXT(void) load_and_parse(i_stream&fin, Json::Value&root);
}//namespace json
namespace xml {
class ORK_ORK_API exportable {
public:
virtual ~exportable() {}//To support polymorphic hierarchies of nodes
public:
virtual void export_xml(pugi::xml_node &n) const = 0;
};
ORK_ORK_EXT(void) export_file(const string&filename, const exportable&object, const string&root_node_name);
ORK_ORK_EXT(void) load_and_parse(i_stream&fin, pugi::xml_document&xml);//Just create a file with error checking
}//namespace xml
#if ORK_USE_GLM
class vector
#if ORK_USE_PUGI
: public xml::exportable
#endif
{
private:
struct impl;
struct deleter {
void operator()(const impl*);
vector::impl operator()(const vector::impl&);
};
private:
value_ptr<impl, deleter>_pimpl;
public:
ORK_ORK_API vector();
ORK_ORK_API explicit vector(const glm::dvec3&vec);
ORK_ORK_API explicit vector(const GLM::dunit3&vec);
ORK_ORK_API vector(const double x, const double y, const double z);
#if ORK_USE_PUGI
ORK_ORK_API explicit vector(pugi::xml_node &node);
#endif
public:
ORK_ORK_API vector&operator=(const glm::dvec3&);
ORK_ORK_API vector&operator=(const GLM::dunit3&);
public:
ORK_ORK_API double&x();
ORK_ORK_API const double&x()const;
ORK_ORK_API double&y();
ORK_ORK_API const double&y()const;
ORK_ORK_API double&z();
ORK_ORK_API const double&z()const;
ORK_ORK_API glm::dvec3&get();
ORK_ORK_API const glm::dvec3&get()const;
ORK_ORK_API bool operator == (const vector &other) const;
ORK_ORK_API bool operator != (const vector &other) const;
ORK_ORK_API string as_string() const;
#if ORK_USE_PUGI
ORK_ORK_API virtual void export_xml(pugi::xml_node &n) const;
#endif
};
ORK_ORK_API o_stream &operator << (o_stream&stream, const ork::vector &vec);
#endif//ORK_USE_GLM
}//namespace ork
<commit_msg>Added guards to IO decls<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"ork/memory.hpp"
#include"glm/fwd.hpp"
namespace Json {
class Value;
}
namespace pugi {
class xml_document;
class xml_node;
}
namespace ork {
namespace json {
#if ORK_USE_JSON
class ORK_ORK_API exportable {
public:
virtual ~exportable() {}//To support polymorphic hierarchies of nodes
public:
virtual void export_json(Json::Value& v) const = 0;
};
ORK_ORK_EXT(void) export_file(const string&filename, const Json::Value&root);
ORK_ORK_EXT(void) export_file(const string&filename, const exportable&object);
ORK_ORK_EXT(void) load_and_parse(i_stream&fin, Json::Value&root);
#endif//ORK_USE_JSON
}//namespace json
namespace xml {
#if ORK_USE_PUGI
class ORK_ORK_API exportable {
public:
virtual ~exportable() {}//To support polymorphic hierarchies of nodes
public:
virtual void export_xml(pugi::xml_node &n) const = 0;
};
ORK_ORK_EXT(void) export_file(const string&filename, const exportable&object, const string&root_node_name);
ORK_ORK_EXT(void) load_and_parse(i_stream&fin, pugi::xml_document&xml);//Just create a file with error checking
#endif//ORK_USE_PUGI
}//namespace xml
#if ORK_USE_GLM
class vector
#if ORK_USE_PUGI
: public xml::exportable
#endif
{
private:
struct impl;
struct deleter {
void operator()(const impl*);
vector::impl operator()(const vector::impl&);
};
private:
value_ptr<impl, deleter>_pimpl;
public:
ORK_ORK_API vector();
ORK_ORK_API explicit vector(const glm::dvec3&vec);
ORK_ORK_API explicit vector(const GLM::dunit3&vec);
ORK_ORK_API vector(const double x, const double y, const double z);
#if ORK_USE_PUGI
ORK_ORK_API explicit vector(pugi::xml_node &node);
#endif
public:
ORK_ORK_API vector&operator=(const glm::dvec3&);
ORK_ORK_API vector&operator=(const GLM::dunit3&);
public:
ORK_ORK_API double&x();
ORK_ORK_API const double&x()const;
ORK_ORK_API double&y();
ORK_ORK_API const double&y()const;
ORK_ORK_API double&z();
ORK_ORK_API const double&z()const;
ORK_ORK_API glm::dvec3&get();
ORK_ORK_API const glm::dvec3&get()const;
ORK_ORK_API bool operator == (const vector &other) const;
ORK_ORK_API bool operator != (const vector &other) const;
ORK_ORK_API string as_string() const;
#if ORK_USE_PUGI
ORK_ORK_API virtual void export_xml(pugi::xml_node &n) const;
#endif
};
ORK_ORK_API o_stream &operator << (o_stream&stream, const ork::vector &vec);
#endif//ORK_USE_GLM
}//namespace ork
<|endoftext|>
|
<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <cstdarg>
#include <random>
#include <chrono>
#include "CompileConfig.h"
#if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)
#include <sys/syslog.h>
#endif
#ifdef OUZEL_PLATFORM_WINDOWS
#define NOMINMAX
#include <windows.h>
#include <strsafe.h>
#endif
#ifdef OUZEL_PLATFORM_ANDROID
#include <android/log.h>
#endif
#include "Utils.h"
namespace ouzel
{
char TEMP_BUFFER[65536];
void log(const char* format, ...)
{
va_list list;
va_start(list, format);
vsprintf(TEMP_BUFFER, format, list);
va_end(list);
#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_LINUX)
printf("%s\n", TEMP_BUFFER);
#elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)
syslog(LOG_WARNING, "%s", TEMP_BUFFER);
printf("%s\n", TEMP_BUFFER);
#elif defined(OUZEL_PLATFORM_WINDOWS)
wchar_t szBuffer[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH);
StringCchCat(szBuffer, sizeof(szBuffer), L"\n");
OutputDebugString(szBuffer);
#elif defined(OUZEL_PLATFORM_ANDROID)
__android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER);
#endif
}
uint64_t getCurrentMicroSeconds()
{
auto t = std::chrono::high_resolution_clock::now();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(t.time_since_epoch());
return micros.count();
}
std::vector<std::string> ARGS;
void setArgs(const std::vector<std::string>& args)
{
ARGS = args;
}
const std::vector<std::string>& getArgs()
{
return ARGS;
}
static std::mt19937 engine(std::random_device{}());
uint32_t random(uint32_t min, uint32_t max)
{
return std::uniform_int_distribution<uint32_t>{min, max}(engine);
}
float randomf(float min, float max)
{
float diff = max - min;
float rand = static_cast<float>(engine()) / engine.max();
return rand * diff + min;
}
}
<commit_msg>Use steady_clock for time measurement<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <cstdarg>
#include <random>
#include <chrono>
#include "CompileConfig.h"
#if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)
#include <sys/syslog.h>
#endif
#ifdef OUZEL_PLATFORM_WINDOWS
#define NOMINMAX
#include <windows.h>
#include <strsafe.h>
#endif
#ifdef OUZEL_PLATFORM_ANDROID
#include <android/log.h>
#endif
#include "Utils.h"
namespace ouzel
{
char TEMP_BUFFER[65536];
void log(const char* format, ...)
{
va_list list;
va_start(list, format);
vsprintf(TEMP_BUFFER, format, list);
va_end(list);
#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_LINUX)
printf("%s\n", TEMP_BUFFER);
#elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)
syslog(LOG_WARNING, "%s", TEMP_BUFFER);
printf("%s\n", TEMP_BUFFER);
#elif defined(OUZEL_PLATFORM_WINDOWS)
wchar_t szBuffer[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH);
StringCchCat(szBuffer, sizeof(szBuffer), L"\n");
OutputDebugString(szBuffer);
#elif defined(OUZEL_PLATFORM_ANDROID)
__android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER);
#endif
}
uint64_t getCurrentMicroSeconds()
{
auto t = std::chrono::steady_clock::now();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(t.time_since_epoch());
return micros.count();
}
std::vector<std::string> ARGS;
void setArgs(const std::vector<std::string>& args)
{
ARGS = args;
}
const std::vector<std::string>& getArgs()
{
return ARGS;
}
static std::mt19937 engine(std::random_device{}());
uint32_t random(uint32_t min, uint32_t max)
{
return std::uniform_int_distribution<uint32_t>{min, max}(engine);
}
float randomf(float min, float max)
{
float diff = max - min;
float rand = static_cast<float>(engine()) / engine.max();
return rand * diff + min;
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _BIGINT_HXX
#define _BIGINT_HXX
#include <climits>
#include <rtl/ustring.hxx>
#include "tools/toolsdllapi.h"
#include <tools/solar.h>
class SvStream;
#ifdef _TLBIGINT_INT64
struct SbxINT64;
struct SbxUINT64;
#endif
#define MAX_DIGITS 8
class Fraction;
class TOOLS_DLLPUBLIC SAL_WARN_UNUSED BigInt
{
private:
long nVal;
unsigned short nNum[MAX_DIGITS];
sal_uInt8 nLen : 5; // current length
sal_Bool bIsNeg : 1, // Is Sign negative?
bIsBig : 1, // sal_True == BigInt
bIsSet : 1; // Not "Null" (not "not 0")
TOOLS_DLLPRIVATE void MakeBigInt(BigInt const &);
TOOLS_DLLPRIVATE void Normalize();
TOOLS_DLLPRIVATE void Mult(BigInt const &, sal_uInt16);
TOOLS_DLLPRIVATE void Div(sal_uInt16, sal_uInt16 &);
TOOLS_DLLPRIVATE sal_Bool IsLess(BigInt const &) const;
TOOLS_DLLPRIVATE void AddLong(BigInt &, BigInt &);
TOOLS_DLLPRIVATE void SubLong(BigInt &, BigInt &);
TOOLS_DLLPRIVATE void MultLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE void DivLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE void ModLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE sal_Bool ABS_IsLess(BigInt const &) const;
public:
BigInt();
BigInt( short nVal );
BigInt( long nVal );
BigInt( int nVal );
BigInt( double nVal );
BigInt( sal_uInt16 nVal );
BigInt( sal_uInt32 nVal );
BigInt( const BigInt& rBigInt );
BigInt( const OUString& rString );
#ifdef _TLBIGINT_INT64
BigInt( const SbxINT64 &r );
BigInt( const SbxUINT64 &r );
#endif
operator short() const;
operator long() const;
operator int() const;
operator double() const;
operator sal_uInt16() const;
operator sal_uIntPtr() const;
void Set( sal_Bool bSet ) { bIsSet = bSet; }
OUString GetString() const;
sal_Bool IsSet() const { return bIsSet; }
sal_Bool IsNeg() const;
sal_Bool IsZero() const;
sal_Bool IsOne() const;
sal_Bool IsLong() const { return !bIsBig; }
void Abs();
#ifdef _TLBIGINT_INT64
sal_Bool INT64 ( SbxINT64 *p ) const;
sal_Bool UINT64( SbxUINT64 *p ) const;
#endif
BigInt& operator =( const BigInt& rVal );
BigInt& operator +=( const BigInt& rVal );
BigInt& operator -=( const BigInt& rVal );
BigInt& operator *=( const BigInt& rVal );
BigInt& operator /=( const BigInt& rVal );
BigInt& operator %=( const BigInt& rVal );
BigInt& operator =( const short nValue );
BigInt& operator =( const long nValue );
BigInt& operator =( const int nValue );
BigInt& operator =( const sal_uInt16 nValue );
friend inline BigInt operator +( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator -( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator *( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator /( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator %( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator==( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator!=( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator< ( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator> ( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator<=( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator>=( const BigInt& rVal1, const BigInt& rVal2 );
friend class Fraction;
};
inline BigInt::BigInt()
{
bIsSet = sal_False;
bIsBig = sal_False;
nVal = 0;
}
inline BigInt::BigInt( short nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( long nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( int nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( sal_uInt16 nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::operator short() const
{
if ( !bIsBig && nVal >= SHRT_MIN && nVal <= SHRT_MAX )
return (short)nVal;
else
return 0;
}
inline BigInt::operator long() const
{
if ( !bIsBig )
return nVal;
else
return 0;
}
inline BigInt::operator int() const
{
if ( !bIsBig && (nVal == (long)(int)nVal) )
return (int)nVal;
else
return 0;
}
inline BigInt::operator sal_uInt16() const
{
if ( !bIsBig && nVal >= 0 && nVal <= USHRT_MAX )
return (sal_uInt16)nVal;
else
return 0;
}
inline BigInt& BigInt::operator =( const short nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const long nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const int nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const sal_uInt16 nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline sal_Bool BigInt::IsNeg() const
{
if ( !bIsBig )
return (nVal < 0);
else
return (sal_Bool)bIsNeg;
}
inline sal_Bool BigInt::IsZero() const
{
if ( bIsBig )
return sal_False;
else
return (nVal == 0);
}
inline sal_Bool BigInt::IsOne() const
{
if ( bIsBig )
return sal_False;
else
return (nVal == 1);
}
inline void BigInt::Abs()
{
if ( bIsBig )
bIsNeg = sal_False;
else if ( nVal < 0 )
nVal = -nVal;
}
inline BigInt operator+( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg += rVal2;
return aErg;
}
inline BigInt operator-( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg -= rVal2;
return aErg;
}
inline BigInt operator*( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg *= rVal2;
return aErg;
}
inline BigInt operator/( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg /= rVal2;
return aErg;
}
inline BigInt operator%( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg %= rVal2;
return aErg;
}
inline sal_Bool operator!=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !(rVal1 == rVal2);
}
inline sal_Bool operator<=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !( rVal1 > rVal2);
}
inline sal_Bool operator>=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !(rVal1 < rVal2);
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: comparison between signed and unsigned integer expressions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _BIGINT_HXX
#define _BIGINT_HXX
#include <climits>
#include <rtl/ustring.hxx>
#include "tools/toolsdllapi.h"
#include <tools/solar.h>
class SvStream;
#ifdef _TLBIGINT_INT64
struct SbxINT64;
struct SbxUINT64;
#endif
#define MAX_DIGITS 8
class Fraction;
class TOOLS_DLLPUBLIC SAL_WARN_UNUSED BigInt
{
private:
long nVal;
unsigned short nNum[MAX_DIGITS];
sal_uInt8 nLen : 5; // current length
sal_Bool bIsNeg : 1, // Is Sign negative?
bIsBig : 1, // sal_True == BigInt
bIsSet : 1; // Not "Null" (not "not 0")
TOOLS_DLLPRIVATE void MakeBigInt(BigInt const &);
TOOLS_DLLPRIVATE void Normalize();
TOOLS_DLLPRIVATE void Mult(BigInt const &, sal_uInt16);
TOOLS_DLLPRIVATE void Div(sal_uInt16, sal_uInt16 &);
TOOLS_DLLPRIVATE sal_Bool IsLess(BigInt const &) const;
TOOLS_DLLPRIVATE void AddLong(BigInt &, BigInt &);
TOOLS_DLLPRIVATE void SubLong(BigInt &, BigInt &);
TOOLS_DLLPRIVATE void MultLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE void DivLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE void ModLong(BigInt const &, BigInt &) const;
TOOLS_DLLPRIVATE sal_Bool ABS_IsLess(BigInt const &) const;
public:
BigInt();
BigInt( short nVal );
BigInt( long nVal );
BigInt( int nVal );
BigInt( double nVal );
BigInt( sal_uInt16 nVal );
BigInt( sal_uInt32 nVal );
BigInt( const BigInt& rBigInt );
BigInt( const OUString& rString );
#ifdef _TLBIGINT_INT64
BigInt( const SbxINT64 &r );
BigInt( const SbxUINT64 &r );
#endif
operator short() const;
operator long() const;
operator int() const;
operator double() const;
operator sal_uInt16() const;
operator sal_uIntPtr() const;
void Set( sal_Bool bSet ) { bIsSet = bSet; }
OUString GetString() const;
sal_Bool IsSet() const { return bIsSet; }
sal_Bool IsNeg() const;
sal_Bool IsZero() const;
sal_Bool IsOne() const;
sal_Bool IsLong() const { return !bIsBig; }
void Abs();
#ifdef _TLBIGINT_INT64
sal_Bool INT64 ( SbxINT64 *p ) const;
sal_Bool UINT64( SbxUINT64 *p ) const;
#endif
BigInt& operator =( const BigInt& rVal );
BigInt& operator +=( const BigInt& rVal );
BigInt& operator -=( const BigInt& rVal );
BigInt& operator *=( const BigInt& rVal );
BigInt& operator /=( const BigInt& rVal );
BigInt& operator %=( const BigInt& rVal );
BigInt& operator =( const short nValue );
BigInt& operator =( const long nValue );
BigInt& operator =( const int nValue );
BigInt& operator =( const sal_uInt16 nValue );
friend inline BigInt operator +( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator -( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator *( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator /( const BigInt& rVal1, const BigInt& rVal2 );
friend inline BigInt operator %( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator==( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator!=( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator< ( const BigInt& rVal1, const BigInt& rVal2 );
TOOLS_DLLPUBLIC friend sal_Bool operator> ( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator<=( const BigInt& rVal1, const BigInt& rVal2 );
friend inline sal_Bool operator>=( const BigInt& rVal1, const BigInt& rVal2 );
friend class Fraction;
};
inline BigInt::BigInt()
{
bIsSet = sal_False;
bIsBig = sal_False;
nVal = 0;
}
inline BigInt::BigInt( short nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( long nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( int nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::BigInt( sal_uInt16 nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
}
inline BigInt::operator short() const
{
if ( !bIsBig && nVal >= SHRT_MIN && nVal <= SHRT_MAX )
return (short)nVal;
else
return 0;
}
inline BigInt::operator long() const
{
if ( !bIsBig )
return nVal;
else
return 0;
}
inline BigInt::operator int() const
{
if ( !bIsBig && (nVal == (long)(int)nVal) )
return (int)nVal;
else
return 0;
}
inline BigInt::operator sal_uInt16() const
{
if ( !bIsBig && nVal >= 0 && nVal <= (long)USHRT_MAX )
return (sal_uInt16)nVal;
else
return 0;
}
inline BigInt& BigInt::operator =( const short nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const long nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const int nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline BigInt& BigInt::operator =( const sal_uInt16 nValue )
{
bIsSet = sal_True;
bIsBig = sal_False;
nVal = nValue;
return *this;
}
inline sal_Bool BigInt::IsNeg() const
{
if ( !bIsBig )
return (nVal < 0);
else
return (sal_Bool)bIsNeg;
}
inline sal_Bool BigInt::IsZero() const
{
if ( bIsBig )
return sal_False;
else
return (nVal == 0);
}
inline sal_Bool BigInt::IsOne() const
{
if ( bIsBig )
return sal_False;
else
return (nVal == 1);
}
inline void BigInt::Abs()
{
if ( bIsBig )
bIsNeg = sal_False;
else if ( nVal < 0 )
nVal = -nVal;
}
inline BigInt operator+( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg += rVal2;
return aErg;
}
inline BigInt operator-( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg -= rVal2;
return aErg;
}
inline BigInt operator*( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg *= rVal2;
return aErg;
}
inline BigInt operator/( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg /= rVal2;
return aErg;
}
inline BigInt operator%( const BigInt &rVal1, const BigInt &rVal2 )
{
BigInt aErg( rVal1 );
aErg %= rVal2;
return aErg;
}
inline sal_Bool operator!=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !(rVal1 == rVal2);
}
inline sal_Bool operator<=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !( rVal1 > rVal2);
}
inline sal_Bool operator>=( const BigInt& rVal1, const BigInt& rVal2 )
{
return !(rVal1 < rVal2);
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: officeclient.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2003-04-23 16:41:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <osl/mutex.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <com/sun/star/uno/XNamingService.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/connection/XConnector.hpp>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMain.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <cppuhelper/implbase1.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::frame;
namespace remotebridges_officeclient {
class OfficeClientMain : public WeakImplHelper1< XMain >
{
public:
OfficeClientMain( const Reference< XMultiServiceFactory > &r ) :
m_xSMgr( r )
{}
public: // Methods
virtual sal_Int32 SAL_CALL run( const Sequence< OUString >& aArguments )
throw(RuntimeException);
private: // helper methods
void testWriter( const Reference < XComponent > & rComponent );
void registerServices();
Reference< XMultiServiceFactory > m_xSMgr;
};
void OfficeClientMain::testWriter( const Reference< XComponent > & rComponent )
{
printf( "pasting some text into the writer document\n" );
Reference< XTextDocument > rTextDoc( rComponent , UNO_QUERY );
Reference< XText > rText = rTextDoc->getText();
Reference< XTextCursor > rCursor = rText->createTextCursor();
Reference< XTextRange > rRange ( rCursor , UNO_QUERY );
rText->insertString( rRange, OUString::createFromAscii( "This text has been posted by the officeclient component" ), sal_False );
}
/********************
* does necessary service registration ( this could be done also by a setup tool )
*********************/
void OfficeClientMain::registerServices( )
{
// register services.
// Note : this needs to be done only once and is in general done by the setup
Reference < XImplementationRegistration > rImplementationRegistration(
m_xSMgr->createInstance(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" )),
UNO_QUERY );
if( ! rImplementationRegistration.is() )
{
printf( "Couldn't create registration component\n" );
exit(1);
}
OUString aSharedLibrary[4];
aSharedLibrary[0] =
OUString::createFromAscii( "connector.uno" SAL_DLLEXTENSION );
aSharedLibrary[1] =
OUString::createFromAscii( "remotebridge.uno" SAL_DLLEXTENSION );
aSharedLibrary[2] =
OUString::createFromAscii( "bridgefac.uno" SAL_DLLEXTENSION );
aSharedLibrary[3] =
OUString::createFromAscii( "uuresolver.uno" SAL_DLLEXTENSION );
sal_Int32 i;
for( i = 0 ; i < 4 ; i ++ )
{
// build the system specific library name
OUString aDllName = aSharedLibrary[i];
try
{
// register the needed services in the servicemanager
rImplementationRegistration->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
Reference< XSimpleRegistry > () );
}
catch( Exception & )
{
printf( "couldn't register dll %s\n" ,
OUStringToOString( aDllName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
}
sal_Int32 OfficeClientMain::run( const Sequence< OUString > & aArguments ) throw ( RuntimeException )
{
printf( "Connecting ....\n" );
if( aArguments.getLength() == 1 )
{
try {
registerServices();
Reference < XInterface > r =
m_xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ) );
Reference < XUnoUrlResolver > rResolver( r , UNO_QUERY );
r = rResolver->resolve( aArguments.getConstArray()[0] );
Reference< XNamingService > rNamingService( r, UNO_QUERY );
if( rNamingService.is() )
{
printf( "got the remote NamingService\n" );
r = rNamingService->getRegisteredObject(OUString::createFromAscii("StarOffice.ServiceManager"));
Reference< XMultiServiceFactory > rRemoteSMgr( r , UNO_QUERY );
Reference < XComponentLoader > rLoader(
rRemoteSMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ))),
UNO_QUERY );
if( rLoader.is() )
{
sal_Char *urls[] = {
"private:factory/swriter",
"private:factory/sdraw",
"private:factory/simpress",
"private:factory/scalc"
};
sal_Char *docu[]= {
"a new writer document ...\n",
"a new draw document ...\n",
"a new schedule document ...\n" ,
"a new calc document ...\n"
};
sal_Int32 i;
for( i = 0 ; i < 4 ; i ++ )
{
printf( "press any key to open %s\n" , docu[i] );
getchar();
Reference< XComponent > rComponent =
rLoader->loadComponentFromURL(
OUString::createFromAscii( urls[i] ) ,
OUString( RTL_CONSTASCII_USTRINGPARAM("_blank")),
0 ,
Sequence < ::com::sun::star::beans::PropertyValue >() );
if( 0 == i )
{
testWriter( rComponent );
}
printf( "press any key to close the document\n" );
getchar();
rComponent->dispose();
}
}
}
}
catch( ConnectionSetupException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "couldn't access local resource ( possible security resons )\n" );
}
catch( NoConnectException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "no server listening on the resource\n" );
}
catch( IllegalArgumentException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "uno url invalid\n" );
}
catch( RuntimeException & e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "a remote call was aborted\n" );
}
}
else
{
printf( "usage: (uno officeclient-component --) uno-url\n"
"e.g.: uno:socket,host=localhost,port=2002;urp;StarOffice.NamingService\n" );
return 1;
}
return 0;
}
Reference< XInterface > SAL_CALL CreateInstance( const Reference< XMultiServiceFactory > &r)
{
return Reference< XInterface > ( ( OWeakObject * ) new OfficeClientMain(r) );
}
Sequence< OUString > getSupportedServiceNames()
{
static Sequence < OUString > *pNames = 0;
if( ! pNames )
{
MutexGuard guard( Mutex::getGlobalMutex() );
if( !pNames )
{
static Sequence< OUString > seqNames(2);
seqNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.bridge.example.OfficeClientExample" );
pNames = &seqNames;
}
}
return *pNames;
}
}
using namespace remotebridges_officeclient;
#define IMPLEMENTATION_NAME "com.sun.star.comp.remotebridges.example.OfficeClientSample"
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
Reference< XRegistryKey > xNewKey(
reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey(
OUString::createFromAscii( "/" IMPLEMENTATION_NAME "/UNO/SERVICES" ) ) );
const Sequence< OUString > & rSNL = getSupportedServiceNames();
const OUString * pArray = rSNL.getConstArray();
for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
xNewKey->createKey( pArray[nPos] );
return sal_True;
}
catch (InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
void * pRet = 0;
if (pServiceManager && rtl_str_compare( pImplName, IMPLEMENTATION_NAME ) == 0)
{
Reference< XSingleServiceFactory > xFactory( createSingleFactory(
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
OUString::createFromAscii( pImplName ),
CreateInstance, getSupportedServiceNames() ) );
if (xFactory.is())
{
xFactory->acquire();
pRet = xFactory.get();
}
}
return pRet;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.78); FILE MERGED 2005/09/05 13:56:23 rt 1.5.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: officeclient.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:21:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include <osl/mutex.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <com/sun/star/uno/XNamingService.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/connection/XConnector.hpp>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMain.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <cppuhelper/implbase1.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::frame;
namespace remotebridges_officeclient {
class OfficeClientMain : public WeakImplHelper1< XMain >
{
public:
OfficeClientMain( const Reference< XMultiServiceFactory > &r ) :
m_xSMgr( r )
{}
public: // Methods
virtual sal_Int32 SAL_CALL run( const Sequence< OUString >& aArguments )
throw(RuntimeException);
private: // helper methods
void testWriter( const Reference < XComponent > & rComponent );
void registerServices();
Reference< XMultiServiceFactory > m_xSMgr;
};
void OfficeClientMain::testWriter( const Reference< XComponent > & rComponent )
{
printf( "pasting some text into the writer document\n" );
Reference< XTextDocument > rTextDoc( rComponent , UNO_QUERY );
Reference< XText > rText = rTextDoc->getText();
Reference< XTextCursor > rCursor = rText->createTextCursor();
Reference< XTextRange > rRange ( rCursor , UNO_QUERY );
rText->insertString( rRange, OUString::createFromAscii( "This text has been posted by the officeclient component" ), sal_False );
}
/********************
* does necessary service registration ( this could be done also by a setup tool )
*********************/
void OfficeClientMain::registerServices( )
{
// register services.
// Note : this needs to be done only once and is in general done by the setup
Reference < XImplementationRegistration > rImplementationRegistration(
m_xSMgr->createInstance(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" )),
UNO_QUERY );
if( ! rImplementationRegistration.is() )
{
printf( "Couldn't create registration component\n" );
exit(1);
}
OUString aSharedLibrary[4];
aSharedLibrary[0] =
OUString::createFromAscii( "connector.uno" SAL_DLLEXTENSION );
aSharedLibrary[1] =
OUString::createFromAscii( "remotebridge.uno" SAL_DLLEXTENSION );
aSharedLibrary[2] =
OUString::createFromAscii( "bridgefac.uno" SAL_DLLEXTENSION );
aSharedLibrary[3] =
OUString::createFromAscii( "uuresolver.uno" SAL_DLLEXTENSION );
sal_Int32 i;
for( i = 0 ; i < 4 ; i ++ )
{
// build the system specific library name
OUString aDllName = aSharedLibrary[i];
try
{
// register the needed services in the servicemanager
rImplementationRegistration->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
Reference< XSimpleRegistry > () );
}
catch( Exception & )
{
printf( "couldn't register dll %s\n" ,
OUStringToOString( aDllName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
}
sal_Int32 OfficeClientMain::run( const Sequence< OUString > & aArguments ) throw ( RuntimeException )
{
printf( "Connecting ....\n" );
if( aArguments.getLength() == 1 )
{
try {
registerServices();
Reference < XInterface > r =
m_xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ) );
Reference < XUnoUrlResolver > rResolver( r , UNO_QUERY );
r = rResolver->resolve( aArguments.getConstArray()[0] );
Reference< XNamingService > rNamingService( r, UNO_QUERY );
if( rNamingService.is() )
{
printf( "got the remote NamingService\n" );
r = rNamingService->getRegisteredObject(OUString::createFromAscii("StarOffice.ServiceManager"));
Reference< XMultiServiceFactory > rRemoteSMgr( r , UNO_QUERY );
Reference < XComponentLoader > rLoader(
rRemoteSMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ))),
UNO_QUERY );
if( rLoader.is() )
{
sal_Char *urls[] = {
"private:factory/swriter",
"private:factory/sdraw",
"private:factory/simpress",
"private:factory/scalc"
};
sal_Char *docu[]= {
"a new writer document ...\n",
"a new draw document ...\n",
"a new schedule document ...\n" ,
"a new calc document ...\n"
};
sal_Int32 i;
for( i = 0 ; i < 4 ; i ++ )
{
printf( "press any key to open %s\n" , docu[i] );
getchar();
Reference< XComponent > rComponent =
rLoader->loadComponentFromURL(
OUString::createFromAscii( urls[i] ) ,
OUString( RTL_CONSTASCII_USTRINGPARAM("_blank")),
0 ,
Sequence < ::com::sun::star::beans::PropertyValue >() );
if( 0 == i )
{
testWriter( rComponent );
}
printf( "press any key to close the document\n" );
getchar();
rComponent->dispose();
}
}
}
}
catch( ConnectionSetupException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "couldn't access local resource ( possible security resons )\n" );
}
catch( NoConnectException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "no server listening on the resource\n" );
}
catch( IllegalArgumentException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "uno url invalid\n" );
}
catch( RuntimeException & e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "a remote call was aborted\n" );
}
}
else
{
printf( "usage: (uno officeclient-component --) uno-url\n"
"e.g.: uno:socket,host=localhost,port=2002;urp;StarOffice.NamingService\n" );
return 1;
}
return 0;
}
Reference< XInterface > SAL_CALL CreateInstance( const Reference< XMultiServiceFactory > &r)
{
return Reference< XInterface > ( ( OWeakObject * ) new OfficeClientMain(r) );
}
Sequence< OUString > getSupportedServiceNames()
{
static Sequence < OUString > *pNames = 0;
if( ! pNames )
{
MutexGuard guard( Mutex::getGlobalMutex() );
if( !pNames )
{
static Sequence< OUString > seqNames(2);
seqNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.bridge.example.OfficeClientExample" );
pNames = &seqNames;
}
}
return *pNames;
}
}
using namespace remotebridges_officeclient;
#define IMPLEMENTATION_NAME "com.sun.star.comp.remotebridges.example.OfficeClientSample"
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
Reference< XRegistryKey > xNewKey(
reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey(
OUString::createFromAscii( "/" IMPLEMENTATION_NAME "/UNO/SERVICES" ) ) );
const Sequence< OUString > & rSNL = getSupportedServiceNames();
const OUString * pArray = rSNL.getConstArray();
for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
xNewKey->createKey( pArray[nPos] );
return sal_True;
}
catch (InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
void * pRet = 0;
if (pServiceManager && rtl_str_compare( pImplName, IMPLEMENTATION_NAME ) == 0)
{
Reference< XSingleServiceFactory > xFactory( createSingleFactory(
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
OUString::createFromAscii( pImplName ),
CreateInstance, getSupportedServiceNames() ) );
if (xFactory.is())
{
xFactory->acquire();
pRet = xFactory.get();
}
}
return pRet;
}
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <array>
#include <cstdint>
#include <vector>
#include "ExeUnpacker.h"
#include "../Utilities/Bytes.h"
#include "../Utilities/Debug.h"
#include "../Utilities/String.h"
#include "components/vfs/manager.hpp"
ExeUnpacker::ExeUnpacker(const std::string &filename)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str());
Debug::check(stream != nullptr, "Exe Unpacker", "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
const auto fileSize = stream->tellg();
stream->seekg(0, std::ios::beg);
std::vector<uint8_t> srcData(fileSize);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// Beginning and end of compressed data in the executable.
const uint8_t *compressedStart = srcData.data() + 752;
const uint8_t *compressedEnd = srcData.data() + (srcData.size() - 8);
// Last word of compressed data must be 0xFFFF.
const uint16_t lastCompWord = Bytes::getLE16(compressedEnd - 2);
Debug::check(lastCompWord == 0xFFFF, "Exe Unpacker",
"Invalid last compressed word \"" + String::toHexString(lastCompWord) + "\".");
// Calculate length of decompressed data -- more precise method (for A.EXE).
const size_t decompLen = [compressedEnd]()
{
const uint16_t segment = Bytes::getLE16(compressedEnd);
const uint16_t offset = Bytes::getLE16(compressedEnd + 2);
return (segment * 16) + offset;
}();
// Buffer for the decompressed data (also little endian).
std::vector<uint8_t> decomp(decompLen);
// Current position for inserting decompressed data.
size_t decompIndex = 0;
// A 16-bit array of compressed data.
uint16_t bitArray = Bytes::getLE16(compressedStart);
// Offset from start of compressed data (start at 2 because of the bit array).
int byteIndex = 2;
// Number of bits consumed in the current 16-bit array.
int bitsRead = 0;
// Continually read bit arrays from the compressed data and interpret each bit.
// Break once a compressed byte equals 0xFF in copy mode.
while (true)
{
// Lambda for getting the next byte from compressed data.
auto getNextByte = [compressedStart, &byteIndex]()
{
const uint8_t byte = compressedStart[byteIndex];
byteIndex++;
return byte;
};
// Lambda for getting the next bit in the theoretical bit stream.
auto getNextBit = [compressedStart, &bitArray, &bitsRead, &getNextByte]()
{
// Advance the bit array if done with the current one.
if (bitsRead == 16)
{
bitsRead = 0;
// Get two bytes in little endian format.
const uint8_t byte1 = getNextByte();
const uint8_t byte2 = getNextByte();
bitArray = byte1 | (byte2 << 8);
}
const bool bit = (bitArray & (1 << bitsRead)) != 0;
bitsRead++;
return bit;
};
// Decide which mode to use for the current bit.
if (getNextBit())
{
// "Copy" mode.
// Calculate which bytes in the decompressed data to duplicate and append.
Debug::crash("Exe Unpacker", "Copy mode not implemented.");
}
else
{
// "Decryption" mode.
// Read the next byte from the compressed data.
const uint8_t encryptedByte = getNextByte();
// Lambda for decrypting an encrypted byte with an XOR operation based on
// the current bit index.
auto decrypt = [](uint8_t encryptedByte, int bitsRead)
{
const uint8_t key = (bitsRead < 16) ? (16 - bitsRead) : 16;
const uint8_t decryptedByte = encryptedByte ^ key;
return decryptedByte;
};
// Decrypt the byte.
const uint8_t decryptedByte = decrypt(encryptedByte, bitsRead);
// Append the decrypted byte onto the decompressed data.
decomp.at(decompIndex) = decryptedByte;
decompIndex++;
}
}
// Keep this until the decompressor works.
Debug::crash("Exe Unpacker", "Not implemented.");
}
ExeUnpacker::~ExeUnpacker()
{
}
const std::string &ExeUnpacker::getText() const
{
return this->text;
}
<commit_msg>Reordered bit array advancing code.<commit_after>#include <algorithm>
#include <array>
#include <cstdint>
#include <vector>
#include "ExeUnpacker.h"
#include "../Utilities/Bytes.h"
#include "../Utilities/Debug.h"
#include "../Utilities/String.h"
#include "components/vfs/manager.hpp"
ExeUnpacker::ExeUnpacker(const std::string &filename)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str());
Debug::check(stream != nullptr, "Exe Unpacker", "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
const auto fileSize = stream->tellg();
stream->seekg(0, std::ios::beg);
std::vector<uint8_t> srcData(fileSize);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// Beginning and end of compressed data in the executable.
const uint8_t *compressedStart = srcData.data() + 752;
const uint8_t *compressedEnd = srcData.data() + (srcData.size() - 8);
// Last word of compressed data must be 0xFFFF.
const uint16_t lastCompWord = Bytes::getLE16(compressedEnd - 2);
Debug::check(lastCompWord == 0xFFFF, "Exe Unpacker",
"Invalid last compressed word \"" + String::toHexString(lastCompWord) + "\".");
// Calculate length of decompressed data -- more precise method (for A.EXE).
const size_t decompLen = [compressedEnd]()
{
const uint16_t segment = Bytes::getLE16(compressedEnd);
const uint16_t offset = Bytes::getLE16(compressedEnd + 2);
return (segment * 16) + offset;
}();
// Buffer for the decompressed data (also little endian).
std::vector<uint8_t> decomp(decompLen);
// Current position for inserting decompressed data.
size_t decompIndex = 0;
// A 16-bit array of compressed data.
uint16_t bitArray = Bytes::getLE16(compressedStart);
// Offset from start of compressed data (start at 2 because of the bit array).
int byteIndex = 2;
// Number of bits consumed in the current 16-bit array.
int bitsRead = 0;
// Continually read bit arrays from the compressed data and interpret each bit.
// Break once a compressed byte equals 0xFF in copy mode.
while (true)
{
// Lambda for getting the next byte from compressed data.
auto getNextByte = [compressedStart, &byteIndex]()
{
const uint8_t byte = compressedStart[byteIndex];
byteIndex++;
return byte;
};
// Lambda for getting the next bit in the theoretical bit stream.
auto getNextBit = [compressedStart, &bitArray, &bitsRead, &getNextByte]()
{
const bool bit = (bitArray & (1 << bitsRead)) != 0;
bitsRead++;
// Advance the bit array if done with the current one.
if (bitsRead == 16)
{
bitsRead = 0;
// Get two bytes in little endian format.
const uint8_t byte1 = getNextByte();
const uint8_t byte2 = getNextByte();
bitArray = byte1 | (byte2 << 8);
}
return bit;
};
// Decide which mode to use for the current bit.
if (getNextBit())
{
// "Copy" mode.
// Calculate which bytes in the decompressed data to duplicate and append.
Debug::crash("Exe Unpacker", "Copy mode not implemented.");
}
else
{
// "Decryption" mode.
// Read the next byte from the compressed data.
const uint8_t encryptedByte = getNextByte();
// Lambda for decrypting an encrypted byte with an XOR operation based on
// the current bit index. "bitsRead" is between 0 and 15. It is 0 if the
// 16th bit of the previous array was used to get here.
auto decrypt = [](uint8_t encryptedByte, int bitsRead)
{
const uint8_t key = 16 - bitsRead;
const uint8_t decryptedByte = encryptedByte ^ key;
return decryptedByte;
};
// Decrypt the byte.
const uint8_t decryptedByte = decrypt(encryptedByte, bitsRead);
// Append the decrypted byte onto the decompressed data.
decomp.at(decompIndex) = decryptedByte;
decompIndex++;
}
}
// Keep this until the decompressor works.
Debug::crash("Exe Unpacker", "Not implemented.");
}
ExeUnpacker::~ExeUnpacker()
{
}
const std::string &ExeUnpacker::getText() const
{
return this->text;
}
<|endoftext|>
|
<commit_before>/*
C++ version of ISBF for TraceBounds
*/
#include "isbfcpp.h"
#include <iostream>
#include <list>
#include <cmath>
#include <vector>
isbfcpp::isbfcpp(){}
void isbfcpp::rot90(int nrows, int ncols, std::vector <std::vector<int> > input, std::vector <std::vector<int> > &output)
{
for (int i=0; i<nrows; i++){
for (int j=0;j<ncols; j++){
output[j][nrows-1-i] = input[i][j];
}
}
}
std::vector <std::vector<int> > isbfcpp::traceBoundary(int nrows, int ncols, std::vector <std::vector<int> > mask, int startX, int startY, float inf)
{
// initialize boundary vector
std::list<int> boundary_listX;
std::list<int> boundary_listY;
// push the first x and y points
boundary_listX.push_back(startX);
boundary_listY.push_back(startY);
// initialize matrix for 90, 180, 270 degrees
std::vector <std::vector<int> > matrix90(ncols, std::vector<int>(nrows));
std::vector <std::vector<int> > matrix180(nrows, std::vector<int>(ncols));
std::vector <std::vector<int> > matrix270(ncols, std::vector<int>(nrows));
// rotate matrix for 90, 180, 270 degrees
rot90(nrows, ncols, mask, matrix270);
rot90(nrows, ncols, matrix270, matrix180);
rot90(nrows, ncols, matrix180, matrix90);
// set defalut direction
int DX = 1;
int DY = 0;
// set the number of rows and cols for ISBF
int rowISBF = 3;
int colISBF = 2;
float angle;
// set size of X: the size of X is equal to the size of Y
int sizeofX;
// loop until true
while(1) {
std::vector <std::vector<int> > h(rowISBF, std::vector<int>(colISBF));
// initialize a and b which are indices of ISBF
int a = 0;
int b = 0;
int x = boundary_listX.back();
int y = boundary_listY.back();
if((DX == 1)&&(DY == 0)){
for (int i = ncols-x-2; i < ncols-x+1; i++) {
for (int j = y-1; j < y+1; j++) {
h[a][b] = matrix90[i][j];
b++;
}
b = 0;
a++;
}
angle = M_PI/2;
}
else if((DX == 0)&&(DY == -1)){
for (int i = y-1; i < y+2; i++) {
for (int j = x-1; j < x+1; j++) {
h[a][b] = mask[i][j];
b++;
}
b = 0;
a++;
}
angle = 0;
}
else if((DX == -1)&&(DY == 0)){
for (int i = x-1; i < x+2; i++) {
for (int j = nrows-y-2; j < nrows-y; j++) {
h[a][b] = matrix270[i][j];
b++;
}
b = 0;
a++;
}
angle = 3*M_PI/2;
}
else{
for (int i = nrows-y-2; i < nrows-y+1; i++) {
for (int j = ncols-x-2; j < ncols-x; j++) {
h[a][b] = matrix180[i][j];
b++;
}
b = 0;
a++;
}
angle = M_PI;
}
// initialize cX and cY which indicate directions for each ISBF
std::vector<int> cX(1);
std::vector<int> cY(1);
if (h[1][0] == 1) {
// 'left' neighbor
cX[0] = -1;
cY[0] = 0;
DX = -1;
DY = 0;
}
else{
if((h[2][0] == 1)&&(h[2][1] != 1)){
// inner-outer corner at left-rear
cX[0] = -1;
cY[0] = 1;
DX = 0;
DY = 1;
}
else{
if(h[0][0] == 1){
if(h[0][1] == 1){
// inner corner at front
cX[0] = 0;
cY[0] = -1;
cX.push_back(-1);
cY.push_back(0);
DX = 0;
DY = -1;
}
else{
// inner-outer corner at front-left
cX[0] = -1;
cY[0] = -1;
DX = 0;
DY = -1;
}
}
else if(h[0][1] == 1){
// front neighbor
cX[0] = 0;
cY[0] = -1;
DX = 1;
DY = 0;
}
else{
// outer corner
DX = 0;
DY = 1;
}
}
}
// transform points by incoming directions and add to contours
float s = sin(angle);
float c = cos(angle);
if(!((cX[0]==0)&&(cY[0]==0))){
for(int t=0; t< int(cX.size()); t++){
float a, b;
int cx = cX[t];
int cy = cY[t];
a = c*cx - s*cy;
b = s*cx + c*cy;
x = boundary_listX.back();
y = boundary_listY.back();
boundary_listX.push_back(x+roundf(a));
boundary_listY.push_back(y+roundf(b));
}
}
float i, j;
i = c*DX - s*DY;
j = s*DX + c*DY;
DX = roundf(i);
DY = roundf(j);
// get length of the current linked list
sizeofX = boundary_listX.size();
if (sizeofX > 3) {
int fx1 = *boundary_listX.begin();
int fx2 = *std::next(boundary_listX.begin(), 1);
int fy1 = *boundary_listY.begin();
int fy2 = *std::next(boundary_listY.begin(), 1);
int lx1 = *std::prev(boundary_listX.end());
int ly1 = *std::prev(boundary_listY.end());
int lx2 = *std::prev(boundary_listX.end(), 2);
int ly2 = *std::prev(boundary_listY.end(), 2);
int lx3 = *std::prev(boundary_listX.end(), 3);
int ly3 = *std::prev(boundary_listY.end(), 3);
// check if the first and the last x and y are equal
if ((sizeofX > inf)|| \
((lx1 == fx2)&&(lx2 == fx1)&&(ly1 == fy2)&&(ly2 == fy1))){
// remove the last element
boundary_listX.pop_back();
boundary_listY.pop_back();
break;
}
if (int(cX.size()) == 2)
if ((lx2 == fx2)&&(lx3 == fx1)&&(ly2 == fy2)&&(ly3 == fy1)){
boundary_listX.pop_back();
boundary_listY.pop_back();
boundary_listX.pop_back();
boundary_listY.pop_back();
break;
}
}
}
std::vector <std::vector<int> > boundary(2, std::vector<int>(sizeofX));
boundary[0].assign(boundary_listX.begin(), boundary_listX.end());
boundary[1].assign(boundary_listY.begin(), boundary_listY.end());
return boundary;
}
isbfcpp::~isbfcpp(){}
<commit_msg>Update isbfcpp.cpp - three parameters are used in rot90<commit_after>/*
C++ version of ISBF for TraceBounds
*/
#include "isbfcpp.h"
#include <iostream>
#include <list>
#include <cmath>
#include <vector>
isbfcpp::isbfcpp()
{
}
void isbfcpp::rot90(int nrows, int ncols, std::vector <std::vector<int> > matrix,
std::vector <std::vector<int> > &matrix270,
std::vector <std::vector<int> > &matrix180,
std::vector <std::vector<int> > &matrix90)
{
// 0 to 270 degree
for (int i=0; i<nrows; i++){
for (int j=0;j<ncols; j++){
matrix270[j][nrows-1-i] = matrix[i][j];
}
}
// 270 to 180 degree
for (int i=0; i<ncols; i++){
for (int j=0;j<nrows; j++){
matrix180[j][ncols-1-i] = matrix270[i][j];
}
}
// 180 to 90 degree
for (int i=0; i<nrows; i++){
for (int j=0;j<ncols; j++){
matrix90[j][nrows-1-i] = matrix180[i][j];
}
}
}
std::vector <std::vector<int> > isbfcpp::traceBoundary(int nrows, int ncols, std::vector <std::vector<int> > mask, int startX, int startY, float inf)
{
// initialize boundary vector
std::list<int> boundary_listX;
std::list<int> boundary_listY;
// push the first x and y points
boundary_listX.push_back(startX);
boundary_listY.push_back(startY);
// initialize matrix for 90, 180, 270 degrees
std::vector <std::vector<int> > matrix90(ncols, std::vector<int>(nrows));
std::vector <std::vector<int> > matrix180(nrows, std::vector<int>(ncols));
std::vector <std::vector<int> > matrix270(ncols, std::vector<int>(nrows));
// rotate matrix for 90, 180, 270 degrees
rot90(nrows, ncols, mask, matrix270, matrix180, matrix90);
// set defalut direction
int DX = 1;
int DY = 0;
// set the number of rows and cols for ISBF
int rowISBF = 3;
int colISBF = 2;
float angle;
// set size of X: the size of X is equal to the size of Y
int sizeofX;
// loop until true
while(1) {
std::vector <std::vector<int> > h(rowISBF, std::vector<int>(colISBF));
// initialize a and b which are indices of ISBF
int a = 0;
int b = 0;
int x = boundary_listX.back();
int y = boundary_listY.back();
if((DX == 1)&&(DY == 0)){
for (int i = ncols-x-2; i < ncols-x+1; i++) {
for (int j = y-1; j < y+1; j++) {
h[a][b] = matrix90[i][j];
b++;
}
b = 0;
a++;
}
angle = M_PI/2;
}
else if((DX == 0)&&(DY == -1)){
for (int i = y-1; i < y+2; i++) {
for (int j = x-1; j < x+1; j++) {
h[a][b] = mask[i][j];
b++;
}
b = 0;
a++;
}
angle = 0;
}
else if((DX == -1)&&(DY == 0)){
for (int i = x-1; i < x+2; i++) {
for (int j = nrows-y-2; j < nrows-y; j++) {
h[a][b] = matrix270[i][j];
b++;
}
b = 0;
a++;
}
angle = 3*M_PI/2;
}
else{
for (int i = nrows-y-2; i < nrows-y+1; i++) {
for (int j = ncols-x-2; j < ncols-x; j++) {
h[a][b] = matrix180[i][j];
b++;
}
b = 0;
a++;
}
angle = M_PI;
}
// initialize cX and cY which indicate directions for each ISBF
std::vector<int> cX(1);
std::vector<int> cY(1);
if (h[1][0] == 1) {
// 'left' neighbor
cX[0] = -1;
cY[0] = 0;
DX = -1;
DY = 0;
}
else{
if((h[2][0] == 1)&&(h[2][1] != 1)){
// inner-outer corner at left-rear
cX[0] = -1;
cY[0] = 1;
DX = 0;
DY = 1;
}
else{
if(h[0][0] == 1){
if(h[0][1] == 1){
// inner corner at front
cX[0] = 0;
cY[0] = -1;
cX.push_back(-1);
cY.push_back(0);
DX = 0;
DY = -1;
}
else{
// inner-outer corner at front-left
cX[0] = -1;
cY[0] = -1;
DX = 0;
DY = -1;
}
}
else if(h[0][1] == 1){
// front neighbor
cX[0] = 0;
cY[0] = -1;
DX = 1;
DY = 0;
}
else{
// outer corner
DX = 0;
DY = 1;
}
}
}
// transform points by incoming directions and add to contours
float s = sin(angle);
float c = cos(angle);
if(!((cX[0]==0)&&(cY[0]==0))){
for(int t=0; t< int(cX.size()); t++){
float a, b;
int cx = cX[t];
int cy = cY[t];
a = c*cx - s*cy;
b = s*cx + c*cy;
x = boundary_listX.back();
y = boundary_listY.back();
boundary_listX.push_back(x+roundf(a));
boundary_listY.push_back(y+roundf(b));
}
}
float i, j;
i = c*DX - s*DY;
j = s*DX + c*DY;
DX = roundf(i);
DY = roundf(j);
// get length of the current linked list
sizeofX = boundary_listX.size();
if (sizeofX > 3) {
int fx1 = *boundary_listX.begin();
int fx2 = *std::next(boundary_listX.begin(), 1);
int fy1 = *boundary_listY.begin();
int fy2 = *std::next(boundary_listY.begin(), 1);
int lx1 = *std::prev(boundary_listX.end());
int ly1 = *std::prev(boundary_listY.end());
int lx2 = *std::prev(boundary_listX.end(), 2);
int ly2 = *std::prev(boundary_listY.end(), 2);
int lx3 = *std::prev(boundary_listX.end(), 3);
int ly3 = *std::prev(boundary_listY.end(), 3);
// check if the first and the last x and y are equal
if ((sizeofX > inf)|| \
((lx1 == fx2)&&(lx2 == fx1)&&(ly1 == fy2)&&(ly2 == fy1))){
// remove the last element
boundary_listX.pop_back();
boundary_listY.pop_back();
break;
}
if (int(cX.size()) == 2)
if ((lx2 == fx2)&&(lx3 == fx1)&&(ly2 == fy2)&&(ly3 == fy1)){
boundary_listX.pop_back();
boundary_listY.pop_back();
boundary_listX.pop_back();
boundary_listY.pop_back();
break;
}
}
}
std::vector <std::vector<int> > boundary(2, std::vector<int>(sizeofX));
boundary[0].assign(boundary_listX.begin(), boundary_listX.end());
boundary[1].assign(boundary_listY.begin(), boundary_listY.end());
return boundary;
}
isbfcpp::~isbfcpp()
{
}
<|endoftext|>
|
<commit_before>#pragma once
#include <gcl_cpp/mp.hpp>
namespace gcl
{
struct tuple_utils
{
template <size_t N, typename ... ts>
using type_at = typename std::tuple_element<N, std::tuple<ts...>>::type;
template <typename ... ts>
static constexpr std::size_t size(const std::tuple<ts...> &)
{
return std::tuple_size_v<std::tuple<ts...>>;
}
template <typename to_find, typename ... Ts>
static constexpr std::size_t index_of(const std::tuple<Ts...> &)
{
return gcl::mp::get_index<to_find, Ts...>();
}
template <typename T, typename ... ts>
static constexpr bool contains(const std::tuple<ts...>&)
{
return std::disjunction<std::is_same<T, ts>...>::value;
}
template <typename func_type, typename ... Ts>
static void for_each(std::tuple<Ts...> & value, func_type func)
{
using tuple_type = std::decay_t<decltype(value)>;
using indexes_type = std::make_index_sequence<std::tuple_size_v<tuple_type>>;
for_each_impl(func, value, indexes_type{});
}
template <typename func_type, typename ... Ts>
static void for_each(const std::tuple<Ts...> & value, func_type func)
{
using tuple_type = std::decay_t<decltype(value)>;
using indexes_type = std::make_index_sequence<std::tuple_size_v<tuple_type>>;
for_each_impl(func, value, indexes_type{});
}
private:
template <typename func_type, typename tuple_type, std::size_t ... indexes>
static void for_each_impl(func_type func, tuple_type & variadic_template, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(variadic_template)), ...);
}
template <typename func_type, typename tuple_type, std::size_t ... indexes>
static void for_each_impl(func_type func, const tuple_type & variadic_template, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(variadic_template)), ...);
}
};
}<commit_msg>new func : gcl::tuple_utils::visit(func_t, std::tuple<args_1...>, std::tuple<args_2...>) for sync-by-index expansion<commit_after>#pragma once
#include <gcl_cpp/mp.hpp>
namespace gcl
{
struct tuple_utils
{
template <size_t N, typename ... ts>
using type_at = typename std::tuple_element<N, std::tuple<ts...>>::type;
template <typename ... ts>
static constexpr std::size_t size(const std::tuple<ts...> &)
{
return std::tuple_size_v<std::tuple<ts...>>;
}
template <typename to_find, typename ... Ts>
static constexpr std::size_t index_of(const std::tuple<Ts...> &)
{
return gcl::mp::get_index<to_find, Ts...>();
}
template <typename T, typename ... ts>
static constexpr bool contains(const std::tuple<ts...>&)
{
return std::disjunction<std::is_same<T, ts>...>::value;
}
template <typename func_type, typename ... Ts>
static void for_each(std::tuple<Ts...> & value, func_type func)
{
using tuple_type = std::decay_t<decltype(value)>;
using indexes_type = std::make_index_sequence<std::tuple_size_v<tuple_type>>;
for_each_impl(func, value, indexes_type{});
}
template <typename func_type, typename ... Ts>
static void for_each(const std::tuple<Ts...> & value, func_type func)
{
using tuple_type = std::decay_t<decltype(value)>;
using indexes_type = std::make_index_sequence<std::tuple_size_v<tuple_type>>;
for_each_impl(func, value, indexes_type{});
}
template <typename t_func, typename ... ts_args_1, typename ... ts_args_2>
static void visit(t_func & func, std::tuple<ts_args_1...> & args_1, std::tuple<ts_args_2...> & args_2)
{ // sync index visit.
// call func `sizeof...(args_1)` times, with std::get<index>(args_1), std::get<index>(args_2);
// example :
// gcl::tuple_utils::visit([](auto & arg1, auto && arg2) {arg1 = std::move(arg2); }, values, arguments);
// is equal to :
// args_1 = args_2;
// e.g std::tuple<ts_1...>::operator=(std::tuple<ts_2...>)
static_assert(sizeof...(ts_args_1) == sizeof...(ts_args_2));
using indexes_type = std::make_index_sequence<sizeof...(ts_args_1)>;
visit_impl(func, args_1, args_2, indexes_type{});
}
template <typename t_func, typename ... ts_args_1, typename ... ts_args_2>
static void visit(const t_func & func, const std::tuple<ts_args_1...> & args_1, const std::tuple<ts_args_2...> & args_2)
{
static_assert(sizeof...(ts_args_1) == sizeof...(ts_args_2));
using indexes_type = std::make_index_sequence<sizeof...(ts_args_1)>;
visit_impl(func, args_1, args_2, indexes_type{});
}
private:
template <typename func_type, typename tuple_type, std::size_t ... indexes>
static void for_each_impl(func_type func, tuple_type & variadic_template, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(variadic_template)), ...);
}
template <typename func_type, typename tuple_type, std::size_t ... indexes>
static void for_each_impl(func_type func, const tuple_type & variadic_template, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(variadic_template)), ...);
}
template <typename t_func, typename ... ts_args_1, typename ... ts_args_2, std::size_t ... indexes>
static void visit_impl(t_func & func, std::tuple<ts_args_1...> & args_1, std::tuple<ts_args_2...> & args_2, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(args_1), std::get<indexes>(args_2)), ...);
}
template <typename t_func, typename ... ts_args_1, typename ... ts_args_2, std::size_t ... indexes>
static void visit_impl(const t_func & func, const std::tuple<ts_args_1...> & args_1, const std::tuple<ts_args_2...> & args_2, std::index_sequence<indexes...>)
{
(func(std::get<indexes>(args_1), std::get<indexes>(args_2)), ...);
}
};
}<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Root
#include <TSystem.h>
#include <TFile.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1F.h>
#include <TList.h>
#include <TProfile.h>
// AliRoot
#include "AliAnalysisManager.h"
#include "AliLog.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAnaWeights.h"
/// \cond CLASSIMP
ClassImp(AliAnaWeights) ;
/// \endcond
//______________________________________________________________
/// Constructor.
//______________________________________________________________
AliAnaWeights::AliAnaWeights()
: TObject(), fDebug(0),
fhCentralityWeight(0),
fCentrality(0),
fUseCentralityWeight(0),
fDoMCParticlePtWeights(1),
fEtaFunction(0), fPi0Function(0),
fMCWeight(1.),
fCurrFileName(0),
fCheckMCCrossSection(kFALSE),
fJustFillCrossSecHist(0),
fhXsec(0),
fhTrials(0),
fPyEventHeader(0),
fCheckPythiaEventHeader(0)
{
}
//______________________________________________________________
/// Destructor.
//______________________________________________________________
AliAnaWeights::~AliAnaWeights()
{
if ( fhCentralityWeight ) delete fhCentralityWeight ;
if ( fEtaFunction ) delete fEtaFunction ;
if ( fPi0Function ) delete fPi0Function ;
}
//____________________________________________________
/// Init histogram pointers.
/// \return TList containing histograms.
//____________________________________________________
TList * AliAnaWeights::GetCreateOutputHistograms()
{
TList * outputContainer = new TList() ;
outputContainer->SetName("MCWeightHistogram") ;
if(!fCheckMCCrossSection) return outputContainer;
outputContainer->SetOwner(kFALSE);
fhXsec = new TH1F("hXsec","xsec from pyxsec.root",1,0,1);
fhXsec->GetXaxis()->SetBinLabel(1,"<#sigma>");
outputContainer->Add(fhXsec);
fhTrials = new TH1F("hTrials","trials root file",1,0,1);
fhTrials->GetXaxis()->SetBinLabel(1,"#sum{ntrials}");
outputContainer->Add(fhTrials);
return outputContainer ;
}
//__________________________________
/// \return weight to be applied to the event.
/// The weight can be right now:
/// * pT-hard bin in PYTHIA MC events
/// * centrality dependent weight
//_________________________________
Double_t AliAnaWeights::GetWeight()
{
Double_t weight = 1.;
if ( fCheckMCCrossSection )
{
Double_t temp = GetPythiaCrossSection() ;
AliDebug(1,Form("MC pT-hard weight: %e",temp));
weight*=temp;
}
if ( fUseCentralityWeight )
{
Double_t temp = fhCentralityWeight->GetBinContent(fhCentralityWeight->FindBin(fCentrality));
AliDebug(1,Form("Centrality %2.1f, weight: %2.2f",fCentrality,temp));
weight*=temp;
}
AliDebug(1,Form("Event weight %e",weight));
return weight ;
}
//_____________________________________________
//
/// \return the particle pT weight depending on
///
/// \param pt: input particle transverse momentum
/// \param pdg: input particle type pdg code
/// \param genName: TString with generator name
/// \param igen: index of generator (not used yet).
///
/// currently, only pi0 and eta cases are considered. The parametrizations are passed via
/// SetEtaFunction(TF1* fun) and SetPi0Function(TF1* fun)
/// ex param: TF1* PowerEta0 = new TF1("PowerEta0","[0]*pow([1]/(([1]*exp(-[3]*x)+x)),[2])",4,25);
/// Only active when SwitchOnMCParticlePtWeights()
//_____________________________________________
Double_t AliAnaWeights::GetParticlePtWeight(Float_t pt, Int_t pdg, TString genName, Int_t igen) const
{
Double_t weight = 1.;
if ( !fDoMCParticlePtWeights ) return weight ;
if (pdg == 111 && fPi0Function &&
(genName.Contains("Pi0") || genName.Contains("pi0") || genName.Contains("PARAM") || genName.Contains("BOX")))
weight = fPi0Function->Eval(pt);
else if (pdg == 221 && fEtaFunction &&
(genName.Contains("Eta") || genName.Contains("eta") || genName.Contains("PARAM") || genName.Contains("BOX")))
weight = fEtaFunction->Eval(pt);
AliDebug(1,Form("MC particle pdg %d, pt %2.2f, generator %s with index %d: weight %f",pdg,pt,genName.Data(),igen, weight));
return weight ;
}
//_____________________________________________
//
/// Read the cross sections and number of trials
/// from pyxsec.root (ESD) or pysec_hists.root (AODs),
/// values stored in specific histograms-trees.
/// If no file available, get information from Pythia event header
///
/// Fill the control histograms on number of trials and xsection
/// optionally, with fJustFillCrossSecHist, just do that and do not return a weight.
/// For cross section obtained from pythia event header, this is already the case.
//_____________________________________________
Double_t AliAnaWeights::GetPythiaCrossSection()
{
Float_t xsection = 0;
Float_t trials = 1;
Float_t avgTrials = 0;
if ( !fhXsec || !fhTrials ) return 1;
// -----------------------------------------------
// Check if info is already in Pythia event header
// Do not apply the weight per event, too much number of trial variation
// -----------------------------------------------
if ( fPyEventHeader && fCheckPythiaEventHeader )
{
fMCWeight = 1 ;
AliDebug(fDebug,Form("Pythia event header: xs %2.2e, trial %d", fPyEventHeader->GetXsection(),fPyEventHeader->Trials()));
fhXsec ->Fill("<#sigma>" ,fPyEventHeader->GetXsection());
fhTrials->Fill("#sum{ntrials}",fPyEventHeader->Trials());
return 1 ;
}
// -----------------------------------------------
// Get cross section from corresponding files
// -----------------------------------------------
TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree();
if ( !tree ) return 1;
TFile *curfile = tree->GetCurrentFile();
if ( !curfile ) return 1;
// Check if file not accessed previously, if so
// return the previously calculated weight
if(fCurrFileName == curfile->GetName()) return fMCWeight;
fCurrFileName = TString(curfile->GetName());
Bool_t ok = GetPythiaInfoFromFile(fCurrFileName,xsection,trials);
if ( !ok )
{
AliWarning("Parameters from file not recovered properly");
return 1;
}
fhXsec->Fill("<#sigma>",xsection);
// average number of trials
Float_t nEntries = (Float_t)tree->GetTree()->GetEntries();
if(trials >= nEntries && nEntries > 0.) avgTrials = trials/nEntries;
fhTrials->Fill("#sum{ntrials}",avgTrials);
AliInfo(Form("xs %2.2e, trial %e, avg trials %2.2e, events per file %e",
xsection,trials,avgTrials,nEntries));
AliDebug(1,Form("Reading File %s",curfile->GetName()));
if(avgTrials > 0.)
{
if(!fJustFillCrossSecHist)
{
fMCWeight = xsection / avgTrials ;
AliInfo(Form("MC Weight: %e",fMCWeight));
}
else fMCWeight = 1; // do not add weight to histograms
}
else
{
AliWarning(Form("Average number of trials is NULL!! Set weight to 1: xs : %e, trials %e, entries %e",
xsection,trials,nEntries));
fMCWeight = 1;
}
return fMCWeight ;
}
//_______________________________________________________________________________________
/// This method gets and returns the
/// \param file : either pyxsec.root (ESDs) or pysec_hists.root (AODs) files
/// \param xsec : cross section
/// \param trials : number of event trials
/// that should be located where the main data file is.
/// This is called in Notify and should provide the path to the AOD/ESD file
//_______________________________________________________________________________________
Bool_t AliAnaWeights::GetPythiaInfoFromFile(TString file,Float_t & xsec,Float_t & trials)
{
xsec = 0;
trials = 1;
if(file.Contains("root_archive.zip#"))
{
Ssiz_t pos1 = file.Index("root_archive",12,0,TString::kExact);
Ssiz_t pos = file.Index("#",1,pos1,TString::kExact);
Ssiz_t pos2 = file.Index(".root",5,TString::kExact);
file.Replace(pos+1,pos2-pos1,"");
}
else
{
// not an archive take the basename....
file.ReplaceAll(gSystem->BaseName(file.Data()),"");
}
//Printf("%s",file.Data());
TFile *fxsec = TFile::Open(Form("%s%s",file.Data(),"pyxsec.root")); // problem that we cannot really test the existance of a file in a archive so we have to lvie with open error message from root
if(!fxsec)
{
// next trial fetch the histgram file
fxsec = TFile::Open(Form("%s%s",file.Data(),"pyxsec_hists.root"));
if(!fxsec)
{
// not a severe condition but inciate that we have no information
return kFALSE;
}
else
{
// find the tlist we want to be independtent of the name so use the Tkey
TKey* key = (TKey*)fxsec->GetListOfKeys()->At(0);
if(!key)
{
fxsec->Close();
return kFALSE;
}
TList *list = dynamic_cast<TList*>(key->ReadObj());
if(!list)
{
fxsec->Close();
return kFALSE;
}
xsec = ((TProfile*)list->FindObject("h1Xsec")) ->GetBinContent(1);
trials = ((TH1F*) list->FindObject("h1Trials"))->GetBinContent(1);
fxsec->Close();
}
} // no tree pyxsec.root
else
{
TTree *xtree = (TTree*)fxsec->Get("Xsection");
if(!xtree)
{
fxsec->Close();
return kFALSE;
}
UInt_t ntrials = 0;
Double_t xsection = 0;
xtree->SetBranchAddress("xsection",&xsection);
xtree->SetBranchAddress("ntrials",&ntrials);
xtree->GetEntry(0);
trials = ntrials;
xsec = xsection;
fxsec->Close();
}
return kTRUE;
}
//_______________________________________________________________________________________
/// This method intializes the histogram containing the centrality weights.
/// Use in case of different binning than default.
/// \param nbins : number of bins in histogram, default 100
/// \param minCen : minimum value of centrality, default 0
/// \param maxCen : maximum value of centrality, default 100
//_______________________________________________________________________________________
void AliAnaWeights::InitCentralityWeightsHistogram(Int_t nbins, Int_t minCen, Int_t maxCen)
{
if ( fhCentralityWeight ) delete fhCentralityWeight ;
fhCentralityWeight = new TH1F("hCentralityWeights","Centrality weights",nbins,minCen,maxCen);
for(Int_t ibin = 0; ibin < fhCentralityWeight->GetNbinsX(); ibin++)
fhCentralityWeight->SetBinContent(ibin,1.) ;
}
//_________________________________________________
/// \return histogram with centrality weights.
//_________________________________________________
TH1F* AliAnaWeights::GetCentralityWeightsHistogram()
{
if ( !fhCentralityWeight ) InitCentralityWeightsHistogram();
return fhCentralityWeight ;
}
<commit_msg>fix automatic weight application in case of getting cross section from event header<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Root
#include <TSystem.h>
#include <TFile.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1F.h>
#include <TList.h>
#include <TProfile.h>
// AliRoot
#include "AliAnalysisManager.h"
#include "AliLog.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAnaWeights.h"
/// \cond CLASSIMP
ClassImp(AliAnaWeights) ;
/// \endcond
//______________________________________________________________
/// Constructor.
//______________________________________________________________
AliAnaWeights::AliAnaWeights()
: TObject(), fDebug(0),
fhCentralityWeight(0),
fCentrality(0),
fUseCentralityWeight(0),
fDoMCParticlePtWeights(1),
fEtaFunction(0), fPi0Function(0),
fMCWeight(1.),
fCurrFileName(0),
fCheckMCCrossSection(kFALSE),
fJustFillCrossSecHist(0),
fhXsec(0),
fhTrials(0),
fPyEventHeader(0),
fCheckPythiaEventHeader(0)
{
}
//______________________________________________________________
/// Destructor.
//______________________________________________________________
AliAnaWeights::~AliAnaWeights()
{
if ( fhCentralityWeight ) delete fhCentralityWeight ;
if ( fEtaFunction ) delete fEtaFunction ;
if ( fPi0Function ) delete fPi0Function ;
}
//____________________________________________________
/// Init histogram pointers.
/// \return TList containing histograms.
//____________________________________________________
TList * AliAnaWeights::GetCreateOutputHistograms()
{
TList * outputContainer = new TList() ;
outputContainer->SetName("MCWeightHistogram") ;
if(!fCheckMCCrossSection) return outputContainer;
outputContainer->SetOwner(kFALSE);
fhXsec = new TH1F("hXsec","xsec from pyxsec.root",1,0,1);
fhXsec->GetXaxis()->SetBinLabel(1,"<#sigma>");
outputContainer->Add(fhXsec);
fhTrials = new TH1F("hTrials","trials root file",1,0,1);
fhTrials->GetXaxis()->SetBinLabel(1,"#sum{ntrials}");
outputContainer->Add(fhTrials);
return outputContainer ;
}
//__________________________________
/// \return weight to be applied to the event.
/// The weight can be right now:
/// * pT-hard bin in PYTHIA MC events
/// * centrality dependent weight
//_________________________________
Double_t AliAnaWeights::GetWeight()
{
Double_t weight = 1.;
if ( fCheckMCCrossSection )
{
Double_t temp = GetPythiaCrossSection() ;
AliDebug(1,Form("MC pT-hard weight: %e",temp));
weight*=temp;
}
if ( fUseCentralityWeight )
{
Double_t temp = fhCentralityWeight->GetBinContent(fhCentralityWeight->FindBin(fCentrality));
AliDebug(1,Form("Centrality %2.1f, weight: %2.2f",fCentrality,temp));
weight*=temp;
}
AliDebug(1,Form("Event weight %e",weight));
return weight ;
}
//_____________________________________________
//
/// \return the particle pT weight depending on
///
/// \param pt: input particle transverse momentum
/// \param pdg: input particle type pdg code
/// \param genName: TString with generator name
/// \param igen: index of generator (not used yet).
///
/// currently, only pi0 and eta cases are considered. The parametrizations are passed via
/// SetEtaFunction(TF1* fun) and SetPi0Function(TF1* fun)
/// ex param: TF1* PowerEta0 = new TF1("PowerEta0","[0]*pow([1]/(([1]*exp(-[3]*x)+x)),[2])",4,25);
/// Only active when SwitchOnMCParticlePtWeights()
//_____________________________________________
Double_t AliAnaWeights::GetParticlePtWeight(Float_t pt, Int_t pdg, TString genName, Int_t igen) const
{
Double_t weight = 1.;
if ( !fDoMCParticlePtWeights ) return weight ;
if (pdg == 111 && fPi0Function &&
(genName.Contains("Pi0") || genName.Contains("pi0") || genName.Contains("PARAM") || genName.Contains("BOX")))
weight = fPi0Function->Eval(pt);
else if (pdg == 221 && fEtaFunction &&
(genName.Contains("Eta") || genName.Contains("eta") || genName.Contains("PARAM") || genName.Contains("BOX")))
weight = fEtaFunction->Eval(pt);
AliDebug(1,Form("MC particle pdg %d, pt %2.2f, generator %s with index %d: weight %f",pdg,pt,genName.Data(),igen, weight));
return weight ;
}
//_____________________________________________
//
/// Read the cross sections and number of trials
/// from pyxsec.root (ESD) or pysec_hists.root (AODs),
/// values stored in specific histograms-trees.
/// If no file available, get information from Pythia event header
///
/// Fill the control histograms on number of trials and xsection
/// optionally, with fJustFillCrossSecHist, just do that and do not return a weight.
/// For cross section obtained from pythia event header, this is already the case.
//_____________________________________________
Double_t AliAnaWeights::GetPythiaCrossSection()
{
Float_t xsection = 0;
Float_t trials = 1;
Float_t avgTrials = 0;
if ( !fhXsec || !fhTrials ) return 1;
// -----------------------------------------------
// Check if info is already in Pythia event header
// Do not apply the weight per event, too much number of trial variation
// -----------------------------------------------
if ( fPyEventHeader && fCheckPythiaEventHeader )
{
AliDebug(fDebug,Form("Pythia event header: xs %2.2e, trial %d",
fPyEventHeader->GetXsection(),fPyEventHeader->Trials()));
fhXsec ->Fill("<#sigma>" ,fPyEventHeader->GetXsection());
fhTrials->Fill("#sum{ntrials}",fPyEventHeader->Trials());
if ( !fJustFillCrossSecHist )
{
fMCWeight = fPyEventHeader->GetXsection() / fPyEventHeader->Trials() ;
AliDebug(1,Form("MC Weight: %e",fMCWeight));
}
else fMCWeight = 1;
return fMCWeight ;
}
// -----------------------------------------------
// Get cross section from corresponding files
// -----------------------------------------------
TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree();
if ( !tree ) return 1;
TFile *curfile = tree->GetCurrentFile();
if ( !curfile ) return 1;
// Check if file not accessed previously, if so
// return the previously calculated weight
if(fCurrFileName == curfile->GetName()) return fMCWeight;
fCurrFileName = TString(curfile->GetName());
Bool_t ok = GetPythiaInfoFromFile(fCurrFileName,xsection,trials);
if ( !ok )
{
AliWarning("Parameters from file not recovered properly");
return 1;
}
fhXsec->Fill("<#sigma>",xsection);
// average number of trials
Float_t nEntries = (Float_t)tree->GetTree()->GetEntries();
if(trials >= nEntries && nEntries > 0.) avgTrials = trials/nEntries;
fhTrials->Fill("#sum{ntrials}",avgTrials);
AliInfo(Form("xs %2.2e, trial %e, avg trials %2.2e, events per file %e",
xsection,trials,avgTrials,nEntries));
AliDebug(1,Form("Reading File %s",curfile->GetName()));
if(avgTrials > 0.)
{
if(!fJustFillCrossSecHist)
{
fMCWeight = xsection / avgTrials ;
AliInfo(Form("MC Weight: %e",fMCWeight));
}
else fMCWeight = 1; // do not add weight to histograms
}
else
{
AliWarning(Form("Average number of trials is NULL!! Set weight to 1: xs : %e, trials %e, entries %e",
xsection,trials,nEntries));
fMCWeight = 1;
}
return fMCWeight ;
}
//_______________________________________________________________________________________
/// This method gets and returns the
/// \param file : either pyxsec.root (ESDs) or pysec_hists.root (AODs) files
/// \param xsec : cross section
/// \param trials : number of event trials
/// that should be located where the main data file is.
/// This is called in Notify and should provide the path to the AOD/ESD file
//_______________________________________________________________________________________
Bool_t AliAnaWeights::GetPythiaInfoFromFile(TString file,Float_t & xsec,Float_t & trials)
{
xsec = 0;
trials = 1;
if(file.Contains("root_archive.zip#"))
{
Ssiz_t pos1 = file.Index("root_archive",12,0,TString::kExact);
Ssiz_t pos = file.Index("#",1,pos1,TString::kExact);
Ssiz_t pos2 = file.Index(".root",5,TString::kExact);
file.Replace(pos+1,pos2-pos1,"");
}
else
{
// not an archive take the basename....
file.ReplaceAll(gSystem->BaseName(file.Data()),"");
}
//Printf("%s",file.Data());
TFile *fxsec = TFile::Open(Form("%s%s",file.Data(),"pyxsec.root")); // problem that we cannot really test the existance of a file in a archive so we have to lvie with open error message from root
if(!fxsec)
{
// next trial fetch the histgram file
fxsec = TFile::Open(Form("%s%s",file.Data(),"pyxsec_hists.root"));
if(!fxsec)
{
// not a severe condition but inciate that we have no information
return kFALSE;
}
else
{
// find the tlist we want to be independtent of the name so use the Tkey
TKey* key = (TKey*)fxsec->GetListOfKeys()->At(0);
if(!key)
{
fxsec->Close();
return kFALSE;
}
TList *list = dynamic_cast<TList*>(key->ReadObj());
if(!list)
{
fxsec->Close();
return kFALSE;
}
xsec = ((TProfile*)list->FindObject("h1Xsec")) ->GetBinContent(1);
trials = ((TH1F*) list->FindObject("h1Trials"))->GetBinContent(1);
fxsec->Close();
}
} // no tree pyxsec.root
else
{
TTree *xtree = (TTree*)fxsec->Get("Xsection");
if(!xtree)
{
fxsec->Close();
return kFALSE;
}
UInt_t ntrials = 0;
Double_t xsection = 0;
xtree->SetBranchAddress("xsection",&xsection);
xtree->SetBranchAddress("ntrials",&ntrials);
xtree->GetEntry(0);
trials = ntrials;
xsec = xsection;
fxsec->Close();
}
return kTRUE;
}
//_______________________________________________________________________________________
/// This method intializes the histogram containing the centrality weights.
/// Use in case of different binning than default.
/// \param nbins : number of bins in histogram, default 100
/// \param minCen : minimum value of centrality, default 0
/// \param maxCen : maximum value of centrality, default 100
//_______________________________________________________________________________________
void AliAnaWeights::InitCentralityWeightsHistogram(Int_t nbins, Int_t minCen, Int_t maxCen)
{
if ( fhCentralityWeight ) delete fhCentralityWeight ;
fhCentralityWeight = new TH1F("hCentralityWeights","Centrality weights",nbins,minCen,maxCen);
for(Int_t ibin = 0; ibin < fhCentralityWeight->GetNbinsX(); ibin++)
fhCentralityWeight->SetBinContent(ibin,1.) ;
}
//_________________________________________________
/// \return histogram with centrality weights.
//_________________________________________________
TH1F* AliAnaWeights::GetCentralityWeightsHistogram()
{
if ( !fhCentralityWeight ) InitCentralityWeightsHistogram();
return fhCentralityWeight ;
}
<|endoftext|>
|
<commit_before>// This is the main DLL file.
#include "stdafx.h"
#include "TreeDetection.h"
#include "stdafx.h"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;
using namespace cv;
void GetEntropyImage( const Mat *graySrc, uint neighborhoodSize, Mat *entropyImage, bool bDoNaive = false );
vector<float> EntropyFunctionCache;
int CacheBaseSize = -1;
/*
This is the function to be called to enter the dll
Inputs
======
FilePath - The file for the entropy function to be calculated on
Output
======
*/
extern "C" _declspec( dllexport ) void Entry( const char *filepath )
{
Mat image = imread( filepath ),
labImage,
luminosityImage,
result;
std::vector<cv::Mat> channels;
string outputPath = filepath;
outputPath = "entropy_" + outputPath;
//
// Converts image from RGB to LAB color space, dropping the A and B channels,
// leaving just the L channel
//
cvtColor( image, labImage, CV_RGB2Lab, 0 );
split( labImage, channels );
luminosityImage = channels[0];
GetEntropyImage( &luminosityImage, 9, &result );
imwrite( outputPath, result );
}
/*
This function gets the value at the location of a matrix, it allows for automatic padding of data
Inputs
======
src - The src matrix for the function to be performed on
x - The x coordinates of the pixel
y - The y coordinates of the pixel
Output
======
Return Value - the value of the pixel at the specified location
*/
int GetMatPixelVal( const Mat* src, uint x, uint y )
{
int val = src->at<uchar>(
borderInterpolate( y, src->rows, BORDER_REFLECT ),
borderInterpolate( x, src->cols, BORDER_REFLECT )
);
return val;
}
/*
This function does the entropy calculation for a given occurence.
It uses a cached value when possible, since the operation is expensive to perform.
Inputs
======
timesOccured - The number of times this luminosity has been seen for a key pixel
numberOfElements - The size of the neighborhood for the calculation
Output
======
Return Value - The result of the entropy calculation
*/
float entropyCalculation( int timesOccured, int numberOfElements )
{
float returnValue,
frequency;
//
// If the size of the neighborhood we are caching changes
// then we need to empty and recreate the cache
//
if( CacheBaseSize != numberOfElements )
{
CacheBaseSize = numberOfElements;
EntropyFunctionCache.clear();
EntropyFunctionCache.insert( EntropyFunctionCache.end(), numberOfElements + 1, ( float ) -1 );
}
if( EntropyFunctionCache[timesOccured] == -1 )
{
frequency = ( float ) timesOccured / ( float ) numberOfElements;
returnValue = frequency * log2f( frequency );
EntropyFunctionCache[timesOccured] = returnValue;
}
else
{
returnValue = EntropyFunctionCache[timesOccured];
}
return returnValue;
}
/*
This function calculates the shannon entropy for an image with a given kernel size
Inputs
======
graySrc - The gray source image for the calculation to be performed
neighborhoodSize - An integer representing the size of the grid that will be used for sampling each pixels entropy
This value must be positive and odd, and an exception will be thrown if it is not.
bDoNaive - Toggle to run the naive unoptimized version of this algorithim
Output
======
entropyImage - Contains a grayscale image representing the entropy of each pixel
*/
void GetEntropyImage( const Mat *graySrc, uint neighborhoodSize, Mat *entropyImage, bool bDoNaive )
{
//
// 256 comes from 0-255 aka the possible values for a pixel in a grayscale image
//
const int NUMBER_OF_BUCKETS = 256;
int lumionisity,
buckets[NUMBER_OF_BUCKETS] = { 0 };
float range[] = { 0, 255 },
pixelFuncVal,
summation,
frequency;
Mat hist,
entropyMat;
if( neighborhoodSize <= 0 || !( neighborhoodSize % 2 ) )
{
throw invalid_argument("neighborhoodSize");
}
//
// Creates empyty matrix to assign entropy values to
//
entropyMat = Mat::zeros( graySrc->rows, graySrc->cols, CV_32F );
*entropyImage = Mat::zeros( graySrc->rows, graySrc->cols, CV_8UC1 );
//
// The following values are used here as:
// x,y - The current pixel being evaluated where x is the column and y is the row (aka the key pixel)
// j,q - Used to iterate through a grid around the key pixel, j is the column q is the row
//
for( int y = 0; y < graySrc->rows; y++ )
{
for( int x = 0; x < graySrc->cols; x++ )
{
if( bDoNaive || true )
{
summation = 0;
for( long q = y - neighborhoodSize / 2; q <= y + neighborhoodSize / 2; q++ )
{
for( long j = x - neighborhoodSize / 2; j <= x + neighborhoodSize / 2; j++ )
{
//
// Here we grab the pixels lumionisity value.
// The bin corresponding to this value is incremented.
// The end result is knowing the number of pixels with a certain value, the number corresponds
// with the bin sizes.
//
lumionisity = GetMatPixelVal( graySrc, j, q );
buckets[lumionisity]++;
}
}
}
else
{
throw "TODO";
}
for( int ndx = 0; ndx < NUMBER_OF_BUCKETS; ndx++ )
{
//
// Buckets which have no associated values will not influence the value of the calculation
// and therefore can be skipped.
//
if( buckets[ndx] != 0 )
{
if( bDoNaive )
{
frequency = ( float ) buckets[ndx] / ( float ) ( neighborhoodSize * neighborhoodSize );
summation -= frequency * log2f( frequency );
}
else
{
summation -= entropyCalculation( buckets[ndx], ( neighborhoodSize * neighborhoodSize ) );
}
//
// Reset the number of pixels that fall in this bucket for the future key pixels
//
buckets[ndx] = 0;
}
}
entropyMat.at<float>( y, x ) = summation;
}
}
//
// The entropy values need to be normalized so the lowest value becomes 0
// and the highest value is 255. This allows for display of images entropy.
//
normalize( entropyMat, *entropyImage, 0, 255, NORM_MINMAX, CV_8UC1 );
imshow( "Derp", *entropyImage );
}
<commit_msg>Optimized Entropy Calc and added performance testing<commit_after>// This is the main DLL file.
#include "stdafx.h"
#ifdef RunPerformanceTest
#include <windows.h>
#endif
#include "TreeDetection.h"
#include "stdafx.h"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <map>
#include <fstream>
using namespace std;
using namespace cv;
void GetEntropyImage( const Mat *graySrc, int neighborhoodSize, Mat *entropyImage, bool bDoNaive = false );
vector<float> EntropyFunctionCache;
int CacheBaseSize = -1;
#ifdef RunPerformanceTest
/*
This is the function can be used to a run a performacne test on
the algorithim
Inputs
======
gridSize - size of the square grid to be generated in with testing
bUseNaive - toggles using naive algorithim or the optimized one
Output
======
ReturnValue - returns the microseconds it took to execute the test
*/
LONGLONG PerfTest(unsigned int gridSize, bool bUseNaive )
{
LARGE_INTEGER startTime,
endTime,
elapsedMicroseconds,
tickFreq;
Mat testMat = Mat::zeros( gridSize, gridSize, CV_8U ),
result;
//
// Want the same matrix for each grid size for reproduceability
//
srand( 0 );
for( int x = 0; x < gridSize; x++ )
{
for( int y = 0; y < gridSize; y++ )
{
testMat.at<uchar>( y, x ) = rand() % 256;
}
}
QueryPerformanceFrequency( &tickFreq );
QueryPerformanceCounter( &startTime );
GetEntropyImage( &testMat, 9, &result, bUseNaive );
QueryPerformanceCounter( &endTime );
elapsedMicroseconds.QuadPart = endTime.QuadPart - startTime.QuadPart;
elapsedMicroseconds.QuadPart *= 1000000;
elapsedMicroseconds.QuadPart /= tickFreq.QuadPart;
return elapsedMicroseconds.QuadPart;
}
#endif
/*
This is the function to be called to enter the dll
Inputs
======
FilePath - The file for the entropy function to be calculated on
Output
======
*/
extern "C" _declspec( dllexport ) void Entry( const char *filepath )
{
#ifndef RunPerformanceTest
Mat image = imread( filepath ),
labImage,
luminosityImage,
result;
std::vector<cv::Mat> channels;
string outputPath = filepath;
outputPath = "entropy_" + outputPath;
//
// Converts image from RGB to LAB color space, dropping the A and B channels,
// leaving just the L channel
//
cvtColor( image, labImage, CV_RGB2Lab, 0 );
split( labImage, channels );
luminosityImage = channels[0];
GetEntropyImage( &luminosityImage, 9, &result );
imshow( "derp", result );
#else
Code to test performance
int base = 1;
ofstream myfile;
myfile.open( "A:\perf.txt" );
while( base <= 128 )
{
LONGLONG resultOpt = PerfTest( base, false );
LONGLONG resultNaive = PerfTest( base, true );
myfile << base << "," << resultNaive << "," << resultOpt << "\n";
base++;
}
myfile.close( );*/
#endif
}
/*
This function gets the value at the location of a matrix, it allows for automatic padding of data
Inputs
======
src - The src matrix for the function to be performed on
x - The x coordinates of the pixel
y - The y coordinates of the pixel
Output
======
Return Value - the value of the pixel at the specified location
*/
int GetMatPixelVal( const Mat* src, int x, int y )
{
int val = src->at<uchar>(
borderInterpolate( y, src->rows, BORDER_REFLECT ),
borderInterpolate( x, src->cols, BORDER_REFLECT )
);
return val;
}
/*
This function does the entropy calculation for a given occurence.
It uses a cached value when possible, since the operation is expensive to perform.
Inputs
======
timesOccured - The number of times this luminosity has been seen for a key pixel
numberOfElements - The size of the neighborhood for the calculation
Output
======
Return Value - The result of the entropy calculation
*/
float entropyCalculation( int timesOccured, int numberOfElements )
{
float returnValue,
frequency;
//
// If the size of the neighborhood we are caching changes
// then we need to empty and recreate the cache
//
if( CacheBaseSize != numberOfElements )
{
CacheBaseSize = numberOfElements;
EntropyFunctionCache.clear();
EntropyFunctionCache.insert( EntropyFunctionCache.end(), numberOfElements + 1, ( float ) -1 );
}
if( EntropyFunctionCache[timesOccured] == -1 )
{
frequency = ( float ) timesOccured / ( float ) numberOfElements;
returnValue = frequency * log2f( frequency );
EntropyFunctionCache[timesOccured] = returnValue;
}
else
{
returnValue = EntropyFunctionCache[timesOccured];
}
return returnValue;
}
/*
This function calculates the shannon entropy for an image with a given kernel size
Inputs
======
graySrc - The gray source image for the calculation to be performed
neighborhoodSize - An integer representing the size of the grid that will be used for sampling each pixels entropy
This value must be positive and odd, and an exception will be thrown if it is not.
bDoNaive - Toggle to run the naive unoptimized version of this algorithim
Output
======
entropyImage - Contains a grayscale image representing the entropy of each pixel
*/
void GetEntropyImage( const Mat *graySrc, int neighborhoodSize, Mat *entropyImage, bool bDoNaive )
{
//
// 256 comes from 0-255 aka the possible values for a pixel in a grayscale image
//
const int NUMBER_OF_BUCKETS = 256;
int lumionisity,
buckets[NUMBER_OF_BUCKETS] = { 0 };
float range[] = { 0, 255 },
pixelFuncVal,
summation,
frequency;
Mat hist,
entropyMat;
if( neighborhoodSize <= 0 || !( neighborhoodSize % 2 ) )
{
throw invalid_argument("neighborhoodSize");
}
//
// Creates empyty matrix to assign entropy values to
//
entropyMat = Mat::zeros( graySrc->rows, graySrc->cols, CV_32F );
*entropyImage = Mat::zeros( graySrc->rows, graySrc->cols, CV_8UC1 );
//
// The following values are used here as:
// x,y - The current pixel being evaluated where x is the column and y is the row (aka the key pixel)
// j,q - Used to iterate through a grid around the key pixel, j is the column q is the row
//
for( int y = 0; y < graySrc->rows; y++ )
{
if( !bDoNaive )
{
//
// If we are not in naive mode we need to manually reset the value of the different buckets
// when we move from on row to the next
//
memset( buckets, 0, sizeof( buckets ) );
}
for( int x = 0; x < graySrc->cols; x++ )
{
summation = 0;
if( bDoNaive || x == 0 )
{
//
// This gets the entropy value for all surrounding pixels optimized version uses memoization to
// improve on this, but it needs to happen for the very first column for each row
//
for( long q = y - neighborhoodSize / 2; q <= y + neighborhoodSize / 2; q++ )
{
for( long j = x - neighborhoodSize / 2; j <= x + neighborhoodSize / 2; j++ )
{
//
// Here we grab the pixels lumionisity value.
// The bin corresponding to this value is incremented.
// The end result is knowing the number of pixels with a certain value, the number corresponds
// with the bin sizes.
//
lumionisity = GetMatPixelVal( graySrc, j, q );
buckets[lumionisity]++;
}
}
}
else
{
long columnSub = x - neighborhoodSize / 2 - 1;
long columnAdd = x + neighborhoodSize / 2;
for( long q = y - neighborhoodSize / 2; q <= y + neighborhoodSize / 2; q++ )
{
lumionisity = GetMatPixelVal( graySrc, columnSub, q );
buckets[lumionisity]--;
}
for( long q = y - neighborhoodSize / 2; q <= y + neighborhoodSize / 2; q++ )
{
lumionisity = GetMatPixelVal( graySrc, columnAdd, q );
buckets[lumionisity]++;
}
}
for( int ndx = 0; ndx < NUMBER_OF_BUCKETS; ndx++ )
{
//
// Buckets which have no associated values will not influence the value of the calculation
// and therefore can be skipped.
//
if( buckets[ndx] != 0 )
{
if( bDoNaive )
{
frequency = ( float ) buckets[ndx] / ( float ) ( neighborhoodSize * neighborhoodSize );
summation -= frequency * log2f( frequency );
}
else
{
summation -= entropyCalculation( buckets[ndx], ( neighborhoodSize * neighborhoodSize ) );
}
if( bDoNaive )
{
//
// Reset the number of pixels that fall in this bucket for the future key pixels
//
buckets[ndx] = 0;
}
}
}
entropyMat.at<float>( y, x ) = summation;
}
}
//
// The entropy values need to be normalized so the lowest value becomes 0
// and the highest value is 255. This allows for display of images entropy.
//
normalize( entropyMat, *entropyImage, 0, 255, NORM_MINMAX, CV_8UC1 );
}
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "knn_statistics.h"
namespace foundation {
namespace knn {
//
// QueryStatistics class implementation.
//
QueryStatistics::QueryStatistics()
: m_query_count(0)
{
}
Statistics QueryStatistics::get_statistics() const
{
Statistics stats;
stats.insert("queries", m_query_count);
stats.insert("fetched nodes", m_fetched_nodes);
stats.insert("visited leaves", m_visited_leaves);
stats.insert("tested points", m_tested_points);
return stats;
}
} // namespace knn
} // namespace foundation
<commit_msg>fixed compilation on gcc.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "knn_statistics.h"
namespace foundation {
namespace knn {
//
// QueryStatistics class implementation.
//
QueryStatistics::QueryStatistics()
: m_query_count(0)
{
}
Statistics QueryStatistics::get_statistics() const
{
Statistics stats;
stats.insert<uint64>("queries", m_query_count);
stats.insert("fetched nodes", m_fetched_nodes);
stats.insert("visited leaves", m_visited_leaves);
stats.insert("tested points", m_tested_points);
return stats;
}
} // namespace knn
} // namespace foundation
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "oslbssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/closures.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bssrdf/betterdipolebssrdf.h"
#include "renderer/modeling/bssrdf/bssrdf.h"
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/directionaldipolebssrdf.h"
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
#include "renderer/modeling/bssrdf/normalizeddiffusionbssrdf.h"
#endif
#include "renderer/modeling/bssrdf/standarddipolebssrdf.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <cassert>
using namespace foundation;
namespace renderer
{
namespace
{
//
// OSL BSSRDF.
//
class OSLBSSRDF
: public BSSRDF
{
public:
OSLBSSRDF(
const char* name,
const ParamArray& params)
: BSSRDF(name, params)
{
memset(m_all_bssrdfs, 0, sizeof(BSSRDF*) * NumClosuresIDs);
m_better_dipole =
create_and_register_bssrdf<BetterDipoleBSSRDFFactory>(
SubsurfaceBetterDipoleID,
"better_dipole");
m_dir_dipole =
create_and_register_bssrdf<DirectionalDipoleBSSRDFFactory>(
SubsurfaceDirectionalDipoleID,
"dir_dipole");
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
m_normalized =
create_and_register_bssrdf<NormalizedDiffusionBSSRDFFactory>(
SubsurfaceNormalizedDiffusionID,
"normalized");
#endif
m_std_dipole =
create_and_register_bssrdf<StandardDipoleBSSRDFFactory>(
SubsurfaceStandardDipoleID,
"std_dipole");
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return "osl_bssrdf";
}
virtual bool on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch = 0) APPLESEED_OVERRIDE
{
if (!BSSRDF::on_frame_begin(project, assembly, abort_switch))
return false;
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
{
if (!bsrsdf->on_frame_begin(project, assembly))
return false;
}
}
return true;
}
virtual void on_frame_end(
const Project& project,
const Assembly& assembly) APPLESEED_OVERRIDE
{
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
bsrsdf->on_frame_end(project, assembly);
}
BSSRDF::on_frame_end(project, assembly);
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const
{
return sizeof(CompositeSubsurfaceClosure);
}
virtual void evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset = 0) const APPLESEED_OVERRIDE
{
CompositeSubsurfaceClosure* c = reinterpret_cast<CompositeSubsurfaceClosure*>(input_evaluator.data());
new (c) CompositeSubsurfaceClosure(
shading_point.get_shading_basis(),
shading_point.get_osl_shader_globals().Ci);
prepare_inputs(input_evaluator.data());
}
virtual void prepare_inputs(void* data) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
bssrdf_from_closure_id(c->get_closure_type(i)).prepare_inputs(
c->get_closure_input_values(i));
}
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
if (c->get_num_closures() > 0)
{
sampling_context.split_in_place(1, 1);
const double s = sampling_context.next_double2();
const size_t closure_index = c->choose_closure(s);
sample.m_shading_basis =
&c->get_closure_shading_basis(closure_index);
return
bssrdf_from_closure_id(c->get_closure_type(closure_index)).sample(
sampling_context,
c->get_closure_input_values(closure_index),
sample);
}
return false;
}
virtual void evaluate(
const void* data,
const ShadingPoint& outgoing_point,
const Vector3d& outgoing_dir,
const ShadingPoint& incoming_point,
const Vector3d& incoming_dir,
Spectrum& value) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
value.set(0.0f);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
Spectrum s;
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate(
c->get_closure_input_values(i),
outgoing_point,
outgoing_dir,
incoming_point,
incoming_dir,
s);
s *= c->get_closure_weight(i);
value += s;
}
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double dist) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
double pdf = 0.0;
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
pdf +=
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate_pdf(
c->get_closure_input_values(i),
channel,
dist) * c->get_closure_pdf_weight(i);
}
return pdf;
}
private:
template <typename BSSRDFFactory>
auto_release_ptr<BSSRDF> create_and_register_bssrdf(
const ClosureID cid,
const char* name)
{
auto_release_ptr<BSSRDF> bssrdf = BSSRDFFactory().create(name, ParamArray());
m_all_bssrdfs[cid] = bssrdf.get();
return bssrdf;
}
const BSSRDF& bssrdf_from_closure_id(const ClosureID cid) const
{
const BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
BSSRDF& bssrdf_from_closure_id(const ClosureID cid)
{
BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
auto_release_ptr<BSSRDF> m_better_dipole;
auto_release_ptr<BSSRDF> m_dir_dipole;
auto_release_ptr<BSSRDF> m_gaussian;
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
auto_release_ptr<BSSRDF> m_normalized;
#endif
auto_release_ptr<BSSRDF> m_std_dipole;
BSSRDF* m_all_bssrdfs[NumClosuresIDs];
};
}
//
// OSLBSSRDFFactory class implementation.
//
auto_release_ptr<BSSRDF> OSLBSSRDFFactory::create() const
{
return auto_release_ptr<BSSRDF>(new OSLBSSRDF("osl_bssrdf", ParamArray()));
}
} // namespace renderer
<commit_msg>Small cleanup of OSL bsdf.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "oslbssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/closures.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bssrdf/betterdipolebssrdf.h"
#include "renderer/modeling/bssrdf/bssrdf.h"
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/directionaldipolebssrdf.h"
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
#include "renderer/modeling/bssrdf/normalizeddiffusionbssrdf.h"
#endif
#include "renderer/modeling/bssrdf/standarddipolebssrdf.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <cassert>
using namespace foundation;
namespace renderer
{
namespace
{
//
// OSL BSSRDF.
//
class OSLBSSRDF
: public BSSRDF
{
public:
OSLBSSRDF(
const char* name,
const ParamArray& params)
: BSSRDF(name, params)
{
memset(m_all_bssrdfs, 0, sizeof(BSSRDF*) * NumClosuresIDs);
m_better_dipole =
create_and_register_bssrdf<BetterDipoleBSSRDFFactory>(
SubsurfaceBetterDipoleID,
"better_dipole");
m_dir_dipole =
create_and_register_bssrdf<DirectionalDipoleBSSRDFFactory>(
SubsurfaceDirectionalDipoleID,
"dir_dipole");
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
m_normalized =
create_and_register_bssrdf<NormalizedDiffusionBSSRDFFactory>(
SubsurfaceNormalizedDiffusionID,
"normalized");
#endif
m_std_dipole =
create_and_register_bssrdf<StandardDipoleBSSRDFFactory>(
SubsurfaceStandardDipoleID,
"std_dipole");
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return "osl_bssrdf";
}
virtual bool on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch = 0) APPLESEED_OVERRIDE
{
if (!BSSRDF::on_frame_begin(project, assembly, abort_switch))
return false;
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
{
if (!bsrsdf->on_frame_begin(project, assembly))
return false;
}
}
return true;
}
virtual void on_frame_end(
const Project& project,
const Assembly& assembly) APPLESEED_OVERRIDE
{
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
bsrsdf->on_frame_end(project, assembly);
}
BSSRDF::on_frame_end(project, assembly);
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const
{
return sizeof(CompositeSubsurfaceClosure);
}
virtual void evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset = 0) const APPLESEED_OVERRIDE
{
CompositeSubsurfaceClosure* c = reinterpret_cast<CompositeSubsurfaceClosure*>(input_evaluator.data());
new (c) CompositeSubsurfaceClosure(
shading_point.get_shading_basis(),
shading_point.get_osl_shader_globals().Ci);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
bssrdf_from_closure_id(c->get_closure_type(i)).prepare_inputs(
c->get_closure_input_values(i));
}
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
if (c->get_num_closures() > 0)
{
sampling_context.split_in_place(1, 1);
const double s = sampling_context.next_double2();
const size_t closure_index = c->choose_closure(s);
sample.m_shading_basis =
&c->get_closure_shading_basis(closure_index);
return
bssrdf_from_closure_id(c->get_closure_type(closure_index)).sample(
sampling_context,
c->get_closure_input_values(closure_index),
sample);
}
return false;
}
virtual void evaluate(
const void* data,
const ShadingPoint& outgoing_point,
const Vector3d& outgoing_dir,
const ShadingPoint& incoming_point,
const Vector3d& incoming_dir,
Spectrum& value) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
value.set(0.0f);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
Spectrum s;
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate(
c->get_closure_input_values(i),
outgoing_point,
outgoing_dir,
incoming_point,
incoming_dir,
s);
s *= c->get_closure_weight(i);
value += s;
}
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double dist) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
double pdf = 0.0;
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
pdf +=
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate_pdf(
c->get_closure_input_values(i),
channel,
dist) * c->get_closure_pdf_weight(i);
}
return pdf;
}
private:
template <typename BSSRDFFactory>
auto_release_ptr<BSSRDF> create_and_register_bssrdf(
const ClosureID cid,
const char* name)
{
auto_release_ptr<BSSRDF> bssrdf = BSSRDFFactory().create(name, ParamArray());
m_all_bssrdfs[cid] = bssrdf.get();
return bssrdf;
}
const BSSRDF& bssrdf_from_closure_id(const ClosureID cid) const
{
const BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
BSSRDF& bssrdf_from_closure_id(const ClosureID cid)
{
BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
auto_release_ptr<BSSRDF> m_better_dipole;
auto_release_ptr<BSSRDF> m_dir_dipole;
auto_release_ptr<BSSRDF> m_gaussian;
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
auto_release_ptr<BSSRDF> m_normalized;
#endif
auto_release_ptr<BSSRDF> m_std_dipole;
BSSRDF* m_all_bssrdfs[NumClosuresIDs];
};
}
//
// OSLBSSRDFFactory class implementation.
//
auto_release_ptr<BSSRDF> OSLBSSRDFFactory::create() const
{
return auto_release_ptr<BSSRDF>(new OSLBSSRDF("osl_bssrdf", ParamArray()));
}
} // namespace renderer
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Zhangyi Chen (chenzhangyi01@baidu.com)
#include <algorithm> // std::set_union
#include <gflags/gflags.h>
#include "butil/containers/flat_map.h"
#include "butil/errno.h"
#include "butil/strings/string_number_conversions.h"
#include "brpc/socket.h"
#include "brpc/policy/consistent_hashing_load_balancer.h"
#include "brpc/policy/hasher.h"
namespace brpc {
namespace policy {
// TODO: or 160?
DEFINE_int32(chash_num_replicas, 100,
"default number of replicas per server in chash");
class ReplicaPolicy {
public:
ReplicaPolicy() : _hash_func(nullptr) {}
ReplicaPolicy(HashFunc hash) : _hash_func(hash) {}
virtual ~ReplicaPolicy() = default;
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const = 0;
protected:
HashFunc _hash_func;
};
class DefaultReplicaPolicy : public ReplicaPolicy {
public:
DefaultReplicaPolicy(HashFunc hash) : ReplicaPolicy(hash) {}
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const;
};
bool DefaultReplicaPolicy::Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const {
SocketUniquePtr ptr;
if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) {
return false;
}
replicas->clear();
for (size_t i = 0; i < num_replicas; ++i) {
char host[32];
int len = snprintf(host, sizeof(host), "%s-%lu",
endpoint2str(ptr->remote_side()).c_str(), i);
ConsistentHashingLoadBalancer::Node node;
node.hash = _hash_func(host, len);
node.server_sock = server;
node.server_addr = ptr->remote_side();
replicas->push_back(node);
}
return true;
}
class KetamaReplicaPolicy : public ReplicaPolicy {
public:
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const;
};
bool KetamaReplicaPolicy::Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const {
SocketUniquePtr ptr;
if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) {
return false;
}
replicas->clear();
const size_t points_per_hash = 4;
CHECK(num_replicas % points_per_hash == 0)
<< "Ketam hash replicas number(" << num_replicas << ") should be n*4";
for (size_t i = 0; i < num_replicas / points_per_hash; ++i) {
char host[32];
int len = snprintf(host, sizeof(host), "%s-%lu",
endpoint2str(ptr->remote_side()).c_str(), i);
unsigned char digest[16];
MD5HashSignature(host, len, digest);
for (size_t j = 0; j < points_per_hash; ++j) {
ConsistentHashingLoadBalancer::Node node;
node.server_sock = server;
node.server_addr = ptr->remote_side();
node.hash = ((uint32_t) (digest[3 + j * 4] & 0xFF) << 24)
| ((uint32_t) (digest[2 + j * 4] & 0xFF) << 16)
| ((uint32_t) (digest[1 + j * 4] & 0xFF) << 8)
| (digest[0 + j * 4] & 0xFF);
replicas->push_back(node);
}
}
return true;
}
namespace {
const std::map<std::string, const ReplicaPolicy*> g_replica_policy_map = {
{"murmurhash3", new DefaultReplicaPolicy(MurmurHash32)},
{"md5", new DefaultReplicaPolicy(MD5Hash32)},
{"ketama", new KetamaReplicaPolicy}
};
const ReplicaPolicy* GetReplicaPolicy(const std::string& name) {
auto iter = g_replica_policy_map.find(name);
if (iter != g_replica_policy_map.end()) {
return iter->second;
}
return nullptr;
}
} // namespace
ConsistentHashingLoadBalancer::ConsistentHashingLoadBalancer(const char* name)
: _num_replicas(FLAGS_chash_num_replicas), _name(name) {
_replicas_policy = GetReplicaPolicy(name);
CHECK(_replicas_policy)
<< "Fail to find replica policy for consistency lb: '" << name << '\'';
}
size_t ConsistentHashingLoadBalancer::AddBatch(
std::vector<Node> &bg, const std::vector<Node> &fg,
const std::vector<Node> &servers, bool *executed) {
if (*executed) {
// Hack DBD
return fg.size() - bg.size();
}
*executed = true;
bg.resize(fg.size() + servers.size());
bg.resize(std::set_union(fg.begin(), fg.end(),
servers.begin(), servers.end(), bg.begin())
- bg.begin());
return bg.size() - fg.size();
}
size_t ConsistentHashingLoadBalancer::RemoveBatch(
std::vector<Node> &bg, const std::vector<Node> &fg,
const std::vector<ServerId> &servers, bool *executed) {
if (*executed) {
return bg.size() - fg.size();
}
*executed = true;
if (servers.empty()) {
bg = fg;
return 0;
}
butil::FlatSet<ServerId> id_set;
bool use_set = true;
if (id_set.init(servers.size() * 2) == 0) {
for (size_t i = 0; i < servers.size(); ++i) {
if (id_set.insert(servers[i]) == NULL) {
use_set = false;
break;
}
}
} else {
use_set = false;
}
CHECK(use_set) << "Fail to construct id_set, " << berror();
bg.clear();
for (size_t i = 0; i < fg.size(); ++i) {
const bool removed =
use_set ? (id_set.seek(fg[i].server_sock) != NULL)
: (std::find(servers.begin(), servers.end(),
fg[i].server_sock) != servers.end());
if (!removed) {
bg.push_back(fg[i]);
}
}
return fg.size() - bg.size();
}
size_t ConsistentHashingLoadBalancer::Remove(
std::vector<Node> &bg, const std::vector<Node> &fg,
const ServerId& server, bool *executed) {
if (*executed) {
return bg.size() - fg.size();
}
*executed = true;
bg.clear();
for (size_t i = 0; i < fg.size(); ++i) {
if (fg[i].server_sock != server) {
bg.push_back(fg[i]);
}
}
return fg.size() - bg.size();
}
bool ConsistentHashingLoadBalancer::AddServer(const ServerId& server) {
std::vector<Node> add_nodes;
add_nodes.reserve(_num_replicas);
if (!_replicas_policy->Build(server, _num_replicas, &add_nodes)) {
return false;
}
std::sort(add_nodes.begin(), add_nodes.end());
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(
AddBatch, add_nodes, &executed);
CHECK(ret == 0 || ret == _num_replicas) << ret;
return ret != 0;
}
size_t ConsistentHashingLoadBalancer::AddServersInBatch(
const std::vector<ServerId> &servers) {
std::vector<Node> add_nodes;
add_nodes.reserve(servers.size() * _num_replicas);
std::vector<Node> replicas;
replicas.reserve(_num_replicas);
for (size_t i = 0; i < servers.size(); ++i) {
replicas.clear();
if (_replicas_policy->Build(servers[i], _num_replicas, &replicas)) {
add_nodes.insert(add_nodes.end(), replicas.begin(), replicas.end());
}
}
std::sort(add_nodes.begin(), add_nodes.end());
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(AddBatch, add_nodes, &executed);
CHECK(ret % _num_replicas == 0);
const size_t n = ret / _num_replicas;
LOG_IF(ERROR, n != servers.size())
<< "Fail to AddServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
bool ConsistentHashingLoadBalancer::RemoveServer(const ServerId& server) {
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(Remove, server, &executed);
CHECK(ret == 0 || ret == _num_replicas);
return ret != 0;
}
size_t ConsistentHashingLoadBalancer::RemoveServersInBatch(
const std::vector<ServerId> &servers) {
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(RemoveBatch, servers, &executed);
CHECK(ret % _num_replicas == 0);
const size_t n = ret / _num_replicas;
LOG_IF(ERROR, n != servers.size())
<< "Fail to RemoveServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
LoadBalancer *ConsistentHashingLoadBalancer::New() const {
return new (std::nothrow) ConsistentHashingLoadBalancer(_name.c_str());
}
void ConsistentHashingLoadBalancer::Destroy() {
delete this;
}
int ConsistentHashingLoadBalancer::SelectServer(
const SelectIn &in, SelectOut *out) {
if (!in.has_request_code) {
LOG(ERROR) << "Controller.set_request_code() is required";
return EINVAL;
}
if (in.request_code > UINT_MAX) {
LOG(ERROR) << "request_code must be 32-bit currently";
return EINVAL;
}
butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s;
if (_db_hash_ring.Read(&s) != 0) {
return ENOMEM;
}
if (s->empty()) {
return ENODATA;
}
std::vector<Node>::const_iterator choice =
std::lower_bound(s->begin(), s->end(), (uint32_t)in.request_code);
if (choice == s->end()) {
choice = s->begin();
}
for (size_t i = 0; i < s->size(); ++i) {
if (((i + 1) == s->size() // always take last chance
|| !ExcludedServers::IsExcluded(in.excluded, choice->server_sock.id))
&& Socket::Address(choice->server_sock.id, out->ptr) == 0
&& !(*out->ptr)->IsLogOff()) {
return 0;
} else {
if (++choice == s->end()) {
choice = s->begin();
}
}
}
return EHOSTDOWN;
}
void ConsistentHashingLoadBalancer::Describe(
std::ostream &os, const DescribeOptions& options) {
if (!options.verbose) {
os << "c_hash";
return;
}
os << "ConsistentHashingLoadBalancer {\n"
<< " hash function: " << _name << '\n'
<< " replica per host: " << _num_replicas << '\n';
std::map<butil::EndPoint, double> load_map;
GetLoads(&load_map);
os << " number of hosts: " << load_map.size() << '\n';
os << " load of hosts: {\n";
double expected_load_per_server = 1.0 / load_map.size();
double load_sum = 0;
double load_sqr_sum = 0;
for (std::map<butil::EndPoint, double>::iterator
it = load_map.begin(); it!= load_map.end(); ++it) {
os << " " << it->first << ": " << it->second << '\n';
double normalized_load = it->second / expected_load_per_server;
load_sum += normalized_load;
load_sqr_sum += normalized_load * normalized_load;
}
os << " }\n";
os << "deviation: "
<< sqrt(load_sqr_sum * load_map.size() - load_sum * load_sum)
/ load_map.size();
os << "}\n";
}
void ConsistentHashingLoadBalancer::GetLoads(
std::map<butil::EndPoint, double> *load_map) {
load_map->clear();
std::map<butil::EndPoint, uint32_t> count_map;
do {
butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s;
if (_db_hash_ring.Read(&s) != 0) {
break;
}
if (s->empty()) {
break;
}
count_map[s->begin()->server_addr] +=
s->begin()->hash + (UINT_MAX - (s->end() - 1)->hash);
for (size_t i = 1; i < s->size(); ++i) {
count_map[(*s.get())[i].server_addr] +=
(*s.get())[i].hash - (*s.get())[i - 1].hash;
}
} while (0);
for (std::map<butil::EndPoint, uint32_t>::iterator
it = count_map.begin(); it!= count_map.end(); ++it) {
(*load_map)[it->first] = (double)it->second / UINT_MAX;
}
}
bool ConsistentHashingLoadBalancer::SetParameters(const butil::StringPiece& params) {
butil::StringPairs param_vec;
if (!SplitParameters(params, ¶m_vec)) {
return false;
}
for (const std::pair<std::string, std::string>& param : param_vec) {
if (param.first == "replicas") {
size_t replicas = 0;
if (butil::StringToSizeT(param.second, &replicas)) {
_num_replicas = replicas;
} else {
return false;
}
continue;
}
LOG(ERROR) << "Failed to set this unknown parameters " << param.first << '=' << param.second;
}
return true;
}
} // namespace policy
} // namespace brpc
<commit_msg>fix for ci comments<commit_after>// Copyright (c) 2015 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Zhangyi Chen (chenzhangyi01@baidu.com)
#include <algorithm> // std::set_union
#include <gflags/gflags.h>
#include "butil/containers/flat_map.h"
#include "butil/errno.h"
#include "butil/strings/string_number_conversions.h"
#include "brpc/socket.h"
#include "brpc/policy/consistent_hashing_load_balancer.h"
#include "brpc/policy/hasher.h"
namespace brpc {
namespace policy {
// TODO: or 160?
DEFINE_int32(chash_num_replicas, 100,
"default number of replicas per server in chash");
class ReplicaPolicy {
public:
virtual ~ReplicaPolicy() = default;
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const = 0;
};
class DefaultReplicaPolicy : public ReplicaPolicy {
public:
DefaultReplicaPolicy(HashFunc hash) : _hash_func(hash) {}
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const;
private:
HashFunc _hash_func;
};
bool DefaultReplicaPolicy::Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const {
SocketUniquePtr ptr;
if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) {
return false;
}
replicas->clear();
for (size_t i = 0; i < num_replicas; ++i) {
char host[32];
int len = snprintf(host, sizeof(host), "%s-%lu",
endpoint2str(ptr->remote_side()).c_str(), i);
ConsistentHashingLoadBalancer::Node node;
node.hash = _hash_func(host, len);
node.server_sock = server;
node.server_addr = ptr->remote_side();
replicas->push_back(node);
}
return true;
}
class KetamaReplicaPolicy : public ReplicaPolicy {
public:
virtual bool Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const;
};
bool KetamaReplicaPolicy::Build(ServerId server,
size_t num_replicas,
std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const {
SocketUniquePtr ptr;
if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) {
return false;
}
replicas->clear();
const size_t points_per_hash = 4;
CHECK(num_replicas % points_per_hash == 0)
<< "Ketam hash replicas number(" << num_replicas << ") should be n*4";
for (size_t i = 0; i < num_replicas / points_per_hash; ++i) {
char host[32];
int len = snprintf(host, sizeof(host), "%s-%lu",
endpoint2str(ptr->remote_side()).c_str(), i);
unsigned char digest[16];
MD5HashSignature(host, len, digest);
for (size_t j = 0; j < points_per_hash; ++j) {
ConsistentHashingLoadBalancer::Node node;
node.server_sock = server;
node.server_addr = ptr->remote_side();
node.hash = ((uint32_t) (digest[3 + j * 4] & 0xFF) << 24)
| ((uint32_t) (digest[2 + j * 4] & 0xFF) << 16)
| ((uint32_t) (digest[1 + j * 4] & 0xFF) << 8)
| (digest[0 + j * 4] & 0xFF);
replicas->push_back(node);
}
}
return true;
}
namespace {
const std::map<std::string, const ReplicaPolicy*> g_replica_policy_map = {
{"murmurhash3", new DefaultReplicaPolicy(MurmurHash32)},
{"md5", new DefaultReplicaPolicy(MD5Hash32)},
{"ketama", new KetamaReplicaPolicy}
};
const ReplicaPolicy* GetReplicaPolicy(const std::string& name) {
auto iter = g_replica_policy_map.find(name);
if (iter != g_replica_policy_map.end()) {
return iter->second;
}
return nullptr;
}
} // namespace
ConsistentHashingLoadBalancer::ConsistentHashingLoadBalancer(const char* name)
: _num_replicas(FLAGS_chash_num_replicas), _name(name) {
_replicas_policy = GetReplicaPolicy(name);
CHECK(_replicas_policy)
<< "Fail to find replica policy for consistency lb: '" << name << '\'';
}
size_t ConsistentHashingLoadBalancer::AddBatch(
std::vector<Node> &bg, const std::vector<Node> &fg,
const std::vector<Node> &servers, bool *executed) {
if (*executed) {
// Hack DBD
return fg.size() - bg.size();
}
*executed = true;
bg.resize(fg.size() + servers.size());
bg.resize(std::set_union(fg.begin(), fg.end(),
servers.begin(), servers.end(), bg.begin())
- bg.begin());
return bg.size() - fg.size();
}
size_t ConsistentHashingLoadBalancer::RemoveBatch(
std::vector<Node> &bg, const std::vector<Node> &fg,
const std::vector<ServerId> &servers, bool *executed) {
if (*executed) {
return bg.size() - fg.size();
}
*executed = true;
if (servers.empty()) {
bg = fg;
return 0;
}
butil::FlatSet<ServerId> id_set;
bool use_set = true;
if (id_set.init(servers.size() * 2) == 0) {
for (size_t i = 0; i < servers.size(); ++i) {
if (id_set.insert(servers[i]) == NULL) {
use_set = false;
break;
}
}
} else {
use_set = false;
}
CHECK(use_set) << "Fail to construct id_set, " << berror();
bg.clear();
for (size_t i = 0; i < fg.size(); ++i) {
const bool removed =
use_set ? (id_set.seek(fg[i].server_sock) != NULL)
: (std::find(servers.begin(), servers.end(),
fg[i].server_sock) != servers.end());
if (!removed) {
bg.push_back(fg[i]);
}
}
return fg.size() - bg.size();
}
size_t ConsistentHashingLoadBalancer::Remove(
std::vector<Node> &bg, const std::vector<Node> &fg,
const ServerId& server, bool *executed) {
if (*executed) {
return bg.size() - fg.size();
}
*executed = true;
bg.clear();
for (size_t i = 0; i < fg.size(); ++i) {
if (fg[i].server_sock != server) {
bg.push_back(fg[i]);
}
}
return fg.size() - bg.size();
}
bool ConsistentHashingLoadBalancer::AddServer(const ServerId& server) {
std::vector<Node> add_nodes;
add_nodes.reserve(_num_replicas);
if (!_replicas_policy->Build(server, _num_replicas, &add_nodes)) {
return false;
}
std::sort(add_nodes.begin(), add_nodes.end());
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(
AddBatch, add_nodes, &executed);
CHECK(ret == 0 || ret == _num_replicas) << ret;
return ret != 0;
}
size_t ConsistentHashingLoadBalancer::AddServersInBatch(
const std::vector<ServerId> &servers) {
std::vector<Node> add_nodes;
add_nodes.reserve(servers.size() * _num_replicas);
std::vector<Node> replicas;
replicas.reserve(_num_replicas);
for (size_t i = 0; i < servers.size(); ++i) {
replicas.clear();
if (_replicas_policy->Build(servers[i], _num_replicas, &replicas)) {
add_nodes.insert(add_nodes.end(), replicas.begin(), replicas.end());
}
}
std::sort(add_nodes.begin(), add_nodes.end());
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(AddBatch, add_nodes, &executed);
CHECK(ret % _num_replicas == 0);
const size_t n = ret / _num_replicas;
LOG_IF(ERROR, n != servers.size())
<< "Fail to AddServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
bool ConsistentHashingLoadBalancer::RemoveServer(const ServerId& server) {
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(Remove, server, &executed);
CHECK(ret == 0 || ret == _num_replicas);
return ret != 0;
}
size_t ConsistentHashingLoadBalancer::RemoveServersInBatch(
const std::vector<ServerId> &servers) {
bool executed = false;
const size_t ret = _db_hash_ring.ModifyWithForeground(RemoveBatch, servers, &executed);
CHECK(ret % _num_replicas == 0);
const size_t n = ret / _num_replicas;
LOG_IF(ERROR, n != servers.size())
<< "Fail to RemoveServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
LoadBalancer *ConsistentHashingLoadBalancer::New() const {
return new (std::nothrow) ConsistentHashingLoadBalancer(_name.c_str());
}
void ConsistentHashingLoadBalancer::Destroy() {
delete this;
}
int ConsistentHashingLoadBalancer::SelectServer(
const SelectIn &in, SelectOut *out) {
if (!in.has_request_code) {
LOG(ERROR) << "Controller.set_request_code() is required";
return EINVAL;
}
if (in.request_code > UINT_MAX) {
LOG(ERROR) << "request_code must be 32-bit currently";
return EINVAL;
}
butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s;
if (_db_hash_ring.Read(&s) != 0) {
return ENOMEM;
}
if (s->empty()) {
return ENODATA;
}
std::vector<Node>::const_iterator choice =
std::lower_bound(s->begin(), s->end(), (uint32_t)in.request_code);
if (choice == s->end()) {
choice = s->begin();
}
for (size_t i = 0; i < s->size(); ++i) {
if (((i + 1) == s->size() // always take last chance
|| !ExcludedServers::IsExcluded(in.excluded, choice->server_sock.id))
&& Socket::Address(choice->server_sock.id, out->ptr) == 0
&& !(*out->ptr)->IsLogOff()) {
return 0;
} else {
if (++choice == s->end()) {
choice = s->begin();
}
}
}
return EHOSTDOWN;
}
void ConsistentHashingLoadBalancer::Describe(
std::ostream &os, const DescribeOptions& options) {
if (!options.verbose) {
os << "c_hash";
return;
}
os << "ConsistentHashingLoadBalancer {\n"
<< " hash function: " << _name << '\n'
<< " replica per host: " << _num_replicas << '\n';
std::map<butil::EndPoint, double> load_map;
GetLoads(&load_map);
os << " number of hosts: " << load_map.size() << '\n';
os << " load of hosts: {\n";
double expected_load_per_server = 1.0 / load_map.size();
double load_sum = 0;
double load_sqr_sum = 0;
for (std::map<butil::EndPoint, double>::iterator
it = load_map.begin(); it!= load_map.end(); ++it) {
os << " " << it->first << ": " << it->second << '\n';
double normalized_load = it->second / expected_load_per_server;
load_sum += normalized_load;
load_sqr_sum += normalized_load * normalized_load;
}
os << " }\n";
os << "deviation: "
<< sqrt(load_sqr_sum * load_map.size() - load_sum * load_sum)
/ load_map.size();
os << "}\n";
}
void ConsistentHashingLoadBalancer::GetLoads(
std::map<butil::EndPoint, double> *load_map) {
load_map->clear();
std::map<butil::EndPoint, uint32_t> count_map;
do {
butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s;
if (_db_hash_ring.Read(&s) != 0) {
break;
}
if (s->empty()) {
break;
}
count_map[s->begin()->server_addr] +=
s->begin()->hash + (UINT_MAX - (s->end() - 1)->hash);
for (size_t i = 1; i < s->size(); ++i) {
count_map[(*s.get())[i].server_addr] +=
(*s.get())[i].hash - (*s.get())[i - 1].hash;
}
} while (0);
for (std::map<butil::EndPoint, uint32_t>::iterator
it = count_map.begin(); it!= count_map.end(); ++it) {
(*load_map)[it->first] = (double)it->second / UINT_MAX;
}
}
bool ConsistentHashingLoadBalancer::SetParameters(const butil::StringPiece& params) {
butil::StringPairs param_vec;
if (!SplitParameters(params, ¶m_vec)) {
return false;
}
for (const std::pair<std::string, std::string>& param : param_vec) {
if (param.first == "replicas") {
size_t replicas = 0;
if (butil::StringToSizeT(param.second, &replicas)) {
_num_replicas = replicas;
} else {
return false;
}
continue;
}
LOG(ERROR) << "Failed to set this unknown parameters " << param.first << '=' << param.second;
}
return true;
}
} // namespace policy
} // namespace brpc
<|endoftext|>
|
<commit_before>/**********************************************************************
* File: tessopt.cpp
* Description: Re-implementation of the unix code.
* Author: Ray Smith
* Created: Tue Nov 28 05:52:50 MST 1995
*
* (C) Copyright 1995, Hewlett-Packard Co.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <cstring>
#include <stdio.h>
#include "tessopt.h"
int tessoptind;
char *tessoptarg;
/**********************************************************************
* tessopt
*
* parse command line args.
**********************************************************************/
int tessopt ( //parse args
int32_t argc, //arg count
char *argv[], //args
const char *arglist //string of arg chars
) {
const char *arg; //arg char
if (tessoptind == 0)
tessoptind = 1;
if (tessoptind < argc && argv[tessoptind][0] == '-') {
arg = strchr (arglist, argv[tessoptind][1]);
if (arg == nullptr || *arg == ':')
return '?'; //dud option
tessoptind++;
tessoptarg = argv[tessoptind];
if (arg[1] == ':') {
if (argv[tessoptind - 1][2] != '\0')
//immediately after
tessoptarg = argv[tessoptind - 1] + 2;
else
tessoptind++;
}
return *arg;
}
else
return EOF;
}
<commit_msg>use <cstdio> instead of <stdio.h><commit_after>/**********************************************************************
* File: tessopt.cpp
* Description: Re-implementation of the unix code.
* Author: Ray Smith
* Created: Tue Nov 28 05:52:50 MST 1995
*
* (C) Copyright 1995, Hewlett-Packard Co.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <cstring>
#include <cstdio>
#include "tessopt.h"
int tessoptind;
char *tessoptarg;
/**********************************************************************
* tessopt
*
* parse command line args.
**********************************************************************/
int tessopt ( //parse args
int32_t argc, //arg count
char *argv[], //args
const char *arglist //string of arg chars
) {
const char *arg; //arg char
if (tessoptind == 0)
tessoptind = 1;
if (tessoptind < argc && argv[tessoptind][0] == '-') {
arg = strchr (arglist, argv[tessoptind][1]);
if (arg == nullptr || *arg == ':')
return '?'; //dud option
tessoptind++;
tessoptarg = argv[tessoptind];
if (arg[1] == ':') {
if (argv[tessoptind - 1][2] != '\0')
//immediately after
tessoptarg = argv[tessoptind - 1] + 2;
else
tessoptind++;
}
return *arg;
}
else
return EOF;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include <dlfcn.h>
#include <errno.h>
#include <iconv.h>
#include <pwd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "api/app/renderdoc_app.h"
#include "common/common.h"
#include "common/threading.h"
#include "os/os_specific.h"
#include "strings/string_utils.h"
namespace Keyboard
{
void Init()
{
}
bool PlatformHasKeyInput()
{
return false;
}
void AddInputWindow(WindowingSystem windowSystem, void *wnd)
{
}
void RemoveInputWindow(WindowingSystem windowSystem, void *wnd)
{
}
bool GetKeyState(int key)
{
return false;
}
}
namespace FileIO
{
rdcstr GetTempRootPath()
{
return "/tmp";
}
rdcstr GetAppFolderFilename(const rdcstr &filename)
{
const char *homedir = NULL;
if(getenv("HOME") != NULL)
{
homedir = getenv("HOME");
RDCLOG("$HOME value is %s", homedir);
}
else
{
RDCLOG("$HOME value is NULL");
homedir = getpwuid(getuid())->pw_dir;
}
rdcstr ret = rdcstr(homedir) + "/.renderdoc/";
mkdir(ret.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
return ret + filename;
}
void GetExecutableFilename(rdcstr &selfName)
{
char path[512] = {0};
readlink("/proc/self/exe", path, 511);
selfName = rdcstr(path);
}
int LibraryLocator = 42;
void GetLibraryFilename(rdcstr &selfName)
{
// this is a hack, but the only reliable way to find the absolute path to the library.
// dladdr would be fine but it returns the wrong result for symbols in the library
rdcstr librenderdoc_path;
FILE *f = fopen("/proc/self/maps", "r");
if(f)
{
// read the whole thing in one go. There's no need to try and be tight with
// this allocation, so just make sure we can read everything.
char *map_string = new char[1024 * 1024];
memset(map_string, 0, 1024 * 1024);
::fread(map_string, 1, 1024 * 1024, f);
::fclose(f);
char *c = strstr(map_string, "/librenderdoc.so");
if(c)
{
// walk backwards until we hit the start of the line
while(c > map_string)
{
c--;
if(c[0] == '\n')
{
c++;
break;
}
}
// walk forwards across the address range (00400000-0040c000)
while(isalnum(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// permissions (r-xp)
while(isalpha(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// offset (0000b000)
while(isalnum(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// dev
while(isalnum(c[0]) || c[0] == ':')
c++;
// whitespace
while(c[0] == ' ')
c++;
// inode
while(isdigit(c[0]))
c++;
// whitespace
while(c[0] == ' ')
c++;
// FINALLY we are at the start of the actual path
char *end = strchr(c, '\n');
if(end)
librenderdoc_path = rdcstr(c, end - c);
}
delete[] map_string;
}
if(librenderdoc_path.empty())
{
RDCWARN("Couldn't get librenderdoc.so path from /proc/self/maps, falling back to dladdr");
Dl_info info;
if(dladdr(&LibraryLocator, &info))
librenderdoc_path = info.dli_fname;
}
selfName = librenderdoc_path;
}
};
namespace StringFormat
{
// cache iconv_t descriptor to save on iconv_open/iconv_close each time
iconv_t iconvWide2UTF8 = (iconv_t)-1;
iconv_t iconvUTF82Wide = (iconv_t)-1;
// iconv is not thread safe when sharing an iconv_t descriptor
// I don't expect much contention but if it happens we could TryLock
// before creating a temporary iconv_t, or hold two iconv_ts, or something.
Threading::CriticalSection iconvLock;
void Shutdown()
{
SCOPED_LOCK(iconvLock);
if(iconvWide2UTF8 != (iconv_t)-1)
iconv_close(iconvWide2UTF8);
iconvWide2UTF8 = (iconv_t)-1;
if(iconvUTF82Wide != (iconv_t)-1)
iconv_close(iconvUTF82Wide);
iconvUTF82Wide = (iconv_t)-1;
}
rdcstr Wide2UTF8(const rdcwstr &s)
{
// include room for null terminator, assuming unicode input (not ucs)
// utf-8 characters can be max 4 bytes.
size_t len = (s.length() + 1) * 4;
rdcarray<char> charBuffer(len);
size_t ret;
{
SCOPED_LOCK(iconvLock);
if(iconvWide2UTF8 == (iconv_t)-1)
iconvWide2UTF8 = iconv_open("UTF-8", "WCHAR_T");
if(iconvWide2UTF8 == (iconv_t)-1)
{
RDCERR("Couldn't open iconv for WCHAR_T to UTF-8: %d", errno);
return "";
}
char *inbuf = (char *)s.c_str();
size_t insize = (s.length() + 1) * sizeof(wchar_t); // include null terminator
char *outbuf = &charBuffer[0];
size_t outsize = len;
ret = iconv(iconvWide2UTF8, &inbuf, &insize, &outbuf, &outsize);
}
if(ret == (size_t)-1)
{
#if ENABLED(RDOC_DEVEL)
RDCWARN("Failed to convert wstring");
#endif
return "";
}
// convert to string from null-terminated string - utf-8 never contains
// 0 bytes before the null terminator, and this way we don't care if
// charBuffer is larger than the string
return rdcstr(&charBuffer[0]);
}
rdcwstr UTF82Wide(const rdcstr &s)
{
// include room for null terminator, for ascii input we need at least as many output chars as
// input.
size_t len = s.length() + 1;
rdcarray<wchar_t> wcharBuffer(len);
size_t ret;
{
SCOPED_LOCK(iconvLock);
if(iconvUTF82Wide == (iconv_t)-1)
iconvUTF82Wide = iconv_open("WCHAR_T", "UTF-8");
if(iconvUTF82Wide == (iconv_t)-1)
{
RDCERR("Couldn't open iconv for UTF-8 to WCHAR_T: %d", errno);
return L"";
}
char *inbuf = (char *)s.c_str();
size_t insize = s.length() + 1; // include null terminator
char *outbuf = (char *)&wcharBuffer[0];
size_t outsize = len * sizeof(wchar_t);
ret = iconv(iconvUTF82Wide, &inbuf, &insize, &outbuf, &outsize);
}
if(ret == (size_t)-1)
{
#if ENABLED(RDOC_DEVEL)
RDCWARN("Failed to convert wstring");
#endif
return L"";
}
// convert to string from null-terminated string
return rdcwstr(&wcharBuffer[0]);
}
};
namespace OSUtility
{
void WriteOutput(int channel, const char *str)
{
if(channel == OSUtility::Output_StdOut)
{
fprintf(stdout, "%s", str);
fflush(stdout);
}
else if(channel == OSUtility::Output_StdErr)
{
fprintf(stderr, "%s", str);
fflush(stderr);
}
}
uint64_t GetMachineIdent()
{
uint64_t ret = MachineIdent_Linux;
#if defined(_M_ARM) || defined(__arm__)
ret |= MachineIdent_Arch_ARM;
#else
ret |= MachineIdent_Arch_x86;
#endif
#if ENABLED(RDOC_X64)
ret |= MachineIdent_64bit;
#else
ret |= MachineIdent_32bit;
#endif
return ret;
}
};
<commit_msg>Fix ggp compilation<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <iconv.h>
#include <pwd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "api/app/renderdoc_app.h"
#include "common/common.h"
#include "common/threading.h"
#include "os/os_specific.h"
#include "strings/string_utils.h"
namespace Keyboard
{
void Init()
{
}
bool PlatformHasKeyInput()
{
return false;
}
void AddInputWindow(WindowingSystem windowSystem, void *wnd)
{
}
void RemoveInputWindow(WindowingSystem windowSystem, void *wnd)
{
}
bool GetKeyState(int key)
{
return false;
}
}
namespace FileIO
{
rdcstr GetTempRootPath()
{
return "/tmp";
}
rdcstr GetAppFolderFilename(const rdcstr &filename)
{
const char *homedir = NULL;
if(getenv("HOME") != NULL)
{
homedir = getenv("HOME");
RDCLOG("$HOME value is %s", homedir);
}
else
{
RDCLOG("$HOME value is NULL");
homedir = getpwuid(getuid())->pw_dir;
}
rdcstr ret = rdcstr(homedir) + "/.renderdoc/";
mkdir(ret.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
return ret + filename;
}
void GetExecutableFilename(rdcstr &selfName)
{
char path[512] = {0};
readlink("/proc/self/exe", path, 511);
selfName = rdcstr(path);
}
int LibraryLocator = 42;
void GetLibraryFilename(rdcstr &selfName)
{
// this is a hack, but the only reliable way to find the absolute path to the library.
// dladdr would be fine but it returns the wrong result for symbols in the library
rdcstr librenderdoc_path;
FILE *f = fopen("/proc/self/maps", "r");
if(f)
{
// read the whole thing in one go. There's no need to try and be tight with
// this allocation, so just make sure we can read everything.
char *map_string = new char[1024 * 1024];
memset(map_string, 0, 1024 * 1024);
::fread(map_string, 1, 1024 * 1024, f);
::fclose(f);
char *c = strstr(map_string, "/librenderdoc.so");
if(c)
{
// walk backwards until we hit the start of the line
while(c > map_string)
{
c--;
if(c[0] == '\n')
{
c++;
break;
}
}
// walk forwards across the address range (00400000-0040c000)
while(isalnum(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// permissions (r-xp)
while(isalpha(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// offset (0000b000)
while(isalnum(c[0]) || c[0] == '-')
c++;
// whitespace
while(c[0] == ' ')
c++;
// dev
while(isalnum(c[0]) || c[0] == ':')
c++;
// whitespace
while(c[0] == ' ')
c++;
// inode
while(isdigit(c[0]))
c++;
// whitespace
while(c[0] == ' ')
c++;
// FINALLY we are at the start of the actual path
char *end = strchr(c, '\n');
if(end)
librenderdoc_path = rdcstr(c, end - c);
}
delete[] map_string;
}
if(librenderdoc_path.empty())
{
RDCWARN("Couldn't get librenderdoc.so path from /proc/self/maps, falling back to dladdr");
Dl_info info;
if(dladdr(&LibraryLocator, &info))
librenderdoc_path = info.dli_fname;
}
selfName = librenderdoc_path;
}
};
namespace StringFormat
{
// cache iconv_t descriptor to save on iconv_open/iconv_close each time
iconv_t iconvWide2UTF8 = (iconv_t)-1;
iconv_t iconvUTF82Wide = (iconv_t)-1;
// iconv is not thread safe when sharing an iconv_t descriptor
// I don't expect much contention but if it happens we could TryLock
// before creating a temporary iconv_t, or hold two iconv_ts, or something.
Threading::CriticalSection iconvLock;
void Shutdown()
{
SCOPED_LOCK(iconvLock);
if(iconvWide2UTF8 != (iconv_t)-1)
iconv_close(iconvWide2UTF8);
iconvWide2UTF8 = (iconv_t)-1;
if(iconvUTF82Wide != (iconv_t)-1)
iconv_close(iconvUTF82Wide);
iconvUTF82Wide = (iconv_t)-1;
}
rdcstr Wide2UTF8(const rdcwstr &s)
{
// include room for null terminator, assuming unicode input (not ucs)
// utf-8 characters can be max 4 bytes.
size_t len = (s.length() + 1) * 4;
rdcarray<char> charBuffer(len);
size_t ret;
{
SCOPED_LOCK(iconvLock);
if(iconvWide2UTF8 == (iconv_t)-1)
iconvWide2UTF8 = iconv_open("UTF-8", "WCHAR_T");
if(iconvWide2UTF8 == (iconv_t)-1)
{
RDCERR("Couldn't open iconv for WCHAR_T to UTF-8: %d", errno);
return "";
}
char *inbuf = (char *)s.c_str();
size_t insize = (s.length() + 1) * sizeof(wchar_t); // include null terminator
char *outbuf = &charBuffer[0];
size_t outsize = len;
ret = iconv(iconvWide2UTF8, &inbuf, &insize, &outbuf, &outsize);
}
if(ret == (size_t)-1)
{
#if ENABLED(RDOC_DEVEL)
RDCWARN("Failed to convert wstring");
#endif
return "";
}
// convert to string from null-terminated string - utf-8 never contains
// 0 bytes before the null terminator, and this way we don't care if
// charBuffer is larger than the string
return rdcstr(&charBuffer[0]);
}
rdcwstr UTF82Wide(const rdcstr &s)
{
// include room for null terminator, for ascii input we need at least as many output chars as
// input.
size_t len = s.length() + 1;
rdcarray<wchar_t> wcharBuffer(len);
size_t ret;
{
SCOPED_LOCK(iconvLock);
if(iconvUTF82Wide == (iconv_t)-1)
iconvUTF82Wide = iconv_open("WCHAR_T", "UTF-8");
if(iconvUTF82Wide == (iconv_t)-1)
{
RDCERR("Couldn't open iconv for UTF-8 to WCHAR_T: %d", errno);
return L"";
}
char *inbuf = (char *)s.c_str();
size_t insize = s.length() + 1; // include null terminator
char *outbuf = (char *)&wcharBuffer[0];
size_t outsize = len * sizeof(wchar_t);
ret = iconv(iconvUTF82Wide, &inbuf, &insize, &outbuf, &outsize);
}
if(ret == (size_t)-1)
{
#if ENABLED(RDOC_DEVEL)
RDCWARN("Failed to convert wstring");
#endif
return L"";
}
// convert to string from null-terminated string
return rdcwstr(&wcharBuffer[0]);
}
};
namespace OSUtility
{
void WriteOutput(int channel, const char *str)
{
if(channel == OSUtility::Output_StdOut)
{
fprintf(stdout, "%s", str);
fflush(stdout);
}
else if(channel == OSUtility::Output_StdErr)
{
fprintf(stderr, "%s", str);
fflush(stderr);
}
}
uint64_t GetMachineIdent()
{
uint64_t ret = MachineIdent_Linux;
#if defined(_M_ARM) || defined(__arm__)
ret |= MachineIdent_Arch_ARM;
#else
ret |= MachineIdent_Arch_x86;
#endif
#if ENABLED(RDOC_X64)
ret |= MachineIdent_64bit;
#else
ret |= MachineIdent_32bit;
#endif
return ret;
}
};
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Number of non-broadcasted elements in a given view
*
* @view The view in question.
* @return Number of elements.
*/
bh_index bh_nelements_nbcast(const bh_view *view)
{
bh_index res = 1;
for (int i = 0; i < view->ndim; ++i)
{
if(view->stride[i] > 0)
res *= view->shape[i];
}
return res;
}
/* Number of element in a given shape
*
* @ndim Number of dimentions
* @shape[] Number of elements in each dimention.
* @return Number of element operations
*/
bh_index bh_nelements(bh_intp ndim,
const bh_index shape[])
{
bh_index res = 1;
for (int i = 0; i < ndim; ++i)
{
res *= shape[i];
}
return res;
}
/* Size of the base array in bytes
*
* @base The base in question
* @return The size of the base array in bytes
*/
bh_index bh_base_size(const bh_base *base)
{
return base->nelem * bh_type_size(base->type);
}
/* Set the view stride to contiguous row-major
*
* @view The view in question
* @return The total number of elements in view
*/
bh_intp bh_set_contiguous_stride(bh_view *view)
{
bh_intp s = 1;
for(bh_intp i=view->ndim-1; i >= 0; --i)
{
view->stride[i] = s;
s *= view->shape[i];
}
return s;
}
/* Updates the view with the complete base
*
* @view The view to update (in-/out-put)
* @base The base assign to the view
* @return The total number of elements in view
*/
void bh_assign_complete_base(bh_view *view, bh_base *base)
{
view->base = base;
view->ndim = 1;
view->start = 0;
view->shape[0] = view->base->nelem;
view->stride[0] = 1;
}
/* Set the data pointer for the view.
* Can only set to non-NULL if the data ptr is already NULL
*
* @view The view in question
* @data The new data pointer
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_set(bh_view* view, bh_data_ptr data)
{
bh_base* base;
if(view == NULL)
{
fprintf(stderr, "Attempt to set data pointer for a null view\n");
return BH_ERROR;
}
base = bh_base_array(view);
if(base->data != NULL && data != NULL)
{
fprintf(stderr, "Attempt to set data pointer an array with existing data pointer\n");
return BH_ERROR;
}
base->data = data;
return BH_SUCCESS;
}
/* Get the data pointer for the view.
*
* @view The view in question
* @result Output data pointer
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_get(bh_view* view, bh_data_ptr* result)
{
bh_base* base;
if(view == NULL)
{
fprintf(stderr, "Attempt to get data pointer for a null view\n");
return BH_ERROR;
}
base = bh_base_array(view);
*result = base->data;
return BH_SUCCESS;
}
/* Allocate data memory for the given base if not already allocated.
* For convenience, the base is allowed to be NULL.
*
* @base The base in question
* @return Error code (BH_SUCCESS, BH_ERROR, BH_OUT_OF_MEMORY)
*/
bh_error bh_data_malloc(bh_base* base)
{
bh_intp bytes;
if(base == NULL)
return BH_SUCCESS;
if(base->data != NULL)
return BH_SUCCESS;
bytes = bh_base_size(base);
if(bytes == 0)//We allow zero sized arrays.
return BH_SUCCESS;
if(bytes < 0)
return BH_ERROR;
base->data = bh_memory_malloc(bytes);
if(base->data == NULL)
{
int errsv = errno;//mmap() sets the errno.
printf("bh_data_malloc() could not allocate a data region. "
"Returned error code: %s.\n", strerror(errsv));
return BH_OUT_OF_MEMORY;
}
return BH_SUCCESS;
}
/* Frees data memory for the given view.
* For convenience, the view is allowed to be NULL.
*
* @base The base in question
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_free(bh_base* base)
{
bh_intp bytes;
if(base == NULL)
return BH_SUCCESS;
if(base->data == NULL)
return BH_SUCCESS;
bytes = bh_base_size(base);
if(bh_memory_free(base->data, bytes) != 0)
{
int errsv = errno;//munmmap() sets the errno.
printf("bh_data_free() could not free a data region. "
"Returned error code: %s.\n", strerror(errsv));
return BH_ERROR;
}
base->data = NULL;
return BH_SUCCESS;
}
/* Retrive the operands of a instruction.
*
* @instruction The instruction in question
* @return The operand list
*/
bh_view *bh_inst_operands(bh_instruction *instruction)
{
return (bh_view *) &instruction->operand;
}
/* Determines whether the base array is a scalar.
*
* @view The view
* @return The boolean answer
*/
bool bh_is_scalar(const bh_view* view)
{
return bh_base_array(view)->nelem == 1;
}
/* Determines whether the operand is a constant
*
* @o The operand
* @return The boolean answer
*/
bool bh_is_constant(const bh_view* o)
{
return (o->base == NULL);
}
/* Flag operand as a constant
*
* @o The operand
*/
void bh_flag_constant(bh_view* o)
{
o->base = NULL;
}
inline int gcd(int a, int b)
{
if (b==0)
return a;
int c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
return b;
}
/* Determines whether two views access some of the same data points
* NB: This functions may return False on two non-overlapping views.
* But will always return True on overlapping views.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_disjoint(const bh_view *a, const bh_view *b)
{
if (bh_is_constant(a) || bh_is_constant(b)) // One is a constant
return true;
if(bh_base_array(a) != bh_base_array(b)) //different base
return true;
if(a->ndim != b->ndim) // we dont handle views of differenr dimensions yet
return false;
int astart = a->start;
int bstart = b->start;
int stride = 1;
for (int i = 0; i < a->ndim; ++i)
{
stride = gcd(a->stride[i], b->stride[i]);
if (stride == 0) // stride is 0 in both views: dimension is virtual
continue;
int as = astart / stride;
int bs = bstart / stride;
int ae = as + a->shape[i] * (a->stride[i]/stride);
int be = bs + b->shape[i] * (b->stride[i]/stride);
if (ae < bs || be < as)
return true;
astart %= stride;
bstart %= stride;
}
if (stride > 1 && a->start % stride != b->start % stride)
return true;
return false;
}
/* Determines whether two views are identical and points
* to the same base array.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_identical(const bh_view *a, const bh_view *b)
{
int i;
if(bh_is_constant(a) || bh_is_constant(b))
return false;
if(a->base != b->base)
return false;
if(a->ndim != b->ndim)
return false;
if(a->start != b->start)
return false;
for(i=0; i<a->ndim; ++i)
{
if(a->shape[i] != b->shape[i])
return false;
if(a->stride[i] != b->stride[i])
return false;
}
return true;
}
/* Determines whether two views are aligned and points
* to the same base array.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_aligned(const bh_view *a, const bh_view *b)
{
if(bh_is_constant(a) || bh_is_constant(b))
return false;
if(a->base != b->base)
return false;
if(a->start != b->start)
return false;
int ia,ib;
for(ia=0,ib=0; ia<a->ndim && ib<b->ndim; ++ia,++ib)
{
while (a->stride[ia] == 0)
if (++ia >= a->ndim)
break;
while (b->stride[ib] == 0)
if (++ib >= b->ndim)
break;
if(a->shape[ia] != b->shape[ib])
return false;
if(a->stride[ia] != b->stride[ib])
return false;
}
if(ia < a->ndim)
while (a->stride[ia] == 0)
if (++ia >= a->ndim)
break;
if(ib < b->ndim)
while (b->stride[ib] == 0)
if (++ib >= b->ndim)
break;
if (ia == a->ndim && ib == b->ndim)
return true;
return false;
}
/* Determines whether instruction 'a' depends on instruction 'b',
* which is true when:
* 'b' writes to an array that 'a' access
* or
* 'a' writes to an array that 'b' access
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_dependency(const bh_instruction *a, const bh_instruction *b)
{
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i]))
return true;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i]))
return true;
}
return false;
}
/* Determines whether it is legal to fuse two instructions into one
* using the broadest possible definition. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* but accepts mismatch in broadcast, reduction, etc.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_fusible(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
/* Determines whether it is legal to fuse two instructions
* without changing any future possible fusings.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_fusible_gently(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(not bh_view_aligned(&a->operand[0], &b->operand[0]))
return false;
const int a_nop = bh_operands(a->opcode);
const int b_nop = bh_operands(b->opcode);
for(int i=1; i<a_nop; ++i)
{
//Check that at least one input in 'b' is aligned with 'a[i]'
bool found_aligned = false;
for(int j=1; j<b_nop; ++j)
{
if(bh_view_aligned(&a->operand[i], &b->operand[j]))
{
found_aligned = true;
break;
}
}
if(not found_aligned)
return false;
}
return true;
}
<commit_msg>core: fixed out-of-bound error in bh_view_aligned()<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Number of non-broadcasted elements in a given view
*
* @view The view in question.
* @return Number of elements.
*/
bh_index bh_nelements_nbcast(const bh_view *view)
{
bh_index res = 1;
for (int i = 0; i < view->ndim; ++i)
{
if(view->stride[i] > 0)
res *= view->shape[i];
}
return res;
}
/* Number of element in a given shape
*
* @ndim Number of dimentions
* @shape[] Number of elements in each dimention.
* @return Number of element operations
*/
bh_index bh_nelements(bh_intp ndim,
const bh_index shape[])
{
bh_index res = 1;
for (int i = 0; i < ndim; ++i)
{
res *= shape[i];
}
return res;
}
/* Size of the base array in bytes
*
* @base The base in question
* @return The size of the base array in bytes
*/
bh_index bh_base_size(const bh_base *base)
{
return base->nelem * bh_type_size(base->type);
}
/* Set the view stride to contiguous row-major
*
* @view The view in question
* @return The total number of elements in view
*/
bh_intp bh_set_contiguous_stride(bh_view *view)
{
bh_intp s = 1;
for(bh_intp i=view->ndim-1; i >= 0; --i)
{
view->stride[i] = s;
s *= view->shape[i];
}
return s;
}
/* Updates the view with the complete base
*
* @view The view to update (in-/out-put)
* @base The base assign to the view
* @return The total number of elements in view
*/
void bh_assign_complete_base(bh_view *view, bh_base *base)
{
view->base = base;
view->ndim = 1;
view->start = 0;
view->shape[0] = view->base->nelem;
view->stride[0] = 1;
}
/* Set the data pointer for the view.
* Can only set to non-NULL if the data ptr is already NULL
*
* @view The view in question
* @data The new data pointer
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_set(bh_view* view, bh_data_ptr data)
{
bh_base* base;
if(view == NULL)
{
fprintf(stderr, "Attempt to set data pointer for a null view\n");
return BH_ERROR;
}
base = bh_base_array(view);
if(base->data != NULL && data != NULL)
{
fprintf(stderr, "Attempt to set data pointer an array with existing data pointer\n");
return BH_ERROR;
}
base->data = data;
return BH_SUCCESS;
}
/* Get the data pointer for the view.
*
* @view The view in question
* @result Output data pointer
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_get(bh_view* view, bh_data_ptr* result)
{
bh_base* base;
if(view == NULL)
{
fprintf(stderr, "Attempt to get data pointer for a null view\n");
return BH_ERROR;
}
base = bh_base_array(view);
*result = base->data;
return BH_SUCCESS;
}
/* Allocate data memory for the given base if not already allocated.
* For convenience, the base is allowed to be NULL.
*
* @base The base in question
* @return Error code (BH_SUCCESS, BH_ERROR, BH_OUT_OF_MEMORY)
*/
bh_error bh_data_malloc(bh_base* base)
{
bh_intp bytes;
if(base == NULL)
return BH_SUCCESS;
if(base->data != NULL)
return BH_SUCCESS;
bytes = bh_base_size(base);
if(bytes == 0)//We allow zero sized arrays.
return BH_SUCCESS;
if(bytes < 0)
return BH_ERROR;
base->data = bh_memory_malloc(bytes);
if(base->data == NULL)
{
int errsv = errno;//mmap() sets the errno.
printf("bh_data_malloc() could not allocate a data region. "
"Returned error code: %s.\n", strerror(errsv));
return BH_OUT_OF_MEMORY;
}
return BH_SUCCESS;
}
/* Frees data memory for the given view.
* For convenience, the view is allowed to be NULL.
*
* @base The base in question
* @return Error code (BH_SUCCESS, BH_ERROR)
*/
bh_error bh_data_free(bh_base* base)
{
bh_intp bytes;
if(base == NULL)
return BH_SUCCESS;
if(base->data == NULL)
return BH_SUCCESS;
bytes = bh_base_size(base);
if(bh_memory_free(base->data, bytes) != 0)
{
int errsv = errno;//munmmap() sets the errno.
printf("bh_data_free() could not free a data region. "
"Returned error code: %s.\n", strerror(errsv));
return BH_ERROR;
}
base->data = NULL;
return BH_SUCCESS;
}
/* Retrive the operands of a instruction.
*
* @instruction The instruction in question
* @return The operand list
*/
bh_view *bh_inst_operands(bh_instruction *instruction)
{
return (bh_view *) &instruction->operand;
}
/* Determines whether the base array is a scalar.
*
* @view The view
* @return The boolean answer
*/
bool bh_is_scalar(const bh_view* view)
{
return bh_base_array(view)->nelem == 1;
}
/* Determines whether the operand is a constant
*
* @o The operand
* @return The boolean answer
*/
bool bh_is_constant(const bh_view* o)
{
return (o->base == NULL);
}
/* Flag operand as a constant
*
* @o The operand
*/
void bh_flag_constant(bh_view* o)
{
o->base = NULL;
}
inline int gcd(int a, int b)
{
if (b==0)
return a;
int c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
return b;
}
/* Determines whether two views access some of the same data points
* NB: This functions may return False on two non-overlapping views.
* But will always return True on overlapping views.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_disjoint(const bh_view *a, const bh_view *b)
{
if (bh_is_constant(a) || bh_is_constant(b)) // One is a constant
return true;
if(bh_base_array(a) != bh_base_array(b)) //different base
return true;
if(a->ndim != b->ndim) // we dont handle views of differenr dimensions yet
return false;
int astart = a->start;
int bstart = b->start;
int stride = 1;
for (int i = 0; i < a->ndim; ++i)
{
stride = gcd(a->stride[i], b->stride[i]);
if (stride == 0) // stride is 0 in both views: dimension is virtual
continue;
int as = astart / stride;
int bs = bstart / stride;
int ae = as + a->shape[i] * (a->stride[i]/stride);
int be = bs + b->shape[i] * (b->stride[i]/stride);
if (ae < bs || be < as)
return true;
astart %= stride;
bstart %= stride;
}
if (stride > 1 && a->start % stride != b->start % stride)
return true;
return false;
}
/* Determines whether two views are identical and points
* to the same base array.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_identical(const bh_view *a, const bh_view *b)
{
int i;
if(bh_is_constant(a) || bh_is_constant(b))
return false;
if(a->base != b->base)
return false;
if(a->ndim != b->ndim)
return false;
if(a->start != b->start)
return false;
for(i=0; i<a->ndim; ++i)
{
if(a->shape[i] != b->shape[i])
return false;
if(a->stride[i] != b->stride[i])
return false;
}
return true;
}
/* Determines whether two views are aligned and points
* to the same base array.
*
* @a The first view
* @b The second view
* @return The boolean answer
*/
bool bh_view_aligned(const bh_view *a, const bh_view *b)
{
if(bh_is_constant(a) || bh_is_constant(b))
return false;
if(a->base != b->base)
return false;
if(a->start != b->start)
return false;
int a_ndim = 0;
for(int i=0; i<a->ndim; ++i)
if(a->stride != 0)
++a_ndim;
int b_ndim = 0;
for(int i=0; i<b->ndim; ++i)
if(b->stride != 0)
++b_ndim;
if(a_ndim != b_ndim)
return false;
int ia=0, ib=0;
for(int i=0; i<a_ndim; ++i)
{
while(a->stride[ia] == 0)
++ia;
while(b->stride[ib] == 0)
++ib;
if(a->shape[ia] != b->shape[ib])
return false;
if(a->stride[ia] != b->stride[ib])
return false;
}
return true;
}
/* Determines whether instruction 'a' depends on instruction 'b',
* which is true when:
* 'b' writes to an array that 'a' access
* or
* 'a' writes to an array that 'b' access
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_dependency(const bh_instruction *a, const bh_instruction *b)
{
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i]))
return true;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i]))
return true;
}
return false;
}
/* Determines whether it is legal to fuse two instructions into one
* using the broadest possible definition. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* but accepts mismatch in broadcast, reduction, etc.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_fusible(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
/* Determines whether it is legal to fuse two instructions
* without changing any future possible fusings.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool bh_instr_fusible_gently(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(not bh_view_aligned(&a->operand[0], &b->operand[0]))
return false;
const int a_nop = bh_operands(a->opcode);
const int b_nop = bh_operands(b->opcode);
for(int i=1; i<a_nop; ++i)
{
//Check that at least one input in 'b' is aligned with 'a[i]'
bool found_aligned = false;
for(int j=1; j<b_nop; ++j)
{
if(bh_view_aligned(&a->operand[i], &b->operand[j]))
{
found_aligned = true;
break;
}
}
if(not found_aligned)
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <limits>
#include <assert.h>
#include "LexicalReordering.h"
#include "InputFileStream.h"
#include "DistortionOrientation.h"
#include "StaticData.h"
using namespace std;
/*
* Load the file pointed to by filename; set up the table according to
* the orientation and condition parameters. Direction will be used
* later for computing the score.
*/
LexicalReordering::LexicalReordering(const std::string &filename,
int orientation, int direction,
int condition, const std::vector<float> weights) :
m_orientation(orientation), m_direction(direction), m_condition(condition), m_weights(weights),
m_filename(filename)
{
const_cast<ScoreIndexManager&>(StaticData::Instance()->GetScoreIndexManager()).AddScoreProducer(this);
// Load the file
LoadFile();
PrintTable();
}
/*
* Loads the file into a map.
*/
void LexicalReordering::LoadFile()
{
InputFileStream inFile(m_filename);
string line = "", key = "";
while (getline(inFile,line))
{
vector<string> tokens = TokenizeMultiCharSeparator(line , "|||");
string f = "", e = "";
// For storing read-in probabilities.
vector<float> probs;
if (m_condition == LexReorderType::Fe)
{
f = tokens[FE_FOREIGN];
e = tokens[FE_ENGLISH];
// if condition is "fe", then concatenate the first two tokens
// to make a single token
key = f + "|||" + e;
probs = Scan<float>(Tokenize(tokens[FE_PROBS]));
}
else
{
// otherwise, key is just foreign
f = tokens[F_FOREIGN];
key = f;
probs = Scan<float>(Tokenize(tokens[F_PROBS]));
}
if (m_orientation == DistortionOrientationType::Monotone)
{
assert(probs.size() == MONO_NUM_PROBS); // 2 backward, 2 forward
}
else
{
assert(probs.size() == MSD_NUM_PROBS); // 3 backward, 3 forward
}
m_orientation_table[key] = probs;
}
inFile.Close();
}
/*
* Print the table in a readable format.
*/
void LexicalReordering::PrintTable()
{
// iterate over map
map<string, vector<float> >::iterator table_iter =
m_orientation_table.begin();
while (table_iter != m_orientation_table.end())
{
// print key
cout << table_iter->first << " ||| ";
// print values
vector<float> val = table_iter->second;
int i=0, num_probs = val.size();
while (i<num_probs-1)
{
cout << val[i] << " ";
i++;
}
cout << val[i] << endl;
table_iter++;
}
}
float LexicalReordering::CalcScore(Hypothesis *hypothesis, int direction)
{
vector<float> val;
//this phrase declaration is to get around const mumbo jumbo and let me call a
//"convert to a string" method
Phrase myphrase = hypothesis->GetPhrase();
int orientation = DistortionOrientation::GetOrientation(hypothesis, direction);
if(m_condition==LexReorderType::Fe)
{
//this key string is be F+'|||'+E from the hypothesis
val=m_orientation_table[myphrase.GetStringRep(hypothesis->GetCurrSourceWordsRange())
+"|||"
+myphrase.GetStringRep(hypothesis->GetCurrTargetWordsRange())];
}
else
{
//this key string is F from the hypothesis
val=m_orientation_table[ myphrase.GetStringRep(hypothesis->GetCurrTargetWordsRange())];
}
int index = 0;
if(m_orientation==DistortionOrientationType::Msd)
{
if(direction==LexReorderType::Backward)
{
if(orientation==DistortionOrientationType::MONO)
{
index=BACK_M;
}
else if(orientation==DistortionOrientationType::SWAP)
{
index=BACK_S;
}
else
{
index=BACK_D;
}
}
else
{
if(orientation==DistortionOrientationType::MONO)
{
index=FOR_M;
}
else if(orientation==DistortionOrientationType::SWAP)
{
index=FOR_S;
}
else
{
index=FOR_D;
}
}
}
else
{
if(direction==LexReorderType::Backward)
{
if(orientation==DistortionOrientationType::MONO)
{
index=BACK_MONO;
}
else
{
index=BACK_NONMONO;
}
}
else
{
if(orientation==DistortionOrientationType::MONO)
{
index=FOR_MONO;
}
else
{
index=FOR_NONMONO;
}
}
}
return val[index];
}
unsigned int LexicalReordering::GetNumScoreComponents() const
{
return 1;
}
const std::string LexicalReordering::GetScoreProducerDescription() const
{
return "Lexicalized reordering score, file=";
}
<commit_msg>more lexical reordering weight stuff<commit_after>#include <iostream>
#include <limits>
#include <assert.h>
#include "LexicalReordering.h"
#include "InputFileStream.h"
#include "DistortionOrientation.h"
#include "StaticData.h"
using namespace std;
/*
* Load the file pointed to by filename; set up the table according to
* the orientation and condition parameters. Direction will be used
* later for computing the score.
*/
LexicalReordering::LexicalReordering(const std::string &filename,
int orientation, int direction,
int condition, const std::vector<float> weights) :
m_orientation(orientation), m_direction(direction), m_condition(condition), m_weights(weights),
m_filename(filename)
{
const_cast<ScoreIndexManager&>(StaticData::Instance()->GetScoreIndexManager()).AddScoreProducer(this);
// Load the file
LoadFile();
PrintTable();
}
/*
* Loads the file into a map.
*/
void LexicalReordering::LoadFile()
{
InputFileStream inFile(m_filename);
string line = "", key = "";
while (getline(inFile,line))
{
vector<string> tokens = TokenizeMultiCharSeparator(line , "|||");
string f = "", e = "";
// For storing read-in probabilities.
vector<float> probs;
if (m_condition == LexReorderType::Fe)
{
f = tokens[FE_FOREIGN];
e = tokens[FE_ENGLISH];
// if condition is "fe", then concatenate the first two tokens
// to make a single token
key = f + "|||" + e;
probs = Scan<float>(Tokenize(tokens[FE_PROBS]));
}
else
{
// otherwise, key is just foreign
f = tokens[F_FOREIGN];
key = f;
probs = Scan<float>(Tokenize(tokens[F_PROBS]));
}
if (m_orientation == DistortionOrientationType::Monotone)
{
assert(probs.size() == MONO_NUM_PROBS); // 2 backward, 2 forward
}
else
{
assert(probs.size() == MSD_NUM_PROBS); // 3 backward, 3 forward
}
m_orientation_table[key] = probs;
}
inFile.Close();
}
/*
* Print the table in a readable format.
*/
void LexicalReordering::PrintTable()
{
// iterate over map
map<string, vector<float> >::iterator table_iter =
m_orientation_table.begin();
while (table_iter != m_orientation_table.end())
{
// print key
cout << table_iter->first << " ||| ";
// print values
vector<float> val = table_iter->second;
int i=0, num_probs = val.size();
while (i<num_probs-1)
{
cout << val[i] << " ";
i++;
}
cout << val[i] << endl;
table_iter++;
}
}
float LexicalReordering::CalcScore(Hypothesis *hypothesis, int direction)
{
if(m_direction==LexReorderType::Bidirectional || m_direction==direction){
vector<float> val;
//this phrase declaration is to get around const mumbo jumbo and let me call a
//"convert to a string" method
Phrase myphrase = hypothesis->GetPhrase();
int orientation = DistortionOrientation::GetOrientation(hypothesis, direction);
if(m_condition==LexReorderType::Fe)
{
//this key string is be F+'|||'+E from the hypothesis
val=m_orientation_table[myphrase.GetStringRep(hypothesis->GetCurrSourceWordsRange())
+"|||"
+myphrase.GetStringRep(hypothesis->GetCurrTargetWordsRange())];
}
else
{
//this key string is F from the hypothesis
val=m_orientation_table[ myphrase.GetStringRep(hypothesis->GetCurrTargetWordsRange())];
}
//will tell us where to look in the table for the probability we need
int index = 0;
//the weight will tell us what to multiply the probability we fetch by
float weight = 1;
int forward_offset = 0;
//the weight vector will be longer if this LexicalReordering is bidirectional,
//containing backward weights then forward weights.
//by probing its size we can see if the LexicalReordering is bidirectional,
//(meaning we need to access the forward weights midvector) and
//if it is Monotone or MSD (which changes where midvector is)
if(m_weights.size()==5){
forward_offset = 2;
}
else if(m_weights.size()==7){
forward_offset = 3;
}
if(m_orientation==DistortionOrientationType::Msd)
{
if(direction==LexReorderType::Backward)
{
if(orientation==DistortionOrientationType::MONO)
{
index=BACK_M;
weight=m_weights[1];
}
else if(orientation==DistortionOrientationType::SWAP)
{
index=BACK_S;
weight=m_weights[2];
}
else
{
index=BACK_D;
weight=m_weights[3];
}
}
else
{
if(orientation==DistortionOrientationType::MONO)
{
index=FOR_M;
weight=m_weights[1+forward_offset];
}
else if(orientation==DistortionOrientationType::SWAP)
{
index=FOR_S;
weight=m_weights[2+forward_offset];
}
else
{
index=FOR_D;
weight=m_weights[3+forward_offset];
}
}
}
else
{
if(direction==LexReorderType::Backward)
{
if(orientation==DistortionOrientationType::MONO)
{
index=BACK_MONO;
weight=m_weights[1];
}
else
{
index=BACK_NONMONO;
weight=m_weights[2];
}
}
else
{
if(orientation==DistortionOrientationType::MONO)
{
index=FOR_MONO;
weight=m_weights[1+forward_offset];
}
else
{
index=FOR_NONMONO;
weight=m_weights[2+forward_offset];
}
}
}
return val[index] * weight;
}
else
{
return 0;
}
}
unsigned int LexicalReordering::GetNumScoreComponents() const
{
return 1;
}
const std::string LexicalReordering::GetScoreProducerDescription() const
{
return "Lexicalized reordering score, file=";
}
<|endoftext|>
|
<commit_before>// The following block tests the following:
// - Only 1 file is generated per translation unit and header file
// - Replacements are written in YAML that matches the expected YAML file
// RUN: rm -rf %t/Test
// RUN: mkdir -p %t/Test
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %t/Test
// RUN: cpp11-migrate -loop-convert -headers -include=%t/Test %t/Test/main.cpp %t/Test/common.cpp --
// Check that only 1 file is generated per translation unit and header file.
// RUN: ls -1 %t/Test | grep -c "main.cpp_common.h_.*.yaml" | grep "^1$"
// RUN: ls -1 %t/Test | grep -c "common.cpp_common.h_.*.yaml" | grep "^1$"
// RUN: cp %S/common.h.yaml %t/Test/main.cpp_common.h.yaml
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%t/Test#g' %S/common.h.yaml > %t/Test/main.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/main.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/main.cpp_common.h.yaml %t/Test/main.cpp_common.h_*.yaml
// RUN: sed -e 's#$(path)#%t/Test#g' -e 's#main.cpp"#common.cpp"#g' %S/common.h.yaml > %t/Test/common.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/common.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/common.cpp_common.h.yaml %t/Test/common.cpp_common.h_*.yaml
//
// The following block tests the following:
// - YAML files are written only when -headers is used
// RUN: rm -rf %t/Test
// RUN: mkdir -p %t/Test
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %t/Test
// RUN: cpp11-migrate -loop-convert -headers -include=%t/Test %t/Test/main.cpp --
// RUN: cpp11-migrate -loop-convert %t/Test/common.cpp --
// Check that only one YAML file is generated from main.cpp and common.h and not from common.cpp and common.h since -header is not specified
// RUN: ls -1 %t/Test | grep -c "main.cpp_common.h_.*.yaml" | grep "^1$"
// RUN: ls -1 %t/Test | not grep "common.cpp_common.h_.*.yaml"
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%t/Test#g' %S/common.h.yaml > %t/Test/main.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/main.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/main.cpp_common.h.yaml %t/Test/main.cpp_common.h_*.yaml
#include "common.h"
void test_header_replacement() {
dostuff();
func2();
}
// FIXME: Investigating on lit-win32.
// REQUIRES: shell
<commit_msg>clang-tools-extra/test/cpp11-migrate/HeaderReplacements/main.cpp: Use FileCheck instead of grep(1).<commit_after>// The following block tests the following:
// - Only 1 file is generated per translation unit and header file
// - Replacements are written in YAML that matches the expected YAML file
// RUN: rm -rf %t/Test
// RUN: mkdir -p %t/Test
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %t/Test
// RUN: cpp11-migrate -loop-convert -headers -include=%t/Test %t/Test/main.cpp %t/Test/common.cpp --
// Check that only 1 file is generated per translation unit and header file.
// RUN: ls -1 %t/Test | FileCheck %s --check-prefix=MAIN_CPP
// RUN: ls -1 %t/Test | FileCheck %s --check-prefix=COMMON_CPP
// RUN: cp %S/common.h.yaml %t/Test/main.cpp_common.h.yaml
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%t/Test#g' %S/common.h.yaml > %t/Test/main.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/main.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/main.cpp_common.h.yaml %t/Test/main.cpp_common.h_*.yaml
// RUN: sed -e 's#$(path)#%t/Test#g' -e 's#main.cpp"#common.cpp"#g' %S/common.h.yaml > %t/Test/common.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/common.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/common.cpp_common.h.yaml %t/Test/common.cpp_common.h_*.yaml
//
// The following block tests the following:
// - YAML files are written only when -headers is used
// RUN: rm -rf %t/Test
// RUN: mkdir -p %t/Test
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %t/Test
// RUN: cpp11-migrate -loop-convert -headers -include=%t/Test %t/Test/main.cpp --
// RUN: cpp11-migrate -loop-convert %t/Test/common.cpp --
// Check that only one YAML file is generated from main.cpp and common.h and not from common.cpp and common.h since -header is not specified
// RUN: ls -1 %t/Test | FileCheck %s --check-prefix=MAIN_CPP
// RUN: ls -1 %t/Test | FileCheck %s --check-prefix=NO_COMMON
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%t/Test#g' %S/common.h.yaml > %t/Test/main.cpp_common.h.yaml
// RUN: sed -i -e 's#\\#/#g' %t/Test/main.cpp_common.h_*.yaml
// RUN: diff -b %t/Test/main.cpp_common.h.yaml %t/Test/main.cpp_common.h_*.yaml
//
// MAIN_CPP: {{^main.cpp_common.h_.*.yaml$}}
// MAIN_CPP-NOT: {{main.cpp_common.h_.*.yaml}}
//
// COMMON_CPP: {{^common.cpp_common.h_.*.yaml$}}
// COMMON_CPP-NOT: {{common.cpp_common.h_.*.yaml}}
//
// NO_COMMON-NOT: {{common.cpp_common.h_.*.yaml}}
#include "common.h"
void test_header_replacement() {
dostuff();
func2();
}
// FIXME: Investigating on lit-win32.
// REQUIRES: shell
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "heap/Heap.h"
namespace WebCore {
void Heap::init(intptr_t* startOfStack)
{
}
void Heap::shutdown()
{
}
}
<commit_msg>Add Oilpan PageMemory abstraction.<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "heap/Heap.h"
#if OS(POSIX)
#include <sys/mman.h>
#include <unistd.h>
#elif OS(WIN)
#include <windows.h>
#endif
namespace WebCore {
#if !OS(POSIX)
static bool IsPowerOf2(size_t power)
{
return !((power - 1) & power);
}
#endif
static size_t osPageSize()
{
#if OS(POSIX)
static const size_t pageSize = getpagesize();
#else
static size_t pageSize = 0;
if (!pageSize) {
SYSTEM_INFO info;
GetSystemInfo(&info);
pageSize = info.dwPageSize;
ASSERT(IsPowerOf2(pageSize));
}
#endif
return pageSize;
}
static Address roundToBlinkPageBoundary(void* base)
{
return reinterpret_cast<Address>((reinterpret_cast<uintptr_t>(base) + blinkPageOffsetMask) & blinkPageBaseMask);
}
static size_t roundToOsPageSize(size_t size)
{
return (size + osPageSize() - 1) & ~(osPageSize() - 1);
}
class MemoryRegion {
public:
MemoryRegion(Address base, size_t size) : m_base(base), m_size(size) { ASSERT(size > 0); }
bool contains(Address addr) const
{
return m_base <= addr && addr < (m_base + m_size);
}
bool contains(const MemoryRegion& other) const
{
return contains(other.m_base) && contains(other.m_base + other.m_size - 1);
}
void release()
{
#if OS(POSIX)
int err = munmap(m_base, m_size);
RELEASE_ASSERT(!err);
#else
bool success = VirtualFree(m_base, 0, MEM_RELEASE);
RELEASE_ASSERT(success);
#endif
}
WARN_UNUSED_RETURN bool commit()
{
#if OS(POSIX)
int err = mprotect(m_base, m_size, PROT_READ | PROT_WRITE);
if (!err) {
madvise(m_base, m_size, MADV_NORMAL);
return true;
}
return false;
#else
void* result = VirtualAlloc(m_base, m_size, MEM_COMMIT, PAGE_READWRITE);
return !!result;
#endif
}
void decommit()
{
#if OS(POSIX)
int err = mprotect(m_base, m_size, PROT_NONE);
RELEASE_ASSERT(!err);
// FIXME: Consider using MADV_FREE on MacOS.
madvise(m_base, m_size, MADV_DONTNEED);
#else
bool success = VirtualFree(m_base, m_size, MEM_DECOMMIT);
RELEASE_ASSERT(success);
#endif
}
Address base() const { return m_base; }
private:
Address m_base;
size_t m_size;
};
// Representation of the memory used for a Blink heap page.
//
// The representation keeps track of two memory regions:
//
// 1. The virtual memory reserved from the sytem in order to be able
// to free all the virtual memory reserved on destruction.
//
// 2. The writable memory (a sub-region of the reserved virtual
// memory region) that is used for the actual heap page payload.
//
// Guard pages are create before and after the writable memory.
class PageMemory {
public:
~PageMemory() { m_reserved.release(); }
bool commit() WARN_UNUSED_RETURN { return m_writable.commit(); }
void decommit() { m_writable.decommit(); }
Address writableStart() { return m_writable.base(); }
// Allocate a virtual address space for the blink page with the
// following layout:
//
// [ guard os page | ... payload ... | guard os page ]
// ^---{ aligned to blink page size }
//
static PageMemory* allocate(size_t payloadSize)
{
ASSERT(payloadSize > 0);
// Virtual memory allocation routines operate in OS page sizes.
// Round up the requested size to nearest os page size.
payloadSize = roundToOsPageSize(payloadSize);
// Overallocate by blinkPageSize and 2 times OS page size to
// ensure a chunk of memory which is blinkPageSize aligned and
// has a system page before and after to use for guarding. We
// unmap the excess memory before returning.
size_t allocationSize = payloadSize + 2 * osPageSize() + blinkPageSize;
#if OS(POSIX)
Address base = static_cast<Address>(mmap(0, allocationSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0));
RELEASE_ASSERT(base != MAP_FAILED);
Address end = base + allocationSize;
Address alignedBase = roundToBlinkPageBoundary(base);
Address payloadBase = alignedBase + osPageSize();
Address payloadEnd = payloadBase + payloadSize;
Address blinkPageEnd = payloadEnd + osPageSize();
// If the allocate memory was not blink page aligned release
// the memory before the aligned address.
if (alignedBase != base)
MemoryRegion(base, alignedBase - base).release();
// Create guard pages by decommiting an OS page before and
// after the payload.
MemoryRegion(alignedBase, osPageSize()).decommit();
MemoryRegion(payloadEnd, osPageSize()).decommit();
// Free the additional memory at the end of the page if any.
if (blinkPageEnd < end)
MemoryRegion(blinkPageEnd, end - blinkPageEnd).release();
return new PageMemory(MemoryRegion(alignedBase, blinkPageEnd - alignedBase), MemoryRegion(payloadBase, payloadSize));
#else
Address base = 0;
Address alignedBase = 0;
// On Windows it is impossible to partially release a region
// of memory allocated by VirtualAlloc. To avoid wasting
// virtual address space we attempt to release a large region
// of memory returned as a whole and then allocate an aligned
// region inside this larger region.
for (int attempt = 0; attempt < 3; attempt++) {
base = static_cast<Address>(VirtualAlloc(0, allocationSize, MEM_RESERVE, PAGE_NOACCESS));
RELEASE_ASSERT(base);
VirtualFree(base, 0, MEM_RELEASE);
alignedBase = roundToBlinkPageBoundary(base);
base = static_cast<Address>(VirtualAlloc(alignedBase, payloadSize + 2 * osPageSize(), MEM_RESERVE, PAGE_NOACCESS));
if (base) {
RELEASE_ASSERT(base == alignedBase);
allocationSize = payloadSize + 2 * osPageSize();
break;
}
}
if (!base) {
// We failed to avoid wasting virtual address space after
// several attempts.
base = static_cast<Address>(VirtualAlloc(0, allocationSize, MEM_RESERVE, PAGE_NOACCESS));
RELEASE_ASSERT(base);
// FIXME: If base is by accident blink page size aligned
// here then we can create two pages out of reserved
// space. Do this.
alignedBase = roundToBlinkPageBoundary(base);
}
Address payloadBase = alignedBase + osPageSize();
PageMemory* storage = new PageMemory(MemoryRegion(base, allocationSize), MemoryRegion(payloadBase, payloadSize));
bool res = storage->commit();
RELEASE_ASSERT(res);
return storage;
#endif
}
private:
PageMemory(const MemoryRegion& reserved, const MemoryRegion& writable)
: m_reserved(reserved)
, m_writable(writable)
{
ASSERT(reserved.contains(writable));
}
MemoryRegion m_reserved;
MemoryRegion m_writable;
};
void Heap::init(intptr_t* startOfStack)
{
}
void Heap::shutdown()
{
}
}
<|endoftext|>
|
<commit_before>/*
* qicomplex.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <getopt.h>
#include <iostream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkComplexToPhaseImageFilter.h"
#include "itkComplexToModulusImageFilter.h"
#include "itkComplexToRealImageFilter.h"
#include "itkComplexToImaginaryImageFilter.h"
#include "itkComposeImageFilter.h"
#include "itkMagnitudeAndPhaseToComplexImageFilter.h"
using namespace std;
const string usage {
"Usage is: qcomplex [input options] [output options] [other options] \n\
\n\
Input is specified with lower case letters. One of the following\n\
combinations must be specified:\n\
-m mag_image -p phase_image\n\
-r real_image -i imaginary_image\n\
-x complex_image\n\
\n\
Output is specified with upper case letters. One or more of the\n\
following can be specified:\n\
-M : Output a magnitude image\n\
-P : Output a phase image\n\
-R : Output a real image\n\
-I : Output an imaginary image\n\
-X : Output a complex image\n\
\n\
Other options:\n\
--double : Use double precision instead of float\n\
--fixge : Fix alternate slice problem with GE data.\n\
\n\
Example:\n\
qicomplex -m mag.nii -p phase.nii -R real.nii -I imag.nii\n"
};
int verbose = false, use_double = false, fixge = false;
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"double", no_argument, &use_double, 1},
{"fixge", no_argument, &fixge, 1},
{0, 0, 0, 0}
};
const char* short_options = "hvm:M:p:P:r:R:i:I:x:X:";
int c, index_ptr = 0;
template<typename TPixel> void Run(int argc, char **argv) {
typedef itk::Image<TPixel, 4> TImage;
typedef itk::Image<complex<TPixel>, 4> TXImage;
typedef itk::ImageFileReader<TImage> TReader;
typedef itk::ImageFileReader<TXImage> TXReader;
typedef itk::ImageFileWriter<TImage> TWriter;
typedef itk::ImageFileWriter<TXImage> TXWriter;
typename TImage::Pointer img1 = ITK_NULLPTR, img2 = ITK_NULLPTR;
typename TXImage::Pointer imgX = ITK_NULLPTR;
if (verbose) cout << "Reading input files" << endl;
bool ri = false, x = false;
optind = 1;
while ((c = getopt(argc, argv, short_options)) != -1) {
switch (c) {
case 'r':
ri = true;
case 'm': {
auto read = TReader::New();
read->SetFileName(optarg);
read->Update();
img1 = read->GetOutput();
} break;
case 'i':
ri = true;
case 'p': {
auto read = TReader::New();
read->SetFileName(optarg);
read->Update();
img2 = read->GetOutput();
} break;
case 'x': {
x = true;
typename TXReader::Pointer readX = TXReader::New();
readX->SetFileName(optarg);
readX->Update();
imgX = readX->GetOutput();
} break;
default: break;
}
}
if (x) {
// Nothing to see here
} else if (ri) {
if (!(img1 && img2)) {
throw(runtime_error("Must set real and imaginary inputs"));
}
if (verbose) cout << "Combining real and imaginary input" << endl;
auto compose = itk::ComposeImageFilter<TImage, TXImage>::New();
compose->SetInput(0, img1);
compose->SetInput(1, img2);
compose->Update();
imgX = compose->GetOutput();
} else {
if (!(img1 && img2)) {
throw(runtime_error("Must set magnitude and phase inputs"));
}
if (verbose) cout << "Combining magnitude and phase input" << endl;
auto compose = itk::MagnitudeAndPhaseToComplexImageFilter<TImage, TImage, TXImage>::New();
compose->SetInput(0, img1);
compose->SetInput(1, img2);
compose->Update();
imgX = compose->GetOutput();
}
if (verbose) cout << "Writing output files" << endl;
typename TWriter::Pointer write = TWriter::New();
optind = 1;
while ((c = getopt(argc, argv, short_options)) != -1) {
switch (c) {
case 'M': {
auto o = itk::ComplexToModulusImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote magnitude image " + string(optarg) << endl;
} break;
case 'P': {
auto o = itk::ComplexToPhaseImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote phase image " + string(optarg) << endl;
} break;
case 'R': {
auto o = itk::ComplexToRealImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote real image " + string(optarg) << endl;
} break;
case 'I': {
auto o = itk::ComplexToImaginaryImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote imaginary image " + string(optarg) << endl;
} break;
case 'X': {
auto writeX = TXWriter::New();
writeX->SetFileName(optarg);
writeX->SetInput(imgX);
writeX->Update();
if (verbose) cout << "Wrote complex image " + string(optarg) << endl;
} break;
default: break;
}
}
}
int main(int argc, char **argv) {
// Do one pass for the general options
bool have_some_options = false;
while ((c = getopt_long(argc, argv, short_options, long_options, &index_ptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 0: break; // A flag
case 'm': case 'M': case 'p': case 'P':
case 'r': case 'R': case 'i': case 'I':
case 'x': case 'X':
have_some_options = true;
break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if (!have_some_options) {
cout << usage << endl;
return EXIT_FAILURE;
}
if (use_double) {
if (verbose) cout << "Using double precision" << endl;
Run<double>(argc, argv);
} else {
if (verbose) cout << "Using float precision" << endl;
Run<float>(argc, argv);
}
return EXIT_SUCCESS;
}
<commit_msg>Implemented fixge option.<commit_after>/*
* qicomplex.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <getopt.h>
#include <iostream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageSliceConstIteratorWithIndex.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "itkComplexToPhaseImageFilter.h"
#include "itkComplexToModulusImageFilter.h"
#include "itkComplexToRealImageFilter.h"
#include "itkComplexToImaginaryImageFilter.h"
#include "itkComposeImageFilter.h"
#include "itkMagnitudeAndPhaseToComplexImageFilter.h"
using namespace std;
namespace itk {
template<typename TImage>
class FixGEFilter : public InPlaceImageFilter<TImage> {
public:
typedef FixGEFilter Self;
typedef InPlaceImageFilter<TImage> Superclass;
typedef SmartPointer<Self> Pointer;
typedef typename TImage::RegionType TRegion;
typedef typename TImage::InternalPixelType TPixel;
itkNewMacro(Self);
itkTypeMacro(FixGEFilter, InPlaceImageFilter);
private:
FixGEFilter(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
protected:
FixGEFilter() {}
~FixGEFilter() {}
public:
virtual void ThreadedGenerateData(const TRegion ®ion, ThreadIdType threadId) override {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
typedef typename TImage::PixelType PixelType;
ImageSliceConstIteratorWithIndex<TImage> inIt(this->GetInput(), region);
ImageSliceIteratorWithIndex<TImage> outIt(this->GetOutput(), region);
inIt.SetFirstDirection(0);
inIt.SetSecondDirection(1);
outIt.SetFirstDirection(0);
outIt.SetSecondDirection(1);
inIt.GoToBegin();
outIt.GoToBegin();
PixelType mult(1); // This works because the complex constructor has default arguments of 0 for real/imaginary parts
while(!inIt.IsAtEnd()) {
while (!inIt.IsAtEndOfSlice()) {
while (!inIt.IsAtEndOfLine()) {
outIt.Set(mult * inIt.Get());
++inIt;
++outIt;
}
inIt.NextLine();
outIt.NextLine();
}
mult = mult * PixelType(-1);
inIt.NextSlice();
outIt.NextSlice();
}
// std::cout << "End " << __PRETTY_FUNCTION__ << std::endl;
}
};
} // End namespace itk
const string usage {
"Usage is: qcomplex [input options] [output options] [other options] \n\
\n\
Input is specified with lower case letters. One of the following\n\
combinations must be specified:\n\
-m mag_image -p phase_image\n\
-r real_image -i imaginary_image\n\
-x complex_image\n\
\n\
Output is specified with upper case letters. One or more of the\n\
following can be specified:\n\
-M : Output a magnitude image\n\
-P : Output a phase image\n\
-R : Output a real image\n\
-I : Output an imaginary image\n\
-X : Output a complex image\n\
\n\
Other options:\n\
--double : Use double precision instead of float\n\
--fixge : Fix alternate slice problem with GE data.\n\
\n\
Example:\n\
qicomplex -m mag.nii -p phase.nii -R real.nii -I imag.nii\n"
};
int verbose = false, use_double = false, fixge = false;
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"double", no_argument, &use_double, 1},
{"fixge", no_argument, &fixge, 1},
{0, 0, 0, 0}
};
const char* short_options = "hvm:M:p:P:r:R:i:I:x:X:";
int c, index_ptr = 0;
template<typename TPixel> void Run(int argc, char **argv) {
typedef itk::Image<TPixel, 4> TImage;
typedef itk::Image<complex<TPixel>, 4> TXImage;
typedef itk::ImageFileReader<TImage> TReader;
typedef itk::ImageFileReader<TXImage> TXReader;
typedef itk::ImageFileWriter<TImage> TWriter;
typedef itk::ImageFileWriter<TXImage> TXWriter;
typename TImage::Pointer img1 = ITK_NULLPTR, img2 = ITK_NULLPTR;
typename TXImage::Pointer imgX = ITK_NULLPTR;
if (verbose) cout << "Reading input files" << endl;
bool ri = false, x = false;
optind = 1;
while ((c = getopt_long(argc, argv, short_options, long_options, &index_ptr)) != -1) {
switch (c) {
case 'r':
ri = true;
case 'm': {
auto read = TReader::New();
read->SetFileName(optarg);
read->Update();
img1 = read->GetOutput();
} break;
case 'i':
ri = true;
case 'p': {
auto read = TReader::New();
read->SetFileName(optarg);
read->Update();
img2 = read->GetOutput();
} break;
case 'x': {
x = true;
typename TXReader::Pointer readX = TXReader::New();
readX->SetFileName(optarg);
readX->Update();
imgX = readX->GetOutput();
} break;
default: break;
}
}
if (x) {
// Nothing to see here
} else if (ri) {
if (!(img1 && img2)) {
throw(runtime_error("Must set real and imaginary inputs"));
}
if (verbose) cout << "Combining real and imaginary input" << endl;
auto compose = itk::ComposeImageFilter<TImage, TXImage>::New();
compose->SetInput(0, img1);
compose->SetInput(1, img2);
compose->Update();
imgX = compose->GetOutput();
} else {
if (!(img1 && img2)) {
throw(runtime_error("Must set magnitude and phase inputs"));
}
if (verbose) cout << "Combining magnitude and phase input" << endl;
auto compose = itk::MagnitudeAndPhaseToComplexImageFilter<TImage, TImage, TXImage>::New();
compose->SetInput(0, img1);
compose->SetInput(1, img2);
compose->Update();
imgX = compose->GetOutput();
}
if (fixge) {
if (verbose) cout << "Fixing GE phase bug" << endl;
auto fix = itk::FixGEFilter<TXImage>::New();
fix->SetInput(imgX);
fix->Update();
imgX = fix->GetOutput();
}
if (verbose) cout << "Writing output files" << endl;
typename TWriter::Pointer write = TWriter::New();
optind = 1;
while ((c = getopt_long(argc, argv, short_options, long_options, &index_ptr)) != -1) {
switch (c) {
case 'M': {
auto o = itk::ComplexToModulusImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote magnitude image " + string(optarg) << endl;
} break;
case 'P': {
auto o = itk::ComplexToPhaseImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote phase image " + string(optarg) << endl;
} break;
case 'R': {
auto o = itk::ComplexToRealImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote real image " + string(optarg) << endl;
} break;
case 'I': {
auto o = itk::ComplexToImaginaryImageFilter<TXImage, TImage>::New();
o->SetInput(imgX);
write->SetFileName(optarg);
write->SetInput(o->GetOutput());
write->Update();
if (verbose) cout << "Wrote imaginary image " + string(optarg) << endl;
} break;
case 'X': {
auto writeX = TXWriter::New();
writeX->SetFileName(optarg);
writeX->SetInput(imgX);
writeX->Update();
if (verbose) cout << "Wrote complex image " + string(optarg) << endl;
} break;
default: break;
}
}
}
int main(int argc, char **argv) {
// Do one pass for the general options
bool have_some_options = false;
while ((c = getopt_long(argc, argv, short_options, long_options, &index_ptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 0: break; // A flag
case 'm': case 'M': case 'p': case 'P':
case 'r': case 'R': case 'i': case 'I':
case 'x': case 'X':
have_some_options = true;
break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if (!have_some_options) {
cout << usage << endl;
return EXIT_FAILURE;
}
if (use_double) {
if (verbose) cout << "Using double precision" << endl;
Run<double>(argc, argv);
} else {
if (verbose) cout << "Using float precision" << endl;
Run<float>(argc, argv);
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <statman>
#include <liveupdate.hpp>
void Statman::store(uint32_t id, liu::Storage& store)
{
store.add_vector<Stat>(id, {m_stats.begin(), m_stats.end()});
}
void Statman::restore(liu::Restore& store)
{
auto stats = store.as_vector<const Stat>();
for (auto& merge_stat : stats)
{
try {
// TODO: merge here
this->get_by_name(merge_stat.name()) = merge_stat;
}
catch (const std::exception& e)
{
this->create(merge_stat.type(), merge_stat.name()) = merge_stat;
}
}
}
<commit_msg>statman: Gracefully ignore old serialization method<commit_after>#include <statman>
#include <liveupdate.hpp>
#define TYPE_BUFFER 11
#define TYPE_VECTOR 12
void Statman::store(uint32_t id, liu::Storage& store)
{
store.add_vector<Stat>(id, {m_stats.begin(), m_stats.end()});
}
void Statman::restore(liu::Restore& store)
{
if (store.get_type() != TYPE_VECTOR) {
assert(store.get_type() == TYPE_BUFFER);
// discard old stats that was stored as buffer
return;
}
auto stats = store.as_vector<const Stat>();
for (auto& merge_stat : stats)
{
try {
// TODO: merge here
this->get_by_name(merge_stat.name()) = merge_stat;
}
catch (const std::exception& e)
{
this->create(merge_stat.type(), merge_stat.name()) = merge_stat;
}
}
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <limits>
// Local includes
#include "libmesh/elem.h"
#include "libmesh/error_vector.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/dof_map.h"
#include "libmesh/equation_systems.h"
#include "libmesh/explicit_system.h"
#include "libmesh/mesh_base.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/gmv_io.h"
#include "libmesh/tecplot_io.h"
#include "libmesh/exodusII_io.h"
namespace libMesh
{
// ------------------------------------------------------------
// ErrorVector class member functions
ErrorVectorReal ErrorVector::minimum() const
{
LOG_SCOPE ("minimum()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
ErrorVectorReal min = std::numeric_limits<ErrorVectorReal>::max();
for (dof_id_type i=0; i<n; i++)
{
// Only positive (or zero) values in the error vector
libmesh_assert_greater_equal ((*this)[i], 0.);
if (this->is_active_elem(i))
min = std::min (min, (*this)[i]);
}
// ErrorVectors are for positive values
libmesh_assert_greater_equal (min, 0.);
return min;
}
Real ErrorVector::mean() const
{
LOG_SCOPE ("mean()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
Real the_mean = 0;
dof_id_type nnz = 0;
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
the_mean += ( static_cast<Real>((*this)[i]) - the_mean ) / (nnz + 1);
nnz++;
}
return the_mean;
}
Real ErrorVector::median()
{
const dof_id_type n = cast_int<dof_id_type>(this->size());
if (n == 0)
return 0.;
// Build a StatisticsVector<ErrorVectorReal> containing
// only our active entries and take its mean
StatisticsVector<ErrorVectorReal> sv;
sv.reserve (n);
for (dof_id_type i=0; i<n; i++)
if(this->is_active_elem(i))
sv.push_back((*this)[i]);
return sv.median();
}
Real ErrorVector::median() const
{
ErrorVector ev = (*this);
return ev.median();
}
Real ErrorVector::variance(const Real mean_in) const
{
const dof_id_type n = cast_int<dof_id_type>(this->size());
LOG_SCOPE ("variance()", "ErrorVector");
Real the_variance = 0;
dof_id_type nnz = 0;
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
const Real delta = ( static_cast<Real>((*this)[i]) - mean_in );
the_variance += (delta * delta - the_variance) / (nnz + 1);
nnz++;
}
return the_variance;
}
std::vector<dof_id_type> ErrorVector::cut_below(Real cut) const
{
LOG_SCOPE ("cut_below()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
std::vector<dof_id_type> cut_indices;
cut_indices.reserve(n/2); // Arbitrary
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
if ((*this)[i] < cut)
{
cut_indices.push_back(i);
}
}
return cut_indices;
}
std::vector<dof_id_type> ErrorVector::cut_above(Real cut) const
{
LOG_SCOPE ("cut_above()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
std::vector<dof_id_type> cut_indices;
cut_indices.reserve(n/2); // Arbitrary
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
if ((*this)[i] > cut)
{
cut_indices.push_back(i);
}
}
return cut_indices;
}
bool ErrorVector::is_active_elem (dof_id_type i) const
{
libmesh_assert_less (i, this->size());
if (_mesh)
{
return _mesh->elem_ptr(i)->active();
}
else
return ((*this)[i] != 0.);
}
void ErrorVector::plot_error(const std::string & filename,
const MeshBase & oldmesh) const
{
UniquePtr<MeshBase> meshptr = oldmesh.clone();
MeshBase & mesh = *meshptr;
// The all_first_order routine requires that renumbering be allowed
mesh.allow_renumbering(true);
mesh.all_first_order();
// We don't want p elevation when plotting a single constant value
// per element
{
MeshBase::element_iterator el =
mesh.elements_begin();
const MeshBase::element_iterator end_el =
mesh.elements_end();
for ( ; el != end_el; ++el)
{
Elem * elem = *el;
elem->set_p_refinement_flag(Elem::DO_NOTHING);
elem->set_p_level(0);
}
}
EquationSystems temp_es (mesh);
ExplicitSystem & error_system
= temp_es.add_system<ExplicitSystem> ("Error");
error_system.add_variable("error", CONSTANT, MONOMIAL);
temp_es.init();
const DofMap & error_dof_map = error_system.get_dof_map();
MeshBase::const_element_iterator el =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
mesh.active_local_elements_end();
std::vector<dof_id_type> dof_indices;
for ( ; el != end_el; ++el)
{
const Elem * elem = *el;
error_dof_map.dof_indices(elem, dof_indices);
const dof_id_type elem_id = elem->id();
//0 for the monomial basis
const dof_id_type solution_index = dof_indices[0];
// libMesh::out << "elem_number=" << elem_number << std::endl;
libmesh_assert_less (elem_id, (*this).size());
// We may have zero error values in special circumstances
// libmesh_assert_greater ((*this)[elem_id], 0.);
error_system.solution->set(solution_index, (*this)[elem_id]);
}
error_system.solution->close();
// We may have to renumber if the original numbering was not
// contiguous. Since this is just a temporary mesh, that's probably
// fine.
if (mesh.max_elem_id() != mesh.n_elem() ||
mesh.max_node_id() != mesh.n_nodes())
{
mesh.allow_renumbering(true);
mesh.renumber_nodes_and_elements();
}
if (filename.rfind(".gmv") < filename.size())
{
GMVIO(mesh).write_discontinuous_gmv(filename,
temp_es, false);
}
else if (filename.rfind(".plt") < filename.size())
{
TecplotIO (mesh).write_equation_systems
(filename, temp_es);
}
#ifdef LIBMESH_HAVE_EXODUS_API
else if( (filename.rfind(".exo") < filename.size()) ||
(filename.rfind(".e") < filename.size()) )
{
ExodusII_IO io(mesh);
io.write(filename);
io.write_element_data(temp_es);
}
#endif
else
{
libmesh_here();
libMesh::err << "Warning: ErrorVector::plot_error currently only"
<< " supports .gmv and .plt and .exo/.e (if enabled) output;" << std::endl;
libMesh::err << "Could not recognize filename: " << filename
<< std::endl;
}
}
} // namespace libMesh
<commit_msg>ErrorVector: Only reset p elevation if AMR is enabled<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <limits>
// Local includes
#include "libmesh/elem.h"
#include "libmesh/error_vector.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/dof_map.h"
#include "libmesh/equation_systems.h"
#include "libmesh/explicit_system.h"
#include "libmesh/mesh_base.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/gmv_io.h"
#include "libmesh/tecplot_io.h"
#include "libmesh/exodusII_io.h"
namespace libMesh
{
// ------------------------------------------------------------
// ErrorVector class member functions
ErrorVectorReal ErrorVector::minimum() const
{
LOG_SCOPE ("minimum()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
ErrorVectorReal min = std::numeric_limits<ErrorVectorReal>::max();
for (dof_id_type i=0; i<n; i++)
{
// Only positive (or zero) values in the error vector
libmesh_assert_greater_equal ((*this)[i], 0.);
if (this->is_active_elem(i))
min = std::min (min, (*this)[i]);
}
// ErrorVectors are for positive values
libmesh_assert_greater_equal (min, 0.);
return min;
}
Real ErrorVector::mean() const
{
LOG_SCOPE ("mean()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
Real the_mean = 0;
dof_id_type nnz = 0;
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
the_mean += ( static_cast<Real>((*this)[i]) - the_mean ) / (nnz + 1);
nnz++;
}
return the_mean;
}
Real ErrorVector::median()
{
const dof_id_type n = cast_int<dof_id_type>(this->size());
if (n == 0)
return 0.;
// Build a StatisticsVector<ErrorVectorReal> containing
// only our active entries and take its mean
StatisticsVector<ErrorVectorReal> sv;
sv.reserve (n);
for (dof_id_type i=0; i<n; i++)
if(this->is_active_elem(i))
sv.push_back((*this)[i]);
return sv.median();
}
Real ErrorVector::median() const
{
ErrorVector ev = (*this);
return ev.median();
}
Real ErrorVector::variance(const Real mean_in) const
{
const dof_id_type n = cast_int<dof_id_type>(this->size());
LOG_SCOPE ("variance()", "ErrorVector");
Real the_variance = 0;
dof_id_type nnz = 0;
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
const Real delta = ( static_cast<Real>((*this)[i]) - mean_in );
the_variance += (delta * delta - the_variance) / (nnz + 1);
nnz++;
}
return the_variance;
}
std::vector<dof_id_type> ErrorVector::cut_below(Real cut) const
{
LOG_SCOPE ("cut_below()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
std::vector<dof_id_type> cut_indices;
cut_indices.reserve(n/2); // Arbitrary
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
if ((*this)[i] < cut)
{
cut_indices.push_back(i);
}
}
return cut_indices;
}
std::vector<dof_id_type> ErrorVector::cut_above(Real cut) const
{
LOG_SCOPE ("cut_above()", "ErrorVector");
const dof_id_type n = cast_int<dof_id_type>(this->size());
std::vector<dof_id_type> cut_indices;
cut_indices.reserve(n/2); // Arbitrary
for (dof_id_type i=0; i<n; i++)
if (this->is_active_elem(i))
{
if ((*this)[i] > cut)
{
cut_indices.push_back(i);
}
}
return cut_indices;
}
bool ErrorVector::is_active_elem (dof_id_type i) const
{
libmesh_assert_less (i, this->size());
if (_mesh)
{
return _mesh->elem_ptr(i)->active();
}
else
return ((*this)[i] != 0.);
}
void ErrorVector::plot_error(const std::string & filename,
const MeshBase & oldmesh) const
{
UniquePtr<MeshBase> meshptr = oldmesh.clone();
MeshBase & mesh = *meshptr;
// The all_first_order routine requires that renumbering be allowed
mesh.allow_renumbering(true);
mesh.all_first_order();
#ifdef LIBMESH_ENABLE_AMR
// We don't want p elevation when plotting a single constant value
// per element
{
MeshBase::element_iterator el =
mesh.elements_begin();
const MeshBase::element_iterator end_el =
mesh.elements_end();
for ( ; el != end_el; ++el)
{
Elem * elem = *el;
elem->set_p_refinement_flag(Elem::DO_NOTHING);
elem->set_p_level(0);
}
}
#endif // LIBMESH_ENABLE_AMR
EquationSystems temp_es (mesh);
ExplicitSystem & error_system
= temp_es.add_system<ExplicitSystem> ("Error");
error_system.add_variable("error", CONSTANT, MONOMIAL);
temp_es.init();
const DofMap & error_dof_map = error_system.get_dof_map();
MeshBase::const_element_iterator el =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
mesh.active_local_elements_end();
std::vector<dof_id_type> dof_indices;
for ( ; el != end_el; ++el)
{
const Elem * elem = *el;
error_dof_map.dof_indices(elem, dof_indices);
const dof_id_type elem_id = elem->id();
//0 for the monomial basis
const dof_id_type solution_index = dof_indices[0];
// libMesh::out << "elem_number=" << elem_number << std::endl;
libmesh_assert_less (elem_id, (*this).size());
// We may have zero error values in special circumstances
// libmesh_assert_greater ((*this)[elem_id], 0.);
error_system.solution->set(solution_index, (*this)[elem_id]);
}
error_system.solution->close();
// We may have to renumber if the original numbering was not
// contiguous. Since this is just a temporary mesh, that's probably
// fine.
if (mesh.max_elem_id() != mesh.n_elem() ||
mesh.max_node_id() != mesh.n_nodes())
{
mesh.allow_renumbering(true);
mesh.renumber_nodes_and_elements();
}
if (filename.rfind(".gmv") < filename.size())
{
GMVIO(mesh).write_discontinuous_gmv(filename,
temp_es, false);
}
else if (filename.rfind(".plt") < filename.size())
{
TecplotIO (mesh).write_equation_systems
(filename, temp_es);
}
#ifdef LIBMESH_HAVE_EXODUS_API
else if( (filename.rfind(".exo") < filename.size()) ||
(filename.rfind(".e") < filename.size()) )
{
ExodusII_IO io(mesh);
io.write(filename);
io.write_element_data(temp_es);
}
#endif
else
{
libmesh_here();
libMesh::err << "Warning: ErrorVector::plot_error currently only"
<< " supports .gmv and .plt and .exo/.e (if enabled) output;" << std::endl;
libMesh::err << "Could not recognize filename: " << filename
<< std::endl;
}
}
} // namespace libMesh
<|endoftext|>
|
<commit_before>#include "listmethodscommand.h"
#include <QScriptValueIterator>
#include "scriptengine.h"
#include "util.h"
#define super AdminCommand
ListMethodsCommand::ListMethodsCommand(QObject *parent) :
super(parent) {
setDescription("List all JavaScript-accessible methods of an object.\n"
"\n"
"Usage: list-methods <object-name> [#]");
}
ListMethodsCommand::~ListMethodsCommand() {
}
void ListMethodsCommand::execute(Player *player, const QString &command) {
super::prepareExecute(player, command);
GameObjectPtrList objects = takeObjects(currentRoom()->objects());
if (!requireUnique(objects, "Object not found.", "Object is not unique.")) {
return;
}
GameObjectPtr object = objects[0];
send(QString("These are all known methods of %1:\n"
"\n").arg(Util::highlight(QString("object #%1").arg(object->id()))));
ScriptEngine *scriptEngine = ScriptEngine::instance();
QScriptValue value = scriptEngine->evaluate(QString("Object.keys($('%1:%2'))")
.arg(object->objectType().toString())
.arg(object->id()));
QScriptValueIterator it(value);
while (it.hasNext()) {
it.next();
QString key = it.value().toString();
if (key.contains('(') && !key.startsWith("destroyed(") &&
!key.contains(QRegExp("[(,]Options\\)"))) {
key = key.replace("QString", "string").replace("QScriptValue", "value")
.replace("GameObjectPtr", "GameObject").replace(",", ", ");
send(QString(" %1\n").arg(Util::highlight(key)));
}
}
}
<commit_msg>Fix list-methods command.<commit_after>#include "listmethodscommand.h"
#include <QScriptValueIterator>
#include "scriptengine.h"
#include "util.h"
#define super AdminCommand
ListMethodsCommand::ListMethodsCommand(QObject *parent) :
super(parent) {
setDescription("List all JavaScript-accessible methods of an object.\n"
"\n"
"Usage: list-methods <object-name> [#]");
}
ListMethodsCommand::~ListMethodsCommand() {
}
void ListMethodsCommand::execute(Player *player, const QString &command) {
super::prepareExecute(player, command);
GameObjectPtrList objects = takeObjects(currentRoom()->objects());
if (!requireUnique(objects, "Object not found.", "Object is not unique.")) {
return;
}
GameObjectPtr object = objects[0];
send(QString("These are all known methods of %1:\n"
"\n").arg(Util::highlight(QString("object #%1").arg(object->id()))));
ScriptEngine *scriptEngine = ScriptEngine::instance();
QScriptValue value = scriptEngine->evaluate(QString("Object.keys($('%1:%2'))")
.arg(QString(object->objectType().toString()).toLower())
.arg(object->id()));
QScriptValueIterator it(value);
while (it.hasNext()) {
it.next();
QString key = it.value().toString();
if (key.contains('(') && !key.startsWith("destroyed(") &&
!key.contains(QRegExp("[(,]Options\\)"))) {
key = key.replace("QString", "string").replace("QScriptValue", "value")
.replace("GameObjectPtr", "GameObject").replace(",", ", ");
send(QString(" %1\n").arg(Util::highlight(key)));
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfilt.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 21:18:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_DOCFILT_HACK_HXX
#define _SFX_DOCFILT_HACK_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_PLUGIN_PLUGINDESCRIPTION_HPP_
#include <com/sun/star/plugin/PluginDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HPP_
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _WLDCRD_HXX //autogen
#include <tools/wldcrd.hxx>
#endif
#define SFX_FILTER_IMPORT 0x00000001L
#define SFX_FILTER_EXPORT 0x00000002L
#define SFX_FILTER_TEMPLATE 0x00000004L
#define SFX_FILTER_INTERNAL 0x00000008L
#define SFX_FILTER_TEMPLATEPATH 0x00000010L
#define SFX_FILTER_OWN 0x00000020L
#define SFX_FILTER_ALIEN 0x00000040L
#define SFX_FILTER_USESOPTIONS 0x00000080L
#define SFX_FILTER_NOTINFILEDLG 0x00001000L
#define SFX_FILTER_NOTINCHOOSER 0x00002000L
#define SFX_FILTER_DEFAULT 0x00000100L
#define SFX_FILTER_EXECUTABLE 0x00000200L
#define SFX_FILTER_SUPPORTSSELECTION 0x00000400L
#define SFX_FILTER_MAPTOAPPPLUG 0x00000800L
#define SFX_FILTER_ASYNC 0x00004000L
// Legt Objekt nur an, kein Laden
#define SFX_FILTER_CREATOR 0x00008000L
#define SFX_FILTER_OPENREADONLY 0x00010000L
#define SFX_FILTER_MUSTINSTALL 0x00020000L
#define SFX_FILTER_CONSULTSERVICE 0x00040000L
#define SFX_FILTER_STARONEFILTER 0x00080000L
#define SFX_FILTER_PACKED 0x00100000L
#define SFX_FILTER_SILENTEXPORT 0x00200000L
#define SFX_FILTER_BROWSERPREFERED 0x00400000L
#define SFX_FILTER_PREFERED 0x10000000L
#define SFX_FILTER_VERSION_NONE 0
#define SFX_FILTER_NOTINSTALLED SFX_FILTER_MUSTINSTALL | SFX_FILTER_CONSULTSERVICE
#include <sfx2/sfxdefs.hxx>
//========================================================================
class SfxFilterContainer;
class SotStorage;
class SFX2_DLLPUBLIC SfxFilter
{
friend class SfxFilterContainer;
WildCard aWildCard;
ULONG lFormat;
String aTypeName;
String aUserData;
SfxFilterFlags nFormatType;
USHORT nDocIcon;
String aServiceName;
String aMimeType;
String aFilterName;
String aPattern;
ULONG nVersion;
String aUIName;
String aDefaultTemplate;
public:
SfxFilter( const String &rName,
const String &rWildCard,
SfxFilterFlags nFormatType,
sal_uInt32 lFormat,
const String &rTypeName,
USHORT nDocIcon,
const String &rMimeType,
const String &rUserData,
const String& rServiceName );
~SfxFilter();
bool IsAllowedAsTemplate() const { return nFormatType & SFX_FILTER_TEMPLATE; }
bool IsOwnFormat() const { return nFormatType & SFX_FILTER_OWN; }
bool IsOwnTemplateFormat() const { return nFormatType & SFX_FILTER_TEMPLATEPATH; }
bool IsAlienFormat() const { return nFormatType & SFX_FILTER_ALIEN; }
bool CanImport() const { return nFormatType & SFX_FILTER_IMPORT; }
bool CanExport() const { return nFormatType & SFX_FILTER_EXPORT; }
bool IsInternal() const { return nFormatType & SFX_FILTER_INTERNAL; }
SfxFilterFlags GetFilterFlags() const { return nFormatType; }
const String& GetFilterName() const { return aFilterName; }
const String& GetMimeType() const { return aMimeType; }
const String& GetName() const { return aFilterName; }
const WildCard& GetWildcard() const { return aWildCard; }
const String& GetRealTypeName() const { return aTypeName; }
ULONG GetFormat() const { return lFormat; }
const String& GetTypeName() const { return aTypeName; }
const String& GetUIName() const { return aUIName; }
USHORT GetDocIconId() const { return nDocIcon; }
const String& GetUserData() const { return aUserData; }
const String& GetDefaultTemplate() const { return aDefaultTemplate; }
void SetDefaultTemplate( const String& rStr ) { aDefaultTemplate = rStr; }
BOOL UsesStorage() const { return GetFormat() != 0; }
void SetURLPattern( const String& rStr ) { aPattern = rStr; aPattern.ToLowerAscii(); }
String GetURLPattern() const { return aPattern; }
void SetUIName( const String& rName ) { aUIName = rName; }
void SetVersion( ULONG nVersionP ) { nVersion = nVersionP; }
ULONG GetVersion() const { return nVersion; }
String GetSuffixes() const;
String GetDefaultExtension() const;
const String& GetServiceName() const { return aServiceName; }
static const SfxFilter* GetDefaultFilter( const String& rName );
static const SfxFilter* GetFilterByName( const String& rName );
static const SfxFilter* GetDefaultFilterFromFactory( const String& rServiceName );
static String GetTypeFromStorage( const SotStorage& rStg );
static String GetTypeFromStorage( const com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage,
BOOL bTemplate = FALSE,
String* pName=0 )
throw ( ::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.280); FILE MERGED 2008/04/01 15:38:22 thb 1.2.280.3: #i85898# Stripping all external header guards 2008/04/01 12:40:34 thb 1.2.280.2: #i85898# Stripping all external header guards 2008/03/31 13:37:55 rt 1.2.280.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfilt.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SFX_DOCFILT_HACK_HXX
#define _SFX_DOCFILT_HACK_HXX
#include "sal/config.h"
#include "sfx2/dllapi.h"
#include "sal/types.h"
#include <com/sun/star/plugin/PluginDescription.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <tools/wldcrd.hxx>
#define SFX_FILTER_IMPORT 0x00000001L
#define SFX_FILTER_EXPORT 0x00000002L
#define SFX_FILTER_TEMPLATE 0x00000004L
#define SFX_FILTER_INTERNAL 0x00000008L
#define SFX_FILTER_TEMPLATEPATH 0x00000010L
#define SFX_FILTER_OWN 0x00000020L
#define SFX_FILTER_ALIEN 0x00000040L
#define SFX_FILTER_USESOPTIONS 0x00000080L
#define SFX_FILTER_NOTINFILEDLG 0x00001000L
#define SFX_FILTER_NOTINCHOOSER 0x00002000L
#define SFX_FILTER_DEFAULT 0x00000100L
#define SFX_FILTER_EXECUTABLE 0x00000200L
#define SFX_FILTER_SUPPORTSSELECTION 0x00000400L
#define SFX_FILTER_MAPTOAPPPLUG 0x00000800L
#define SFX_FILTER_ASYNC 0x00004000L
// Legt Objekt nur an, kein Laden
#define SFX_FILTER_CREATOR 0x00008000L
#define SFX_FILTER_OPENREADONLY 0x00010000L
#define SFX_FILTER_MUSTINSTALL 0x00020000L
#define SFX_FILTER_CONSULTSERVICE 0x00040000L
#define SFX_FILTER_STARONEFILTER 0x00080000L
#define SFX_FILTER_PACKED 0x00100000L
#define SFX_FILTER_SILENTEXPORT 0x00200000L
#define SFX_FILTER_BROWSERPREFERED 0x00400000L
#define SFX_FILTER_PREFERED 0x10000000L
#define SFX_FILTER_VERSION_NONE 0
#define SFX_FILTER_NOTINSTALLED SFX_FILTER_MUSTINSTALL | SFX_FILTER_CONSULTSERVICE
#include <sfx2/sfxdefs.hxx>
//========================================================================
class SfxFilterContainer;
class SotStorage;
class SFX2_DLLPUBLIC SfxFilter
{
friend class SfxFilterContainer;
WildCard aWildCard;
ULONG lFormat;
String aTypeName;
String aUserData;
SfxFilterFlags nFormatType;
USHORT nDocIcon;
String aServiceName;
String aMimeType;
String aFilterName;
String aPattern;
ULONG nVersion;
String aUIName;
String aDefaultTemplate;
public:
SfxFilter( const String &rName,
const String &rWildCard,
SfxFilterFlags nFormatType,
sal_uInt32 lFormat,
const String &rTypeName,
USHORT nDocIcon,
const String &rMimeType,
const String &rUserData,
const String& rServiceName );
~SfxFilter();
bool IsAllowedAsTemplate() const { return nFormatType & SFX_FILTER_TEMPLATE; }
bool IsOwnFormat() const { return nFormatType & SFX_FILTER_OWN; }
bool IsOwnTemplateFormat() const { return nFormatType & SFX_FILTER_TEMPLATEPATH; }
bool IsAlienFormat() const { return nFormatType & SFX_FILTER_ALIEN; }
bool CanImport() const { return nFormatType & SFX_FILTER_IMPORT; }
bool CanExport() const { return nFormatType & SFX_FILTER_EXPORT; }
bool IsInternal() const { return nFormatType & SFX_FILTER_INTERNAL; }
SfxFilterFlags GetFilterFlags() const { return nFormatType; }
const String& GetFilterName() const { return aFilterName; }
const String& GetMimeType() const { return aMimeType; }
const String& GetName() const { return aFilterName; }
const WildCard& GetWildcard() const { return aWildCard; }
const String& GetRealTypeName() const { return aTypeName; }
ULONG GetFormat() const { return lFormat; }
const String& GetTypeName() const { return aTypeName; }
const String& GetUIName() const { return aUIName; }
USHORT GetDocIconId() const { return nDocIcon; }
const String& GetUserData() const { return aUserData; }
const String& GetDefaultTemplate() const { return aDefaultTemplate; }
void SetDefaultTemplate( const String& rStr ) { aDefaultTemplate = rStr; }
BOOL UsesStorage() const { return GetFormat() != 0; }
void SetURLPattern( const String& rStr ) { aPattern = rStr; aPattern.ToLowerAscii(); }
String GetURLPattern() const { return aPattern; }
void SetUIName( const String& rName ) { aUIName = rName; }
void SetVersion( ULONG nVersionP ) { nVersion = nVersionP; }
ULONG GetVersion() const { return nVersion; }
String GetSuffixes() const;
String GetDefaultExtension() const;
const String& GetServiceName() const { return aServiceName; }
static const SfxFilter* GetDefaultFilter( const String& rName );
static const SfxFilter* GetFilterByName( const String& rName );
static const SfxFilter* GetDefaultFilterFromFactory( const String& rServiceName );
static String GetTypeFromStorage( const SotStorage& rStg );
static String GetTypeFromStorage( const com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage,
BOOL bTemplate = FALSE,
String* pName=0 )
throw ( ::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException );
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_const_arrays_to_uniforms.cpp
*
* Lower constant arrays to uniform arrays.
*
* Some driver backends (such as i965 and nouveau) don't handle constant arrays
* gracefully, instead treating them as ordinary writable temporary arrays.
* Since arrays can be large, this often means spilling them to scratch memory,
* which usually involves a large number of instructions.
*
* This must be called prior to link_set_uniform_initializers(); we need the
* linker to process our new uniform's constant initializer.
*
* This should be called after optimizations, since those can result in
* splitting and removing arrays that are indexed by constant expressions.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_rvalue_visitor.h"
#include "compiler/glsl_types.h"
namespace {
class lower_const_array_visitor : public ir_rvalue_visitor {
public:
lower_const_array_visitor(exec_list *insts)
{
instructions = insts;
progress = false;
}
bool run()
{
visit_list_elements(this, instructions);
return progress;
}
void handle_rvalue(ir_rvalue **rvalue);
private:
exec_list *instructions;
bool progress;
};
void
lower_const_array_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_dereference_array *dra = (*rvalue)->as_dereference_array();
if (!dra)
return;
ir_constant *con = dra->array->as_constant();
if (!con || !con->type->is_array())
return;
void *mem_ctx = ralloc_parent(con);
char *uniform_name = ralloc_asprintf(mem_ctx, "constarray__%p", dra);
ir_variable *uni =
new(mem_ctx) ir_variable(con->type, uniform_name, ir_var_uniform);
uni->constant_initializer = con;
uni->constant_value = con;
uni->data.has_initializer = true;
uni->data.how_declared = ir_var_hidden;
uni->data.read_only = true;
/* Assume the whole thing is accessed. */
uni->data.max_array_access = uni->type->length - 1;
instructions->push_head(uni);
ir_dereference_variable *varref = new(mem_ctx) ir_dereference_variable(uni);
*rvalue = new(mem_ctx) ir_dereference_array(varref, dra->array_index);
progress = true;
}
} /* anonymous namespace */
bool
lower_const_arrays_to_uniforms(exec_list *instructions)
{
lower_const_array_visitor v(instructions);
return v.run();
}
<commit_msg>glsl: Make lower_const_arrays_to_uniforms work directly on constants.<commit_after>/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_const_arrays_to_uniforms.cpp
*
* Lower constant arrays to uniform arrays.
*
* Some driver backends (such as i965 and nouveau) don't handle constant arrays
* gracefully, instead treating them as ordinary writable temporary arrays.
* Since arrays can be large, this often means spilling them to scratch memory,
* which usually involves a large number of instructions.
*
* This must be called prior to link_set_uniform_initializers(); we need the
* linker to process our new uniform's constant initializer.
*
* This should be called after optimizations, since those can result in
* splitting and removing arrays that are indexed by constant expressions.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_rvalue_visitor.h"
#include "compiler/glsl_types.h"
namespace {
class lower_const_array_visitor : public ir_rvalue_visitor {
public:
lower_const_array_visitor(exec_list *insts)
{
instructions = insts;
progress = false;
}
bool run()
{
visit_list_elements(this, instructions);
return progress;
}
void handle_rvalue(ir_rvalue **rvalue);
private:
exec_list *instructions;
bool progress;
};
void
lower_const_array_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_constant *con = (*rvalue)->as_constant();
if (!con || !con->type->is_array())
return;
void *mem_ctx = ralloc_parent(con);
char *uniform_name = ralloc_asprintf(mem_ctx, "constarray__%p", con);
ir_variable *uni =
new(mem_ctx) ir_variable(con->type, uniform_name, ir_var_uniform);
uni->constant_initializer = con;
uni->constant_value = con;
uni->data.has_initializer = true;
uni->data.how_declared = ir_var_hidden;
uni->data.read_only = true;
/* Assume the whole thing is accessed. */
uni->data.max_array_access = uni->type->length - 1;
instructions->push_head(uni);
*rvalue = new(mem_ctx) ir_dereference_variable(uni);
progress = true;
}
} /* anonymous namespace */
bool
lower_const_arrays_to_uniforms(exec_list *instructions)
{
lower_const_array_visitor v(instructions);
return v.run();
}
<|endoftext|>
|
<commit_before>#include "formulation/equation/diffusion.h"
#include <gtest/gtest.h>
#include "test_helpers/gmock_wrapper.h"
class EquationDiffusionTest : public ::testing::Test {};
TEST_F(EquationDiffusionTest, Dummy) {
EXPECT_TRUE(true);
}<commit_msg>added constructor tests to EquationDiffusionTest<commit_after>#include "formulation/types.h"
#include "formulation/equation/diffusion.h"
#include <gtest/gtest.h>
#include "test_helpers/gmock_wrapper.h"
class EquationDiffusionTest : public ::testing::Test {
protected:
using DiscretizationType = bart::formulation::DiscretizationType;
using ScalarEquations = bart::formulation::ScalarEquations;
using EquationType = bart::formulation::EquationType;
bart::formulation::equation::Diffusion<2> diffusion_cfem{
DiscretizationType::kContinuousFEM};
bart::formulation::equation::Diffusion<2> diffusion_dfem{
DiscretizationType::kDiscontinuousFEM};
};
TEST_F(EquationDiffusionTest, ConstructorTest) {
EXPECT_EQ(diffusion_cfem.discretization_type(),
DiscretizationType::kContinuousFEM);
EXPECT_EQ(diffusion_cfem.equation_type(), EquationType::kScalar);
EXPECT_EQ(diffusion_dfem.discretization_type(),
DiscretizationType::kDiscontinuousFEM);
EXPECT_EQ(diffusion_dfem.equation_type(), EquationType::kScalar);
}<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.