text
stringlengths 54
60.6k
|
---|
<commit_before>#pragma once
#include <bitset>
#include <iomanip>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <iwlib.h>
#include <limits.h>
#include <linux/ethtool.h>
#include <linux/if_link.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <memory>
#include <sstream>
#include <string>
#include <string>
#ifdef inline
#undef inline
#endif
#include "common.hpp"
#include "config.hpp"
#include "utils/command.hpp"
#include "utils/file.hpp"
#include "utils/string.hpp"
LEMONBUDDY_NS
namespace net {
DEFINE_ERROR(network_error);
// types {{{
struct quality_range {
int val = 0;
int max = 0;
int percentage() const {
if (max < 0)
return 2 * (val + 100);
return static_cast<float>(val) / max * 100.0f + 0.5f;
}
};
using bytes_t = unsigned int;
struct link_activity {
bytes_t transmitted = 0;
bytes_t received = 0;
chrono::system_clock::time_point time;
};
struct link_status {
string ip;
link_activity previous;
link_activity current;
};
// }}}
// class: network {{{
class network {
public:
/**
* Construct network interface
*/
explicit network(string interface) : m_interface(interface) {
if (if_nametoindex(m_interface.c_str()) == 0)
throw network_error("Invalid network interface \"" + m_interface + "\"");
if ((m_socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
throw network_error("Failed to open socket");
}
/**
* Destruct network interface
*/
virtual ~network() {
if (m_socketfd != -1)
close(m_socketfd);
}
/**
* Query device driver for information
*/
virtual bool query() {
struct ifaddrs* ifaddr;
if (getifaddrs(&ifaddr) == -1)
return false;
for (auto ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (m_interface.compare(0, m_interface.length(), ifa->ifa_name) != 0)
continue;
switch (ifa->ifa_addr->sa_family) {
case AF_INET:
char ip_buffer[NI_MAXHOST];
getnameinfo(ifa->ifa_addr, sizeof(sockaddr_in), ip_buffer, NI_MAXHOST, nullptr, 0,
NI_NUMERICHOST);
m_status.ip = string{ip_buffer};
break;
case AF_PACKET:
if (ifa->ifa_data == nullptr)
continue;
struct rtnl_link_stats* link_state =
reinterpret_cast<decltype(link_state)>(ifa->ifa_data);
m_status.previous = m_status.current;
m_status.current.transmitted = link_state->tx_bytes;
m_status.current.received = link_state->rx_bytes;
m_status.current.time = chrono::system_clock::now();
break;
}
}
freeifaddrs(ifaddr);
return true;
}
/**
* Check current connection state
*/
virtual bool connected() const = 0;
/**
* Run ping command to test internet connectivity
*/
virtual bool ping() const {
try {
auto exec = "ping -c 2 -W 2 -I " + m_interface + " " + string(CONNECTION_TEST_IP);
auto ping = command_util::make_command(exec);
return ping && ping->exec(true) == EXIT_SUCCESS;
} catch (const std::exception& err) {
return false;
}
}
/**
* Get interface ip address
*/
string ip() const {
return m_status.ip;
}
/**
* Get download speed rate
*/
string downspeed(int minwidth = 3) const {
float bytes_diff = m_status.current.received - m_status.previous.received;
return format_speedrate(bytes_diff, minwidth);
}
/**
* Get upload speed rate
*/
string upspeed(int minwidth = 3) const {
float bytes_diff = m_status.current.transmitted - m_status.previous.transmitted;
return format_speedrate(bytes_diff, minwidth);
}
protected:
/**
* Test if the network interface is in a valid state
*/
bool test_interface(struct ifreq& request) const {
if ((ioctl(m_socketfd, SIOCGIFFLAGS, &request)) == -1)
return false;
if ((request.ifr_flags & IFF_UP) == 0)
return false;
if ((request.ifr_flags & IFF_RUNNING) == 0)
return false;
auto operstate = file_util::get_contents("/sys/class/net/" + m_interface + "/operstate");
return operstate.compare(0, 2, "up") == 0;
}
/**
* Format up- and download speed
*/
string format_speedrate(float bytes_diff, int minwidth) const {
const auto duration = m_status.current.time - m_status.previous.time;
float time_diff = chrono::duration_cast<chrono::seconds>(duration).count();
float speedrate = bytes_diff / (time_diff ? time_diff : 1);
vector<string> suffixes{"GB", "MB"};
string suffix{"KB"};
while ((speedrate /= 1000) > 999) {
suffix = suffixes.back();
suffixes.pop_back();
}
return string_util::from_stream(stringstream() << std::setw(minwidth) << std::setfill(' ')
<< std::setprecision(0) << std::fixed
<< speedrate << " " << suffix << "/s");
}
int m_socketfd = 0;
link_status m_status;
string m_interface;
};
// }}}
// class: wired_network {{{
class wired_network : public network {
public:
explicit wired_network(string interface) : network(interface) {}
/**
* Query device driver for information
*/
bool query() override {
if (!network::query())
return false;
struct ethtool_cmd ethernet_data;
ethernet_data.cmd = ETHTOOL_GSET;
struct ifreq request;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
request.ifr_data = reinterpret_cast<caddr_t>(ðernet_data);
if (ioctl(m_socketfd, SIOCETHTOOL, &request) == -1)
return false;
m_linkspeed = ethernet_data.speed;
return true;
}
/**
* Check current connection state
*/
bool connected() const override {
struct ifreq request;
struct ethtool_value ethernet_data;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
ethernet_data.cmd = ETHTOOL_GLINK;
request.ifr_data = reinterpret_cast<caddr_t>(ðernet_data);
if (!network::test_interface(request))
return false;
if (ioctl(m_socketfd, SIOCETHTOOL, &request) != -1)
return ethernet_data.data != 0;
return false;
}
/**
*
* about the current connection
*/
string linkspeed() const {
return (m_linkspeed == 0 ? "???" : to_string(m_linkspeed)) + " Mbit/s";
}
private:
int m_linkspeed = 0;
};
// }}}
// class: wireless_network {{{
class wireless_network : public network {
public:
wireless_network(string interface) : network(interface) {}
/**
* Query the wireless device for information
* about the current connection
*/
bool query() override {
if (!network::query())
return false;
auto socket_fd = iw_sockets_open();
if (socket_fd == -1)
return false;
struct iwreq req;
if (iw_get_ext(socket_fd, m_interface.c_str(), SIOCGIWMODE, &req) == -1)
return false;
// Ignore interfaces in ad-hoc mode
if (req.u.mode == IW_MODE_ADHOC)
return false;
query_essid(socket_fd);
query_quality(socket_fd);
iw_sockets_close(socket_fd);
return true;
}
/**
* Check current connection state
*/
bool connected() const override {
struct ifreq request;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
if (!network::test_interface(request))
return false;
if (m_essid.empty())
return false;
return true;
}
/**
* ESSID reported by last query
*/
string essid() const {
return m_essid;
}
/**
* Signal strength percentage reported by last query
*/
int signal() const {
return m_signalstrength.percentage();
}
/**
* Link quality percentage reported by last query
*/
int quality() const {
return m_linkquality.percentage();
}
protected:
/**
* Query for ESSID
*/
void query_essid(const int& socket_fd) {
char essid[IW_ESSID_MAX_SIZE + 1];
struct iwreq req;
req.u.essid.pointer = &essid;
req.u.essid.length = sizeof(essid);
req.u.essid.flags = 0;
if (iw_get_ext(socket_fd, m_interface.c_str(), SIOCGIWESSID, &req) != -1) {
m_essid = string{essid};
} else {
m_essid.clear();
}
}
/**
* Query for device driver quality values
*/
void query_quality(const int& socket_fd) {
iwrange range;
iwstats stats;
// Fill range
if (iw_get_range_info(socket_fd, m_interface.c_str(), &range) == -1)
return;
// Fill stats
if (iw_get_stats(socket_fd, m_interface.c_str(), &stats, &range, 1) == -1)
return;
// Check if the driver supplies the quality value
if (stats.qual.updated & IW_QUAL_QUAL_INVALID)
return;
// Check if the driver supplies the quality level value
if (stats.qual.updated & IW_QUAL_LEVEL_INVALID)
return;
// Check if the link quality has been uodated
if (stats.qual.updated & IW_QUAL_QUAL_UPDATED) {
m_linkquality.val = stats.qual.qual;
m_linkquality.max = range.max_qual.qual;
}
// Check if the signal strength has been uodated
if (stats.qual.updated & IW_QUAL_LEVEL_UPDATED) {
m_signalstrength.val = stats.qual.level;
m_signalstrength.max = range.max_qual.level;
// Check if the values are defined in dBm
if (stats.qual.level > range.max_qual.level) {
m_signalstrength.val -= 0x100;
m_signalstrength.max -= 0x100;
}
}
}
private:
shared_ptr<wireless_info> m_info;
string m_essid;
quality_range m_signalstrength;
quality_range m_linkquality;
};
// }}}
/**
* Test if interface with given name is a wireless device
*/
inline bool is_wireless_interface(string ifname) {
return file_util::exists("/sys/class/net/" + ifname + "/wireless");
}
using wireless_t = unique_ptr<wireless_network>;
using wired_t = unique_ptr<wired_network>;
}
LEMONBUDDY_NS_END
<commit_msg>fix(network): Connection state<commit_after>#pragma once
#include <bitset>
#include <iomanip>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <iwlib.h>
#include <limits.h>
#include <linux/ethtool.h>
#include <linux/if_link.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <memory>
#include <sstream>
#include <string>
#include <string>
#ifdef inline
#undef inline
#endif
#include "common.hpp"
#include "config.hpp"
#include "utils/command.hpp"
#include "utils/file.hpp"
#include "utils/string.hpp"
LEMONBUDDY_NS
namespace net {
DEFINE_ERROR(network_error);
// types {{{
struct quality_range {
int val = 0;
int max = 0;
int percentage() const {
if (max < 0)
return 2 * (val + 100);
return static_cast<float>(val) / max * 100.0f + 0.5f;
}
};
using bytes_t = unsigned int;
struct link_activity {
bytes_t transmitted = 0;
bytes_t received = 0;
chrono::system_clock::time_point time;
};
struct link_status {
string ip;
link_activity previous;
link_activity current;
};
// }}}
// class: network {{{
class network {
public:
/**
* Construct network interface
*/
explicit network(string interface) : m_interface(interface) {
if (if_nametoindex(m_interface.c_str()) == 0)
throw network_error("Invalid network interface \"" + m_interface + "\"");
if ((m_socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
throw network_error("Failed to open socket");
}
/**
* Destruct network interface
*/
virtual ~network() {
if (m_socketfd != -1)
close(m_socketfd);
}
/**
* Query device driver for information
*/
virtual bool query() {
struct ifaddrs* ifaddr;
if (getifaddrs(&ifaddr) == -1)
return false;
for (auto ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (m_interface.compare(0, m_interface.length(), ifa->ifa_name) != 0)
continue;
switch (ifa->ifa_addr->sa_family) {
case AF_INET:
char ip_buffer[NI_MAXHOST];
getnameinfo(ifa->ifa_addr, sizeof(sockaddr_in), ip_buffer, NI_MAXHOST, nullptr, 0,
NI_NUMERICHOST);
m_status.ip = string{ip_buffer};
break;
case AF_PACKET:
if (ifa->ifa_data == nullptr)
continue;
struct rtnl_link_stats* link_state =
reinterpret_cast<decltype(link_state)>(ifa->ifa_data);
m_status.previous = m_status.current;
m_status.current.transmitted = link_state->tx_bytes;
m_status.current.received = link_state->rx_bytes;
m_status.current.time = chrono::system_clock::now();
break;
}
}
freeifaddrs(ifaddr);
return true;
}
/**
* Check current connection state
*/
virtual bool connected() const = 0;
/**
* Run ping command to test internet connectivity
*/
virtual bool ping() const {
try {
auto exec = "ping -c 2 -W 2 -I " + m_interface + " " + string(CONNECTION_TEST_IP);
auto ping = command_util::make_command(exec);
return ping && ping->exec(true) == EXIT_SUCCESS;
} catch (const std::exception& err) {
return false;
}
}
/**
* Get interface ip address
*/
string ip() const {
return m_status.ip;
}
/**
* Get download speed rate
*/
string downspeed(int minwidth = 3) const {
float bytes_diff = m_status.current.received - m_status.previous.received;
return format_speedrate(bytes_diff, minwidth);
}
/**
* Get upload speed rate
*/
string upspeed(int minwidth = 3) const {
float bytes_diff = m_status.current.transmitted - m_status.previous.transmitted;
return format_speedrate(bytes_diff, minwidth);
}
protected:
/**
* Test if the network interface is in a valid state
*/
bool test_interface() const {
auto operstate = file_util::get_contents("/sys/class/net/" + m_interface + "/operstate");
return operstate.compare(0, 2, "up") == 0;
}
/**
* Format up- and download speed
*/
string format_speedrate(float bytes_diff, int minwidth) const {
const auto duration = m_status.current.time - m_status.previous.time;
float time_diff = chrono::duration_cast<chrono::seconds>(duration).count();
float speedrate = bytes_diff / (time_diff ? time_diff : 1);
vector<string> suffixes{"GB", "MB"};
string suffix{"KB"};
while ((speedrate /= 1000) > 999) {
suffix = suffixes.back();
suffixes.pop_back();
}
return string_util::from_stream(stringstream() << std::setw(minwidth) << std::setfill(' ')
<< std::setprecision(0) << std::fixed
<< speedrate << " " << suffix << "/s");
}
int m_socketfd = 0;
link_status m_status;
string m_interface;
};
// }}}
// class: wired_network {{{
class wired_network : public network {
public:
explicit wired_network(string interface) : network(interface) {}
/**
* Query device driver for information
*/
bool query() override {
if (!network::query())
return false;
struct ethtool_cmd ethernet_data;
ethernet_data.cmd = ETHTOOL_GSET;
struct ifreq request;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
request.ifr_data = reinterpret_cast<caddr_t>(ðernet_data);
if (ioctl(m_socketfd, SIOCETHTOOL, &request) == -1)
return false;
m_linkspeed = ethernet_data.speed;
return true;
}
/**
* Check current connection state
*/
bool connected() const override {
if (!network::test_interface())
return false;
struct ifreq request;
struct ethtool_value ethernet_data;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
ethernet_data.cmd = ETHTOOL_GLINK;
request.ifr_data = reinterpret_cast<caddr_t>(ðernet_data);
if (ioctl(m_socketfd, SIOCETHTOOL, &request) != -1)
return ethernet_data.data != 0;
return false;
}
/**
*
* about the current connection
*/
string linkspeed() const {
return (m_linkspeed == 0 ? "???" : to_string(m_linkspeed)) + " Mbit/s";
}
private:
int m_linkspeed = 0;
};
// }}}
// class: wireless_network {{{
class wireless_network : public network {
public:
wireless_network(string interface) : network(interface) {}
/**
* Query the wireless device for information
* about the current connection
*/
bool query() override {
if (!network::query())
return false;
auto socket_fd = iw_sockets_open();
if (socket_fd == -1)
return false;
struct iwreq req;
if (iw_get_ext(socket_fd, m_interface.c_str(), SIOCGIWMODE, &req) == -1)
return false;
// Ignore interfaces in ad-hoc mode
if (req.u.mode == IW_MODE_ADHOC)
return false;
query_essid(socket_fd);
query_quality(socket_fd);
iw_sockets_close(socket_fd);
return true;
}
/**
* Check current connection state
*/
bool connected() const override {
if (!network::test_interface())
return false;
struct ifreq request;
strncpy(request.ifr_name, m_interface.c_str(), IFNAMSIZ - 1);
if ((ioctl(m_socketfd, SIOCGIFFLAGS, &request)) == -1)
return false;
if (m_essid.empty())
return false;
return true;
}
/**
* ESSID reported by last query
*/
string essid() const {
return m_essid;
}
/**
* Signal strength percentage reported by last query
*/
int signal() const {
return m_signalstrength.percentage();
}
/**
* Link quality percentage reported by last query
*/
int quality() const {
return m_linkquality.percentage();
}
protected:
/**
* Query for ESSID
*/
void query_essid(const int& socket_fd) {
char essid[IW_ESSID_MAX_SIZE + 1];
struct iwreq req;
req.u.essid.pointer = &essid;
req.u.essid.length = sizeof(essid);
req.u.essid.flags = 0;
if (iw_get_ext(socket_fd, m_interface.c_str(), SIOCGIWESSID, &req) != -1) {
m_essid = string{essid};
} else {
m_essid.clear();
}
}
/**
* Query for device driver quality values
*/
void query_quality(const int& socket_fd) {
iwrange range;
iwstats stats;
// Fill range
if (iw_get_range_info(socket_fd, m_interface.c_str(), &range) == -1)
return;
// Fill stats
if (iw_get_stats(socket_fd, m_interface.c_str(), &stats, &range, 1) == -1)
return;
// Check if the driver supplies the quality value
if (stats.qual.updated & IW_QUAL_QUAL_INVALID)
return;
// Check if the driver supplies the quality level value
if (stats.qual.updated & IW_QUAL_LEVEL_INVALID)
return;
// Check if the link quality has been uodated
if (stats.qual.updated & IW_QUAL_QUAL_UPDATED) {
m_linkquality.val = stats.qual.qual;
m_linkquality.max = range.max_qual.qual;
}
// Check if the signal strength has been uodated
if (stats.qual.updated & IW_QUAL_LEVEL_UPDATED) {
m_signalstrength.val = stats.qual.level;
m_signalstrength.max = range.max_qual.level;
// Check if the values are defined in dBm
if (stats.qual.level > range.max_qual.level) {
m_signalstrength.val -= 0x100;
m_signalstrength.max -= 0x100;
}
}
}
private:
shared_ptr<wireless_info> m_info;
string m_essid;
quality_range m_signalstrength;
quality_range m_linkquality;
};
// }}}
/**
* Test if interface with given name is a wireless device
*/
inline bool is_wireless_interface(string ifname) {
return file_util::exists("/sys/class/net/" + ifname + "/wireless");
}
using wireless_t = unique_ptr<wireless_network>;
using wired_t = unique_ptr<wired_network>;
}
LEMONBUDDY_NS_END
<|endoftext|> |
<commit_before>#include "game/states/skirmishstate.hpp"
#include <SFML/Graphics/Sprite.hpp>
#include "game/gui/victorydialog.hpp"
#include "game/states/deploystate.hpp"
#include "game/path.hpp"
#include "engine/pathfinding/astar.hpp"
#include "engine/pathfinding/path.hpp"
#include "engine/player.hpp"
#include "gui/texturemanager.hpp"
#include "gui/ng/label.hpp"
#include "gui/ng/spritewidget.hpp"
#include "gui/ng/button.hpp"
#include "gui/squaredetailwindow.hpp"
#include "gui/cursor.hpp"
#include "gui/squaremarker.hpp"
#include "eventsystem/inputevents.hpp"
namespace qrw
{
SkirmishState::SkirmishState(sf::RenderWindow* renderWindow)
: SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE),
_selectedUnit(nullptr),
m_victoryGui(new namelessgui::Gui(renderWindow))
{
_squareDetailWindow = new SquareDetailWindow();
_guiUptr->addWidget(_squareDetailWindow);
path_ = new Path();
g_scene.addGameObject(path_);
_squareMarker = new SquareMarker();
_squareMarker->setVisible(false);
g_scene.addGameObject(_squareMarker);
_playerNameText = new namelessgui::Text();
_playerNameText->setText("Player Name");
_playerNameText->setParentAnchor({0.5, 0});
_playerNameText->setAnchor({0.5, 0});
_toolBar->addWidget(_playerNameText);
namelessgui::Button* endTurnButton = new namelessgui::Button();
endTurnButton->setText("End Turn");
endTurnButton->setSize({140, 30});
endTurnButton->setParentAnchor({0.5, 1});
endTurnButton->setAnchor({0.5, 1.0});
endTurnButton->setRelativePosition({0.0f, -5.0f});
endTurnButton->signalClicked.connect(std::bind(&SkirmishState::endTurn, this));
_toolBar->addWidget(endTurnButton);
m_victoryDialog = new VictoryDialog();
m_victoryDialog->signalCloseClicked.connect(std::bind(&SceneState::slotBackToMainMenu, this));
m_victoryGui->addWidget(m_victoryDialog);
m_victoryGui->setVisible(false);
}
void SkirmishState::init(GameState *previousState)
{
SceneState::init(previousState);
if(previousState->getId() != EGameStateId::EGSID_DEPLOY_STATE)
return;
DeployState* deployState = static_cast<DeployState*>(previousState);
_board = deployState->getBoard();
g_scene.setBoard(_board);
_players = deployState->getPlayers();
_currentPlayer = 0;
_playerNameText->setText(_players[_currentPlayer]->getName());
// Initialize square detail window.
const Coordinates& cursorPosition = g_scene.getSingleGameObject<Cursor>()->getBoardPosition();
Unit* unit = _board->getUnit(cursorPosition);
Terrain* terrain = _board->getTerrain(cursorPosition);
_squareDetailWindow->setUnitAndTerrain(unit, terrain);
}
void SkirmishState::draw()
{
SceneState::draw();
m_victoryGui->render(*_renderWindow);
}
bool SkirmishState::handleEvent(const IEvent &event)
{
SceneState::handleEvent(event);
if(event.getName() == RightMouseButtonPressedEvent::name)
deselectUnit();
return false;
}
EGameStateId SkirmishState::update()
{
if(_backToMainMenu)
return EGameStateId::EGSID_MAIN_MENU_STATE;
return EGameStateId::EGSID_NO_CHANGE;
}
void SkirmishState::slotCursorMoved(const Coordinates &boardPosition)
{
if(_board->isOnBoard(boardPosition))
{
Unit* unitUnderCursor = _board->getUnit(boardPosition);
Terrain* terrainUnderCursor = _board->getTerrain(boardPosition);
_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);
if(_selectedUnit)
{
path_->setStartAndEnd(_selectedUnit->getPosition(), boardPosition);
Cursor::Color cursorColor = Cursor::Color::ESC_DEFAULT;
if(path_->getMovementCosts() > _selectedUnit->getCurrentMovement())
cursorColor = Cursor::Color::ESC_WARNING;
if(boardPosition == _squareMarker->getBoardPosition())
cursorColor = Cursor::Color::ESC_DEFAULT;
g_scene.getSingleGameObject<Cursor>()->setFillColor(cursorColor);
}
}
else
_squareDetailWindow->setUnitAndTerrain(nullptr, nullptr);
}
void SkirmishState::moveUnit()
{
if(!_selectedUnit) return;
int pathCosts = path_->getMovementCosts();
int maxDistance = _selectedUnit->getCurrentMovement();
if(pathCosts > maxDistance) return;
int remainingMovement = maxDistance - pathCosts;
_selectedUnit->setCurrentMovement(remainingMovement);
_selectedUnit->setPosition(path_->getTarget());
}
void SkirmishState::performAttack(Unit* attackedUnit)
{
const Coordinates& positionOfAttackedUnit = attackedUnit->getPosition();
if(!_selectedUnit->isTargetWithinAttackRange(positionOfAttackedUnit))
return;
if(_selectedUnit->getCurrentMovement() == 0)
return;
_selectedUnit->setCurrentMovement(0);
int inflictedDamage = _selectedUnit->getModifiedAttack() - attackedUnit->getModifiedDefense();
inflictedDamage = inflictedDamage < 0 ? 0 : inflictedDamage;
attackedUnit->damage(inflictedDamage);
if(attackedUnit->getHP() == 0)
{
g_scene.despawn(attackedUnit);
_selectedUnit->setPosition(positionOfAttackedUnit);
}
else
{
inflictedDamage = attackedUnit->getModifiedAttack() - _selectedUnit->getModifiedDefense();
inflictedDamage = inflictedDamage < 0 ? 0 : inflictedDamage;
_selectedUnit->damage(inflictedDamage);
if(_selectedUnit->getHP() == 0)
{
g_scene.despawn(_selectedUnit);
_selectedUnit = nullptr;
}
}
updateSquareDetailWindow(positionOfAttackedUnit);
}
void SkirmishState::checkVictory()
{
bool playersHaveUnits[] = {false, false};
for(auto unitIter : _board->getUnits())
{
playersHaveUnits[unitIter.second->getPlayer()->getId() - 1] = true;
}
bool gameEnded = !playersHaveUnits[0] || !playersHaveUnits[1];
if(gameEnded)
{
m_victoryDialog->setLoserName(!playersHaveUnits[0] ? _players[0]->getName() : _players[1]->getName());
m_victoryDialog->setWinnerName(!playersHaveUnits[0] ? _players[1]->getName() : _players[0]->getName());
m_victoryGui->setVisible(true);
_guiUptr->setVisible(false);
}
}
void SkirmishState::replenishTroops()
{
Unit* unit;
for(auto unitIter : _board->getUnits())
{
unit = unitIter.second;
unit->setCurrentMovement(unit->getMovement());
}
}
void SkirmishState::updateSquareDetailWindow(const Coordinates& position)
{
_squareDetailWindow->setUnitAndTerrain(
_board->getUnit(position),
_board->getTerrain(position));
}
void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition)
{
Unit* unitUnderCursor = _board->getUnit(boardPosition);
Terrain* terrainUnderCursor = _board->getTerrain(boardPosition);
_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);
// Case 1: Unit is selected and instructed to move.
if(_selectedUnit && !unitUnderCursor)
{
moveUnit();
deselectUnit();
return;
}
// Case 2: Unit is selected and instructed to attack enemy.
if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer())
{
performAttack(unitUnderCursor);
deselectUnit();
checkVictory();
return;
}
// Select unit if it belongs to current player
if(unitUnderCursor && unitUnderCursor->getPlayer() == _players[_currentPlayer])
{
// Select unit
_selectedUnit = unitUnderCursor;
_squareMarker->setBoardPosition(boardPosition);
_squareMarker->setVisible(true);
return;
}
deselectUnit();
}
void SkirmishState::endTurn()
{
_currentPlayer = (_currentPlayer + 1) % _players.size();
_playerNameText->setText(_players[_currentPlayer]->getName());
deselectUnit();
replenishTroops();
}
void SkirmishState::deselectUnit()
{
_selectedUnit = nullptr;
_squareMarker->setVisible(false);
g_scene.getSingleGameObject<Cursor>()->setFillColor(Cursor::Color::ESC_DEFAULT);
path_->reset();
}
} // namespace qrw
<commit_msg>Assertion to ensure game state order<commit_after>#include "game/states/skirmishstate.hpp"
#include <SFML/Graphics/Sprite.hpp>
#include "game/gui/victorydialog.hpp"
#include "game/states/deploystate.hpp"
#include "game/path.hpp"
#include "engine/pathfinding/astar.hpp"
#include "engine/pathfinding/path.hpp"
#include "engine/player.hpp"
#include "gui/texturemanager.hpp"
#include "gui/ng/label.hpp"
#include "gui/ng/spritewidget.hpp"
#include "gui/ng/button.hpp"
#include "gui/squaredetailwindow.hpp"
#include "gui/cursor.hpp"
#include "gui/squaremarker.hpp"
#include "eventsystem/inputevents.hpp"
namespace qrw
{
SkirmishState::SkirmishState(sf::RenderWindow* renderWindow)
: SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE),
_selectedUnit(nullptr),
m_victoryGui(new namelessgui::Gui(renderWindow))
{
_squareDetailWindow = new SquareDetailWindow();
_guiUptr->addWidget(_squareDetailWindow);
path_ = new Path();
g_scene.addGameObject(path_);
_squareMarker = new SquareMarker();
_squareMarker->setVisible(false);
g_scene.addGameObject(_squareMarker);
_playerNameText = new namelessgui::Text();
_playerNameText->setText("Player Name");
_playerNameText->setParentAnchor({0.5, 0});
_playerNameText->setAnchor({0.5, 0});
_toolBar->addWidget(_playerNameText);
namelessgui::Button* endTurnButton = new namelessgui::Button();
endTurnButton->setText("End Turn");
endTurnButton->setSize({140, 30});
endTurnButton->setParentAnchor({0.5, 1});
endTurnButton->setAnchor({0.5, 1.0});
endTurnButton->setRelativePosition({0.0f, -5.0f});
endTurnButton->signalClicked.connect(std::bind(&SkirmishState::endTurn, this));
_toolBar->addWidget(endTurnButton);
m_victoryDialog = new VictoryDialog();
m_victoryDialog->signalCloseClicked.connect(std::bind(&SceneState::slotBackToMainMenu, this));
m_victoryGui->addWidget(m_victoryDialog);
m_victoryGui->setVisible(false);
}
void SkirmishState::init(GameState *previousState)
{
SceneState::init(previousState);
assert(previousState->getId() == EGameStateId::EGSID_DEPLOY_STATE);
DeployState* deployState = static_cast<DeployState*>(previousState);
_board = deployState->getBoard();
g_scene.setBoard(_board);
_players = deployState->getPlayers();
_currentPlayer = 0;
_playerNameText->setText(_players[_currentPlayer]->getName());
// Initialize square detail window.
const Coordinates& cursorPosition = g_scene.getSingleGameObject<Cursor>()->getBoardPosition();
Unit* unit = _board->getUnit(cursorPosition);
Terrain* terrain = _board->getTerrain(cursorPosition);
_squareDetailWindow->setUnitAndTerrain(unit, terrain);
}
void SkirmishState::draw()
{
SceneState::draw();
m_victoryGui->render(*_renderWindow);
}
bool SkirmishState::handleEvent(const IEvent &event)
{
SceneState::handleEvent(event);
if(event.getName() == RightMouseButtonPressedEvent::name)
deselectUnit();
return false;
}
EGameStateId SkirmishState::update()
{
if(_backToMainMenu)
return EGameStateId::EGSID_MAIN_MENU_STATE;
return EGameStateId::EGSID_NO_CHANGE;
}
void SkirmishState::slotCursorMoved(const Coordinates &boardPosition)
{
if(_board->isOnBoard(boardPosition))
{
Unit* unitUnderCursor = _board->getUnit(boardPosition);
Terrain* terrainUnderCursor = _board->getTerrain(boardPosition);
_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);
if(_selectedUnit)
{
path_->setStartAndEnd(_selectedUnit->getPosition(), boardPosition);
Cursor::Color cursorColor = Cursor::Color::ESC_DEFAULT;
if(path_->getMovementCosts() > _selectedUnit->getCurrentMovement())
cursorColor = Cursor::Color::ESC_WARNING;
if(boardPosition == _squareMarker->getBoardPosition())
cursorColor = Cursor::Color::ESC_DEFAULT;
g_scene.getSingleGameObject<Cursor>()->setFillColor(cursorColor);
}
}
else
_squareDetailWindow->setUnitAndTerrain(nullptr, nullptr);
}
void SkirmishState::moveUnit()
{
if(!_selectedUnit) return;
int pathCosts = path_->getMovementCosts();
int maxDistance = _selectedUnit->getCurrentMovement();
if(pathCosts > maxDistance) return;
int remainingMovement = maxDistance - pathCosts;
_selectedUnit->setCurrentMovement(remainingMovement);
_selectedUnit->setPosition(path_->getTarget());
}
void SkirmishState::performAttack(Unit* attackedUnit)
{
const Coordinates& positionOfAttackedUnit = attackedUnit->getPosition();
if(!_selectedUnit->isTargetWithinAttackRange(positionOfAttackedUnit))
return;
if(_selectedUnit->getCurrentMovement() == 0)
return;
_selectedUnit->setCurrentMovement(0);
int inflictedDamage = _selectedUnit->getModifiedAttack() - attackedUnit->getModifiedDefense();
inflictedDamage = inflictedDamage < 0 ? 0 : inflictedDamage;
attackedUnit->damage(inflictedDamage);
if(attackedUnit->getHP() == 0)
{
g_scene.despawn(attackedUnit);
_selectedUnit->setPosition(positionOfAttackedUnit);
}
else
{
inflictedDamage = attackedUnit->getModifiedAttack() - _selectedUnit->getModifiedDefense();
inflictedDamage = inflictedDamage < 0 ? 0 : inflictedDamage;
_selectedUnit->damage(inflictedDamage);
if(_selectedUnit->getHP() == 0)
{
g_scene.despawn(_selectedUnit);
_selectedUnit = nullptr;
}
}
updateSquareDetailWindow(positionOfAttackedUnit);
}
void SkirmishState::checkVictory()
{
bool playersHaveUnits[] = {false, false};
for(auto unitIter : _board->getUnits())
{
playersHaveUnits[unitIter.second->getPlayer()->getId() - 1] = true;
}
bool gameEnded = !playersHaveUnits[0] || !playersHaveUnits[1];
if(gameEnded)
{
m_victoryDialog->setLoserName(!playersHaveUnits[0] ? _players[0]->getName() : _players[1]->getName());
m_victoryDialog->setWinnerName(!playersHaveUnits[0] ? _players[1]->getName() : _players[0]->getName());
m_victoryGui->setVisible(true);
_guiUptr->setVisible(false);
}
}
void SkirmishState::replenishTroops()
{
Unit* unit;
for(auto unitIter : _board->getUnits())
{
unit = unitIter.second;
unit->setCurrentMovement(unit->getMovement());
}
}
void SkirmishState::updateSquareDetailWindow(const Coordinates& position)
{
_squareDetailWindow->setUnitAndTerrain(
_board->getUnit(position),
_board->getTerrain(position));
}
void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition)
{
Unit* unitUnderCursor = _board->getUnit(boardPosition);
Terrain* terrainUnderCursor = _board->getTerrain(boardPosition);
_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);
// Case 1: Unit is selected and instructed to move.
if(_selectedUnit && !unitUnderCursor)
{
moveUnit();
deselectUnit();
return;
}
// Case 2: Unit is selected and instructed to attack enemy.
if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer())
{
performAttack(unitUnderCursor);
deselectUnit();
checkVictory();
return;
}
// Select unit if it belongs to current player
if(unitUnderCursor && unitUnderCursor->getPlayer() == _players[_currentPlayer])
{
// Select unit
_selectedUnit = unitUnderCursor;
_squareMarker->setBoardPosition(boardPosition);
_squareMarker->setVisible(true);
return;
}
deselectUnit();
}
void SkirmishState::endTurn()
{
_currentPlayer = (_currentPlayer + 1) % _players.size();
_playerNameText->setText(_players[_currentPlayer]->getName());
deselectUnit();
replenishTroops();
}
void SkirmishState::deselectUnit()
{
_selectedUnit = nullptr;
_squareMarker->setVisible(false);
g_scene.getSingleGameObject<Cursor>()->setFillColor(Cursor::Color::ESC_DEFAULT);
path_->reset();
}
} // namespace qrw
<|endoftext|> |
<commit_before>
namespace cusim
{
namespace detail
{
template< typename tCount > __device__ inline
tCount warp_prefix( unsigned aWTID, tCount aValue )
{
/* The PTX version results in much tighter code than the C version.
* The C version produces four instructions per step (a ISETP,
* IADD, SHFL and SEL); the inline PTX version gets it down to two
* (SHFL + predicated IADD).
*
* Incidentally, the PTX code is shown as an example for the shfl
* instruction in the PTX ISA document. See
* http://docs.nvidia.com/cuda/parallel-thread-execution/index.html
*/
# if 0
auto x0 = __shfl_up( aValue, 1 );
aValue += (aWTID >= 1) ? x0 : 0;
auto x1 = __shfl_up( aValue, 2 );
aValue += (aWTID >= 2) ? x1 : 0;
auto x2 = __shfl_up( aValue, 4 );
aValue += (aWTID >= 4) ? x2 : 0;
auto x3 = __shfl_up( aValue, 8 );
aValue += (aWTID >= 8) ? x3 : 0;
auto x4 = __shfl_up( aValue, 16 );
aValue += (aWTID >= 16) ? x4 : 0;
# else
__asm__ volatile( "{\n\t"
".reg .u32 t0;\n\t"
".reg .pred valid;\n\t"
"shfl.up.b32 t0|valid, %0, 1, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 2, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 4, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 8, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 16, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"}\n\t"
: "+r"(aValue)
);
# endif
return aValue;
}
template< typename tReal > __device__ inline
tReal reduce0( tReal aValue )
{
aValue += __shfl_down( aValue, 16 );
aValue += __shfl_down( aValue, 8 );
aValue += __shfl_down( aValue, 4 );
aValue += __shfl_down( aValue, 2 );
aValue += __shfl_down( aValue, 1 );
return aValue;
}
}
template< typename tReal, typename tCount > __global__
void /*__launch_bounds__(1024,1)*/ K_distance( tReal* aDistance, unsigned aN, unsigned aM, tCount* aCur, tCount const* aRef )
{
__shared__ tReal totals[32]; //XXX-FIXME: number of warps in block.
auto const warp = threadIdx.y;
auto const wtid = threadIdx.x;
auto const n32 = (aN+32-1)/32*32;
auto const m32 = (aM+32-1)/32*32;
// init
if( 0 == warp )
{
totals[wtid] = tReal(0);
}
__syncthreads();
// column-wise prefix sums
for( auto row = warp; row < aN; row += blockDim.y )
{
tCount base = 0;
for( auto col = wtid; col < m32; col += 32 )
{
tCount const val = col < aM
? aCur[row*aM+col]
: 0
;
tCount const sum = base + detail::warp_prefix( wtid, val );
if( col < aM )
aCur[row*aM+col] = sum;
base = __shfl( sum, 31 );
}
}
__syncthreads();
// row-wise prefix sums, and accumulate the squared difference to the reference
tReal acc = tReal(0);
for( auto col = warp; col < aM; col += blockDim.y )
{
tCount base = 0;
tReal a2 = tReal(0);
for( auto row = wtid; row < n32; row += 32 )
{
tCount const val = row < aN
? aCur[row*aM+col]
: 0
;
tCount const sum = base + detail::warp_prefix( wtid, val );
base = __shfl( sum, 31 );
if( row < aN )
{
tCount const ref = aRef[row*aM+col];
tReal const dd = tReal(sum) - ref;
a2 += dd*dd;
}
}
acc += a2;
}
// reduce the per-thread sums in each warp
tReal const wsum = detail::reduce0( acc );
if( 0 == wtid )
totals[warp] = wsum;
__syncthreads();
// have one warp reduce the per-warp sums to the final sum
if( 0 == warp )
{
tReal const tsum = wtid < 32 //XXX
? totals[wtid]
: 0
;
tReal const fin = detail::reduce0( tsum );
if( 0 == wtid )
*aDistance = fin;
}
// zero out the histogram for the next invocation
for( auto row = warp; row < aN; row += blockDim.y )
{
for( auto col = wtid; col < m32; col += 32 )
{
aCur[row*aM+col] = 0;
}
}
}
}
<commit_msg>Fixed: GPU write out of bounds<commit_after>
namespace cusim
{
namespace detail
{
template< typename tCount > __device__ inline
tCount warp_prefix( unsigned aWTID, tCount aValue )
{
/* The PTX version results in much tighter code than the C version.
* The C version produces four instructions per step (a ISETP,
* IADD, SHFL and SEL); the inline PTX version gets it down to two
* (SHFL + predicated IADD).
*
* Incidentally, the PTX code is shown as an example for the shfl
* instruction in the PTX ISA document. See
* http://docs.nvidia.com/cuda/parallel-thread-execution/index.html
*/
# if 0
auto x0 = __shfl_up( aValue, 1 );
aValue += (aWTID >= 1) ? x0 : 0;
auto x1 = __shfl_up( aValue, 2 );
aValue += (aWTID >= 2) ? x1 : 0;
auto x2 = __shfl_up( aValue, 4 );
aValue += (aWTID >= 4) ? x2 : 0;
auto x3 = __shfl_up( aValue, 8 );
aValue += (aWTID >= 8) ? x3 : 0;
auto x4 = __shfl_up( aValue, 16 );
aValue += (aWTID >= 16) ? x4 : 0;
# else
__asm__ volatile( "{\n\t"
".reg .u32 t0;\n\t"
".reg .pred valid;\n\t"
"shfl.up.b32 t0|valid, %0, 1, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 2, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 4, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 8, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"shfl.up.b32 t0|valid, %0, 16, 0;\n\t"
"@valid add.s32 %0, t0, %0;\n\t"
"}\n\t"
: "+r"(aValue)
);
# endif
return aValue;
}
template< typename tReal > __device__ inline
tReal reduce0( tReal aValue )
{
aValue += __shfl_down( aValue, 16 );
aValue += __shfl_down( aValue, 8 );
aValue += __shfl_down( aValue, 4 );
aValue += __shfl_down( aValue, 2 );
aValue += __shfl_down( aValue, 1 );
return aValue;
}
}
template< typename tReal, typename tCount > __global__
void /*__launch_bounds__(1024,1)*/ K_distance( tReal* aDistance, unsigned aN, unsigned aM, tCount* aCur, tCount const* aRef )
{
__shared__ tReal totals[32]; //XXX-FIXME: number of warps in block.
auto const warp = threadIdx.y;
auto const wtid = threadIdx.x;
auto const n32 = (aN+32-1)/32*32;
auto const m32 = (aM+32-1)/32*32;
// init
if( 0 == warp )
{
totals[wtid] = tReal(0);
}
__syncthreads();
// column-wise prefix sums
for( auto row = warp; row < aN; row += blockDim.y )
{
tCount base = 0;
for( auto col = wtid; col < m32; col += 32 )
{
tCount const val = col < aM
? aCur[row*aM+col]
: 0
;
tCount const sum = base + detail::warp_prefix( wtid, val );
if( col < aM )
aCur[row*aM+col] = sum;
base = __shfl( sum, 31 );
}
}
__syncthreads();
// row-wise prefix sums, and accumulate the squared difference to the reference
tReal acc = tReal(0);
for( auto col = warp; col < aM; col += blockDim.y )
{
tCount base = 0;
tReal a2 = tReal(0);
for( auto row = wtid; row < n32; row += 32 )
{
tCount const val = row < aN
? aCur[row*aM+col]
: 0
;
tCount const sum = base + detail::warp_prefix( wtid, val );
base = __shfl( sum, 31 );
if( row < aN )
{
tCount const ref = aRef[row*aM+col];
tReal const dd = tReal(sum) - ref;
a2 += dd*dd;
}
}
acc += a2;
}
// reduce the per-thread sums in each warp
tReal const wsum = detail::reduce0( acc );
if( 0 == wtid )
totals[warp] = wsum;
__syncthreads();
// have one warp reduce the per-warp sums to the final sum
if( 0 == warp )
{
tReal const tsum = wtid < 32 //XXX
? totals[wtid]
: 0
;
tReal const fin = detail::reduce0( tsum );
if( 0 == wtid )
*aDistance = fin;
}
// zero out the histogram for the next invocation
for( auto row = warp; row < aN; row += blockDim.y )
{
for( auto col = wtid; col < aM; col += 32 )
{
aCur[row*aM+col] = 0;
}
}
}
}
<|endoftext|> |
<commit_before>/**
* @file rotations.hpp
* @author Paul Furgale <[email protected]>
* @date Mon Nov 22 21:45:54 2010
*
* @brief
*
*
*/
#define SM_2_PI 0.6366197723675814 // 2/pi
#define SM_PI 3.141592653589793 // pi
#define SM_PI_2 1.5707963267948966 // pi/2
#define SM_PI_4 0.7853981633974483 // pi/4
#define SM_2PI 6.283185307179586 // 2*pi
#define SM_DEG2RAD 0.017453292519943 // pi/180
#define SM_RAD2DEG 57.295779513082323 // 180/pi
#define SM_1_PI_F 0.3183098861837907f
#define SM_2_PI_F 0.6366197723675814f
#define SM_PI_F 3.141592653589793f
#define SM_PI_2_F 1.5707963267948966f
#define SM_PI_4_F 0.7853981633974483f
#define SM_2PI_F 6.283185307179586f
#define SM_DEG2RAD_F 0.017453292519943f
#define SM_RAD2DEG_F 57.295779513082323f
#include <Eigen/Core>
namespace sm { namespace kinematics {
// Principle axis rotations.
Eigen::Matrix3d Rx(double radians);
Eigen::Matrix3d Ry(double radians);
Eigen::Matrix3d Rz(double radians);
Eigen::Matrix3d rph2R(double x, double y, double z);
Eigen::Matrix3d rph2R(Eigen::Vector3d const & x);
Eigen::Vector3d R2rph(Eigen::Matrix3d const & C);
// The C rotations are more standard. They go the other way
Eigen::Matrix3d Cx(double radians);
Eigen::Matrix3d Cy(double radians);
Eigen::Matrix3d Cz(double radians);
Eigen::Matrix3d rph2C(double x, double y, double z);
Eigen::Matrix3d rph2C(Eigen::Vector3d const & x);
Eigen::Vector3d C2rph(Eigen::Matrix3d const & C);
// Small angle approximation.
Eigen::Matrix3d crossMx(double x, double y, double z);
Eigen::Matrix3d crossMx(Eigen::Vector3d const & x);
// Axis Angle rotation.
Eigen::Matrix3d axisAngle2R(double a, double ax, double ay, double az);
Eigen::Matrix3d axisAngle2R(double x, double y, double z);
Eigen::Matrix3d axisAngle2R(Eigen::Vector3d const & x);
Eigen::Vector3d R2AxisAngle(Eigen::Matrix3d const & C);
// Utility functions
// Moves a value in radians to within -pi, pi
double angleMod(double radians);
double deg2rad(double degrees);
double rad2deg(double radians);
}} // namespace sm::kinematics
<commit_msg>added missing include guard in rotations.hpp<commit_after>/**
* @file rotations.hpp
* @author Paul Furgale <[email protected]>
* @date Mon Nov 22 21:45:54 2010
*
* @brief
*
*
*/
#ifndef SM_ROTATIONS_HPP
#define SM_ROTATIONS_HPP
#define SM_2_PI 0.6366197723675814 // 2/pi
#define SM_PI 3.141592653589793 // pi
#define SM_PI_2 1.5707963267948966 // pi/2
#define SM_PI_4 0.7853981633974483 // pi/4
#define SM_2PI 6.283185307179586 // 2*pi
#define SM_DEG2RAD 0.017453292519943 // pi/180
#define SM_RAD2DEG 57.295779513082323 // 180/pi
#define SM_1_PI_F 0.3183098861837907f
#define SM_2_PI_F 0.6366197723675814f
#define SM_PI_F 3.141592653589793f
#define SM_PI_2_F 1.5707963267948966f
#define SM_PI_4_F 0.7853981633974483f
#define SM_2PI_F 6.283185307179586f
#define SM_DEG2RAD_F 0.017453292519943f
#define SM_RAD2DEG_F 57.295779513082323f
#include <Eigen/Core>
namespace sm { namespace kinematics {
// Principle axis rotations.
Eigen::Matrix3d Rx(double radians);
Eigen::Matrix3d Ry(double radians);
Eigen::Matrix3d Rz(double radians);
Eigen::Matrix3d rph2R(double x, double y, double z);
Eigen::Matrix3d rph2R(Eigen::Vector3d const & x);
Eigen::Vector3d R2rph(Eigen::Matrix3d const & C);
// The C rotations are more standard. They go the other way
Eigen::Matrix3d Cx(double radians);
Eigen::Matrix3d Cy(double radians);
Eigen::Matrix3d Cz(double radians);
Eigen::Matrix3d rph2C(double x, double y, double z);
Eigen::Matrix3d rph2C(Eigen::Vector3d const & x);
Eigen::Vector3d C2rph(Eigen::Matrix3d const & C);
// Small angle approximation.
Eigen::Matrix3d crossMx(double x, double y, double z);
Eigen::Matrix3d crossMx(Eigen::Vector3d const & x);
// Axis Angle rotation.
Eigen::Matrix3d axisAngle2R(double a, double ax, double ay, double az);
Eigen::Matrix3d axisAngle2R(double x, double y, double z);
Eigen::Matrix3d axisAngle2R(Eigen::Vector3d const & x);
Eigen::Vector3d R2AxisAngle(Eigen::Matrix3d const & C);
// Utility functions
// Moves a value in radians to within -pi, pi
double angleMod(double radians);
double deg2rad(double degrees);
double rad2deg(double radians);
}} // namespace sm::kinematics
#endif // ndef SM_ROTATIONS_HPP
<|endoftext|> |
<commit_before>/*
* AnalyticPassPlanner.cpp
*
* Created on: Dec 9, 2009
* Author: Philip Rogers
*/
#include <AnalyticPassPlanner.hpp>
#include <motion/planning/rrt.hpp>
#include <framework/Path.hpp>
#include <PassState.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
using namespace Geometry2d;
using namespace Gameplay;
using namespace std;
#define TIME_TO_AIM_APPROX 0.3 // seconds it takes for the robot to pivot for an aim. Due to aiming time in kick behavior, even if we knew rot accel, this is an approximation.
#define BALL_KICK_AVG_VEL 1.0 // average speed of ball during a kick ((kick vel + end vel) / 2) very conservative due to inaccurate kick speeds and varying dynamics
void AnalyticPassPlanner::generateAllConfigs(const Point &ballPos, set<Robot *> &robots, PassConfigVector &passConfigResult){
Geometry2d::Point goalBallPos = Geometry2d::Point(0.0, Constants::Field::Length);
Planning::Path path;
ObstacleGroup og;
float pathDist, pathTime;
// for times and distances, use a conservative estimate of 45deg. travel
Robot* rTmp = *(robots.begin());
float maxVel = rTmp->packet()->config.motion.deg45.velocity;
float timeStopToMaxVel = maxVel/ rTmp->packet()->config.motion.deg45.acceleration;
float timeMaxVelToStop = maxVel / rTmp->packet()->config.motion.deg45.deceleration;
float distStopToMaxVel = 0.5 * maxVel * timeStopToMaxVel;
float distMaxVelToStop = 0.5 * maxVel * timeMaxVelToStop;
BOOST_FOREACH(Robot *r1, robots){
if(!r1->visible()){continue;} // don't use invisible robots
BOOST_FOREACH(Robot *r2, robots){
if(!r2->visible()){continue;} // don't use invisible robots
if(r2->id()==r1->id()){continue;} // don't pass to self
PassConfig* passConfig = new PassConfig();
// setup calculations
Point passVec = (r2->pos() - ballPos).normalized();
float passAngle = passVec.angle();
Point goalVec = (goalBallPos - r2->pos()).normalized();
float goalAngle = goalVec.angle();
// add initial state with no robots having the ball
passConfig->addPassState(
PassState(r1, r2, r1->pos(), r2->pos(), r1->angle(), r2->angle(),
ballPos, PassState::INTERMEDIATE, 0));
// add state with robot1 at a position to pass to robot2
Point state2Robot1Pos = ballPos - passVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state2Robot1Rot = passAngle;
// calculate time
og = r1->obstacles();
Point r1pos = r1->pos();
float r1angle = r1->angle();
Point r1vel = r1->vel();
Motion::RRT::Planner planner;
Motion::Dynamics dynamics;
dynamics.setConfig(_gameplay->state()->self[r1->id()].config.motion);
planner.setDynamics(&dynamics);
planner.run(r1pos,r1angle,r1vel,ballPos,&og,path);
pathDist = path.length(0);
if(pathDist < distStopToMaxVel + distMaxVelToStop){
pathTime = (pathDist/(distStopToMaxVel + distMaxVelToStop))*(timeStopToMaxVel + timeMaxVelToStop);
}else{
pathTime = timeStopToMaxVel + timeMaxVelToStop + (pathDist - (distStopToMaxVel + distMaxVelToStop))/maxVel;
}
double state2Time = pathTime + TIME_TO_AIM_APPROX;
//double state2Time = r1->pos().distTo(state2Robot1Pos) / APPROXROBOTVELTRANS;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, r2->pos(), state2Robot1Rot, r2->angle(),
ballPos, PassState::KICKPASS, state2Time));
// add state with robot2 receiving ball
Point state3BallPos = r2->pos();
Point state3Robot2Pos = state3BallPos + passVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state3Robot2Rot = (passVec * -1.0f).angle();
double state3Time = state2Time + r2->pos().distTo(state3Robot2Pos) / BALL_KICK_AVG_VEL;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state3Robot2Pos, state2Robot1Rot, state3Robot2Rot,
state3BallPos, PassState::RECEIVEPASS, state3Time));
// add state with robot2 kicking a goal
Point state4Robot2Pos = state3BallPos - goalVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state4Robot2Rot = goalAngle;
double state4Time = state3Time + state3Robot2Pos.distTo(state4Robot2Pos) / TIME_TO_AIM_APPROX;
//double state4Time = state3Time + state3Robot2Pos.distTo(state4Robot2Pos) / APPROXROBOTVELTRANS;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state4Robot2Pos, state2Robot1Rot, state4Robot2Rot,
state3BallPos, PassState::KICKGOAL, state4Time));
// add state with ball in goal
double state5Time = state4Time + state3BallPos.distTo(goalBallPos) / BALL_KICK_AVG_VEL;
//double state5Time = state4Time + state3BallPos.distTo(goalBallPos) / APPROXBALLVEL;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state4Robot2Pos, state2Robot1Rot, state4Robot2Rot,
goalBallPos, PassState::INTERMEDIATE, state5Time));
passConfigResult.push_back(passConfig);
}
}
}
void AnalyticPassPlanner::evaluateConfigs(set<Robot *> &robots, Robot** opponents, PassConfigVector &passConfigs){
Geometry2d::Point goalBallPos = Geometry2d::Point(0.0, Constants::Field::Length);
//
// Weight configs
//
PassState prevState;
// locate opponent's goalie by finding closest opponent to goal
Robot *oppGoalie = opponents[0];
float bestDist = oppGoalie->pos().distTo(goalBallPos), thisDist;
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
thisDist = opponentR->pos().distTo(goalBallPos);
if(thisDist < bestDist){
oppGoalie = opponentR;
bestDist = thisDist;
}
}
Planning::Path path;Motion::RRT::Planner planner;
ObstacleGroup og;
float pathDist, pathTime;
Robot* rTmp = *(robots.begin());
float maxVel = rTmp->packet()->config.motion.deg45.velocity;
float timeStopToMaxVel = maxVel/ rTmp->packet()->config.motion.deg45.acceleration;
float timeMaxVelToStop = maxVel / rTmp->packet()->config.motion.deg45.deceleration;
float distStopToMaxVel = 0.5 * maxVel * timeStopToMaxVel;
float distMaxVelToStop = 0.5 * maxVel * timeMaxVelToStop;
for(int i=0; i<(int)passConfigs.size(); i++){
int numInteractions = 0;
// calculate the total number of opponents that can touch the ball at each intermediate
// ballPos (where the ball will be waiting for the robot to pivot and pass)
for(int j=0; j<passConfigs[i].length(); j++){
PassState thisState = passConfigs[i].getPassState(j);
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
if(opponentR->id() == oppGoalie->id()){continue;} // do not consider opponent's goalie
og = opponentR->obstacles();
Motion::RRT::Planner planner;
planner.run(opponentR->pos(),opponentR->angle(),opponentR->vel(),thisState.ballPos,&og,path);
pathDist = path.length(0);
if(pathDist < distStopToMaxVel + distMaxVelToStop){
pathTime = (pathDist/(distStopToMaxVel + distMaxVelToStop))*(timeStopToMaxVel + timeMaxVelToStop);
}else{
pathTime = timeStopToMaxVel + timeMaxVelToStop + (pathDist - (distStopToMaxVel + distMaxVelToStop))/maxVel;
}
if(pathTime < thisState.timestamp){
numInteractions++;
}
}
if(thisState.stateType == PassState::KICKGOAL){
break; // do not include the last state with ball in goal.
}
}
// calculate the total number of opponents that currently intersect
// the ball's path at this instant.
for(int j=0; j<passConfigs[i].length(); j++){
PassState thisState = passConfigs[i].getPassState(j);
Line ballPath(thisState.ballPos,prevState.ballPos);
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
if(opponentR->id() == oppGoalie->id()){continue;} // do not consider opponent's goalie
// use 1.5*Radius to give "wiggle room"
if(ballPath.distTo(opponentR->pos()) < (float)(Constants::Robot::Radius + 1.5*Constants::Ball::Radius)){
numInteractions++;
}
}
prevState = thisState;
}
passConfigs[i].setWeight(numInteractions);
}
passConfigs.sort();
}
<commit_msg>Changed analytic planner to use new state setup<commit_after>/*
* AnalyticPassPlanner.cpp
*
* Created on: Dec 9, 2009
* Author: Philip Rogers
*/
#include <AnalyticPassPlanner.hpp>
#include <motion/planning/rrt.hpp>
#include <framework/Path.hpp>
#include <PassState.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
using namespace Geometry2d;
using namespace Gameplay;
using namespace std;
#define TIME_TO_AIM_APPROX 0.3 // seconds it takes for the robot to pivot for an aim. Due to aiming time in kick behavior, even if we knew rot accel, this is an approximation.
#define BALL_KICK_AVG_VEL 1.0 // average speed of ball during a kick ((kick vel + end vel) / 2) very conservative due to inaccurate kick speeds and varying dynamics
void AnalyticPassPlanner::generateAllConfigs(const Point &ballPos, set<Robot *> &robots, PassConfigVector &passConfigResult){
Geometry2d::Point goalBallPos = Geometry2d::Point(0.0, Constants::Field::Length);
Planning::Path path;
ObstacleGroup og;
float pathDist, pathTime;
// for times and distances, use a conservative estimate of 45deg. travel
Robot* rTmp = *(robots.begin());
float maxVel = rTmp->packet()->config.motion.deg45.velocity;
float timeStopToMaxVel = maxVel/ rTmp->packet()->config.motion.deg45.acceleration;
float timeMaxVelToStop = maxVel / rTmp->packet()->config.motion.deg45.deceleration;
float distStopToMaxVel = 0.5 * maxVel * timeStopToMaxVel;
float distMaxVelToStop = 0.5 * maxVel * timeMaxVelToStop;
BOOST_FOREACH(Robot *r1, robots){
if(!r1->visible()){continue;} // don't use invisible robots
BOOST_FOREACH(Robot *r2, robots){
if(!r2->visible()){continue;} // don't use invisible robots
if(r2->id()==r1->id()){continue;} // don't pass to self
PassConfig* passConfig = new PassConfig();
// setup calculations
Point passVec = (r2->pos() - ballPos).normalized();
float passAngle = passVec.angle();
Point goalVec = (goalBallPos - r2->pos()).normalized();
float goalAngle = goalVec.angle();
// add initial state with no robots having the ball
passConfig->addPassState(
PassState(r1, r2, r1->pos(), r2->pos(), r1->angle(), r2->angle(),
ballPos, PassState::INITIAL, 0));
// add state with robot1 at a position to pass to robot2
Point state2Robot1Pos = ballPos - passVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state2Robot1Rot = passAngle;
Point state2Robot2Pos = r2->pos();
float state2Robot2Rot = (passVec * -1.0f).angle();
// calculate time
og = r1->obstacles();
Point r1pos = r1->pos();
float r1angle = r1->angle();
Point r1vel = r1->vel();
Motion::RRT::Planner planner;
Motion::Dynamics dynamics;
dynamics.setConfig(_gameplay->state()->self[r1->id()].config.motion);
planner.setDynamics(&dynamics);
planner.run(r1pos,r1angle,r1vel,ballPos,&og,path);
pathDist = path.length(0);
if(pathDist < distStopToMaxVel + distMaxVelToStop){
pathTime = (pathDist/(distStopToMaxVel + distMaxVelToStop))*(timeStopToMaxVel + timeMaxVelToStop);
}else{
pathTime = timeStopToMaxVel + timeMaxVelToStop + (pathDist - (distStopToMaxVel + distMaxVelToStop))/maxVel;
}
double state2Time = pathTime + TIME_TO_AIM_APPROX;
//double state2Time = r1->pos().distTo(state2Robot1Pos) / APPROXROBOTVELTRANS;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state2Robot2Pos, state2Robot1Rot, state2Robot2Rot,
ballPos, PassState::KICKPASS, state2Time));
// add state with robot2 receiving ball
Point state3BallPos = state2Robot2Pos;
Point state3Robot2Pos = state3BallPos + passVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state3Robot2Rot = (passVec * -1.0f).angle();
double state3Time = state2Time + r2->pos().distTo(state3Robot2Pos) / BALL_KICK_AVG_VEL;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state3Robot2Pos, state2Robot1Rot, state3Robot2Rot,
state3BallPos, PassState::RECEIVEPASS, state3Time));
// add state with robot2 kicking a goal
Point state4Robot2Pos = state3BallPos - goalVec * (float)(Constants::Robot::Radius + Constants::Ball::Radius);
float state4Robot2Rot = goalAngle;
double state4Time = state3Time + state3Robot2Pos.distTo(state4Robot2Pos) / TIME_TO_AIM_APPROX;
//double state4Time = state3Time + state3Robot2Pos.distTo(state4Robot2Pos) / APPROXROBOTVELTRANS;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state4Robot2Pos, state2Robot1Rot, state4Robot2Rot,
state3BallPos, PassState::KICKGOAL, state4Time));
// add state with ball in goal
double state5Time = state4Time + state3BallPos.distTo(goalBallPos) / BALL_KICK_AVG_VEL;
//double state5Time = state4Time + state3BallPos.distTo(goalBallPos) / APPROXBALLVEL;
passConfig->addPassState(
PassState(r1, r2, state2Robot1Pos, state4Robot2Pos, state2Robot1Rot, state4Robot2Rot,
goalBallPos, PassState::GOAL, state5Time));
passConfigResult.push_back(passConfig);
}
}
}
void AnalyticPassPlanner::evaluateConfigs(set<Robot *> &robots, Robot** opponents, PassConfigVector &passConfigs){
Geometry2d::Point goalBallPos = Geometry2d::Point(0.0, Constants::Field::Length);
//
// Weight configs
//
PassState prevState;
// locate opponent's goalie by finding closest opponent to goal
Robot *oppGoalie = opponents[0];
float bestDist = oppGoalie->pos().distTo(goalBallPos), thisDist;
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
thisDist = opponentR->pos().distTo(goalBallPos);
if(thisDist < bestDist){
oppGoalie = opponentR;
bestDist = thisDist;
}
}
Planning::Path path;Motion::RRT::Planner planner;
ObstacleGroup og;
float pathDist, pathTime;
Robot* rTmp = *(robots.begin());
float maxVel = rTmp->packet()->config.motion.deg45.velocity;
float timeStopToMaxVel = maxVel/ rTmp->packet()->config.motion.deg45.acceleration;
float timeMaxVelToStop = maxVel / rTmp->packet()->config.motion.deg45.deceleration;
float distStopToMaxVel = 0.5 * maxVel * timeStopToMaxVel;
float distMaxVelToStop = 0.5 * maxVel * timeMaxVelToStop;
for(int i=0; i<(int)passConfigs.size(); i++){
int numInteractions = 0;
// calculate the total number of opponents that can touch the ball at each intermediate
// ballPos (where the ball will be waiting for the robot to pivot and pass)
for(int j=0; j<passConfigs[i].length(); j++){
PassState thisState = passConfigs[i].getPassState(j);
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
if(opponentR->id() == oppGoalie->id()){continue;} // do not consider opponent's goalie
og = opponentR->obstacles();
Motion::RRT::Planner planner;
planner.run(opponentR->pos(),opponentR->angle(),opponentR->vel(),thisState.ballPos,&og,path);
pathDist = path.length(0);
if(pathDist < distStopToMaxVel + distMaxVelToStop){
pathTime = (pathDist/(distStopToMaxVel + distMaxVelToStop))*(timeStopToMaxVel + timeMaxVelToStop);
}else{
pathTime = timeStopToMaxVel + timeMaxVelToStop + (pathDist - (distStopToMaxVel + distMaxVelToStop))/maxVel;
}
if(pathTime < thisState.timestamp){
numInteractions++;
}
}
if(thisState.stateType == PassState::KICKGOAL){
break; // do not include the last state with ball in goal.
}
}
// calculate the total number of opponents that currently intersect
// the ball's path at this instant.
for(int j=0; j<passConfigs[i].length(); j++){
PassState thisState = passConfigs[i].getPassState(j);
Line ballPath(thisState.ballPos,prevState.ballPos);
for (int i=0; i<Constants::Robots_Per_Team; ++i){
Robot *opponentR = opponents[i];
if(opponentR->id() == oppGoalie->id()){continue;} // do not consider opponent's goalie
// use 1.5*Radius to give "wiggle room"
if(ballPath.distTo(opponentR->pos()) < (float)(Constants::Robot::Radius + 1.5*Constants::Ball::Radius)){
numInteractions++;
}
}
prevState = thisState;
}
passConfigs[i].setWeight(numInteractions);
}
passConfigs.sort();
}
<|endoftext|> |
<commit_before>#include <climits>
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <set>
#include <wibble/commandline/parser.h>
#include <elevator/elevator.h>
#include <elevator/scheduler.h>
#include <elevator/udptools.h>
#include <elevator/udpqueue.h>
#include <elevator/sessionmanager.h>
namespace elevator {
using namespace wibble;
using namespace wibble::commandline;
using namespace udp;
struct Main {
const Address commSend{ IPv4Address::any, Port{ 64123 } };
const Address commRcv{ IPv4Address::any, Port{ 64125 } };
const Address commBroadcast{ IPv4Address::broadcast, Port{ 64125 } };
const Port stateChangePort{ 64016 };
const Port commandPort{ 64017 };
StandardParser opts;
OptionGroup *execution;
IntOption *optNodes;
BoolOption *avoidRecovery;
const int peerMsg = 1000;
std::set< IPv4Address > peerAddresses;
int id = INT_MIN;
int nodes = 1;
Main( int argc, const char **argv ) : opts( "elevator", "0.1" ) {
// setup options
execution = opts.createGroup( "Execution options" );
optNodes = execution->add< IntOption >(
"nodes", 'n', "nodes", "",
"specifies number of elevator nodes to expect" );
avoidRecovery = execution->add< BoolOption >(
"avoid recovery", 0, "avoid-recovery", "",
"avoid auto-recovery when program is killed (do not fork)" );
opts.usage = "";
opts.description = "Elevator control software as a project for the "
"TTK4145 Real-Time Programming at NTNU. Controls "
"multiple elevator connected with local network.\n"
"(c) 2014, Vladimír Štill and Sameh Khalil\n"
"https://github.com/vlstill/ttk4145/tree/master/project";
opts.add( execution );
// parse options
try {
opts.parse( argc, argv );
} catch ( exception::BadOption &ex ) {
std::cerr << "FATAL: " << ex.fullInfo() << std::endl;
exit( 1 );
}
if ( opts.help->boolValue() || opts.version->boolValue() )
exit( 0 );
}
void main() {
if ( avoidRecovery->boolValue() ) {
runElevator();
} else {
assert_unimplemented();
}
}
void runElevator() {
int id;
GlobalState global;
SessionManager sessman{ global };
if ( optNodes->boolValue() && optNodes->intValue() > 1 ) {
nodes = optNodes->intValue();
sessman.connect( nodes );
id = sessman.id();
} else {
id = 0;
}
std::cout << "starting elevator, id " << id << " of " << nodes << " elevators" << std::endl;
HeartBeatManager heartbeatManager;
ConcurrentQueue< Command > commandsToLocalElevator;
ConcurrentQueue< Command > commandsToOthers;
ConcurrentQueue< StateChange > stateChangesIn;
ConcurrentQueue< StateChange > stateChangesOut;
std::unique_ptr< QueueReceiver< Command > > commandsToLocalElevatorReceiver;
std::unique_ptr< QueueReceiver< StateChange > > stateChangesInReceiver;
std::unique_ptr< QueueSender< StateChange > > stateChangesOutSender;
std::unique_ptr< QueueSender< Command > > commandsToOthersReceiver;
if ( nodes > 1 ) {
commandsToOthersReceiver.reset( new QueueSender< Command >{
commSend,
Address{ IPv4Address::broadcast, commandPort },
commandsToOthers
} );
commandsToLocalElevatorReceiver.reset( new QueueReceiver< Command >{
Address{ IPv4Address::any, commandPort },
commandsToLocalElevator,
[id]( const Command &comm ) { return comm.targetElevatorId == id; }
} );
stateChangesInReceiver.reset( new QueueReceiver< StateChange >{
Address{ IPv4Address::any, stateChangePort },
stateChangesIn,
[id]( const StateChange &chan ) { return chan.state.id != id; }
} );
stateChangesOutSender.reset( new QueueSender< StateChange >{
commSend,
Address{ IPv4Address::broadcast, stateChangePort },
stateChangesOut
} );
}
/* about heartbeat lengths:
* - elevator loop is polling and never sleeping, therefore its scheduling
* is quite relieable and it can have short heartbeat,
* furthermore we need to make sure we will detect any floor change,
* therefore heartbeat it must respond faster then is time to cross sensor
* (approx 400ms), also note that even with heartbeat of 10ms the elevator
* seems to be running reliably
* - scheduler again has quite tight demand, as it should be able to handle
* all state changes from elevator, but we have to be more carefull here
* as it is sleeping sometimes
*/
Elevator elevator{ id, heartbeatManager.getNew( 500 /* ms */ ),
commandsToLocalElevator, stateChangesIn };
Scheduler scheduler{ id, heartbeatManager.getNew( 1000 /* ms */ ),
elevator.info(),
stateChangesIn, stateChangesOut, commandsToOthers, commandsToLocalElevator };
if ( nodes > 1 ) {
commandsToLocalElevatorReceiver->run();
stateChangesInReceiver->run();
commandsToOthersReceiver->run();
stateChangesOutSender->run();
}
elevator.run();
scheduler.run();
// wait for 2 seconds so that everything has chance to start
// it something fails to start in this time heartbeat will
// fail and process will be terminated
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
// heartbeat failure will throw an exception which will terminate
// process (as it is not catched)
heartbeatManager.runInThisThread();
}
};
}
int main( int args, const char **argv ) {
elevator::Main m( args, argv );
m.main();
}
<commit_msg>main: Use automatic recovery in case of receiving signal.<commit_after>#include <climits>
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <set>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <wibble/commandline/parser.h>
#include <string.h>
#include <elevator/driver.h>
#include <elevator/test.h>
#include <elevator/elevator.h>
#include <elevator/scheduler.h>
#include <elevator/udptools.h>
#include <elevator/udpqueue.h>
#include <elevator/sessionmanager.h>
void handler( int sig, siginfo_t *info, void * ) {
elevator::Driver driver;
driver.stopElevator();
std::cerr << "elevator stopped" << std::endl;
if ( sig != SIGCHLD ) {
exit( sig );
} else {
int pid = info->si_pid;
waitpid( pid, nullptr, WNOHANG );
}
}
namespace elevator {
using namespace wibble;
using namespace wibble::commandline;
using namespace udp;
struct Main {
const Address commSend{ IPv4Address::any, Port{ 64123 } };
const Address commRcv{ IPv4Address::any, Port{ 64125 } };
const Address commBroadcast{ IPv4Address::broadcast, Port{ 64125 } };
const Port stateChangePort{ 64016 };
const Port commandPort{ 64017 };
StandardParser opts;
OptionGroup *execution;
IntOption *optNodes;
BoolOption *avoidRecovery;
const int peerMsg = 1000;
std::set< IPv4Address > peerAddresses;
int id = INT_MIN;
int nodes = 1;
Main( int argc, const char **argv ) : opts( "elevator", "0.1" ) {
// setup options
execution = opts.createGroup( "Execution options" );
optNodes = execution->add< IntOption >(
"nodes", 'n', "nodes", "",
"specifies number of elevator nodes to expect" );
avoidRecovery = execution->add< BoolOption >(
"avoid recovery", 0, "avoid-recovery", "",
"avoid auto-recovery when program is killed (do not fork)" );
opts.usage = "";
opts.description = "Elevator control software as a project for the "
"TTK4145 Real-Time Programming at NTNU. Controls "
"multiple elevator connected with local network.\n"
"(c) 2014, Vladimír Štill and Sameh Khalil\n"
"https://github.com/vlstill/ttk4145/tree/master/project";
opts.add( execution );
// parse options
try {
opts.parse( argc, argv );
} catch ( exception::BadOption &ex ) {
std::cerr << "FATAL: " << ex.fullInfo() << std::endl;
exit( 1 );
}
if ( opts.help->boolValue() || opts.version->boolValue() )
exit( 0 );
}
void setupChild() {
struct sigaction act;
memset( &act, 0, sizeof( struct sigaction ) );
act.sa_handler = SIG_DFL;
sigaction( SIGCHLD, &act, nullptr );
sigaction( SIGINT, &act, nullptr );
runElevator();
}
void watchChild( int childPid ) {
while ( true ) {
pause(); // wait for signal
initRecovery();
}
}
void setupSignals() {
struct sigaction act;
memset( &act, 0, sizeof( struct sigaction ) );
act.sa_sigaction = handler;
act.sa_flags = SA_SIGINFO;
sigaction( SIGCHLD, &act, nullptr ); // child died
sigaction( SIGINT, &act, nullptr ); // ctrl+c
}
void initRecovery() {
setupSignals();
int pid = fork();
if ( pid == 0 ) { // child
setupChild();
} else if ( pid > 0 ) { // parent
watchChild( pid );
} else {
std::cerr << "Fatal error: fork failed" << std::endl;
exit( 1 );
}
}
void main() {
if ( avoidRecovery->boolValue() ) {
runElevator();
} else {
initRecovery();
}
}
void runElevator() {
int id;
GlobalState global;
SessionManager sessman{ global };
if ( optNodes->boolValue() && optNodes->intValue() > 1 ) {
nodes = optNodes->intValue();
sessman.connect( nodes );
id = sessman.id();
} else {
id = 0;
}
std::cout << "starting elevator, id " << id << " of " << nodes << " elevators" << std::endl;
HeartBeatManager heartbeatManager;
ConcurrentQueue< Command > commandsToLocalElevator;
ConcurrentQueue< Command > commandsToOthers;
ConcurrentQueue< StateChange > stateChangesIn;
ConcurrentQueue< StateChange > stateChangesOut;
std::unique_ptr< QueueReceiver< Command > > commandsToLocalElevatorReceiver;
std::unique_ptr< QueueReceiver< StateChange > > stateChangesInReceiver;
std::unique_ptr< QueueSender< StateChange > > stateChangesOutSender;
std::unique_ptr< QueueSender< Command > > commandsToOthersReceiver;
if ( nodes > 1 ) {
commandsToOthersReceiver.reset( new QueueSender< Command >{
commSend,
Address{ IPv4Address::broadcast, commandPort },
commandsToOthers
} );
commandsToLocalElevatorReceiver.reset( new QueueReceiver< Command >{
Address{ IPv4Address::any, commandPort },
commandsToLocalElevator,
[id]( const Command &comm ) { return comm.targetElevatorId == id; }
} );
stateChangesInReceiver.reset( new QueueReceiver< StateChange >{
Address{ IPv4Address::any, stateChangePort },
stateChangesIn,
[id]( const StateChange &chan ) { return chan.state.id != id; }
} );
stateChangesOutSender.reset( new QueueSender< StateChange >{
commSend,
Address{ IPv4Address::broadcast, stateChangePort },
stateChangesOut
} );
}
/* about heartbeat lengths:
* - elevator loop is polling and never sleeping, therefore its scheduling
* is quite relieable and it can have short heartbeat,
* furthermore we need to make sure we will detect any floor change,
* therefore heartbeat it must respond faster then is time to cross sensor
* (approx 400ms), also note that even with heartbeat of 10ms the elevator
* seems to be running reliably
* - scheduler again has quite tight demand, as it should be able to handle
* all state changes from elevator, but we have to be more carefull here
* as it is sleeping sometimes
*/
Elevator elevator{ id, heartbeatManager.getNew( 500 /* ms */ ),
commandsToLocalElevator, stateChangesIn };
Scheduler scheduler{ id, heartbeatManager.getNew( 1000 /* ms */ ),
elevator.info(),
stateChangesIn, stateChangesOut, commandsToOthers, commandsToLocalElevator };
if ( nodes > 1 ) {
commandsToLocalElevatorReceiver->run();
stateChangesInReceiver->run();
commandsToOthersReceiver->run();
stateChangesOutSender->run();
}
elevator.run();
scheduler.run();
// wait for 2 seconds so that everything has chance to start
// it something fails to start in this time heartbeat will
// fail and process will be terminated
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
// heartbeat failure will throw an exception which will terminate
// process (as it is not catched)
heartbeatManager.runInThisThread();
}
};
}
int main( int args, const char **argv ) {
elevator::Main m( args, argv );
m.main();
}
<|endoftext|> |
<commit_before>
#include <gloperate/painter/ContextFormat.h>
#include <cassert>
#include <sstream>
#include <map>
#include <globjects/base/baselogging.h>
using namespace globjects;
namespace gloperate
{
ContextFormat::ContextFormat()
: m_version(glbinding::Version(4, 5))
, m_profile(Profile::None)
, m_debugContext(false)
, m_forwardCompatibility(false)
, m_redBufferSize(8)
, m_greenBufferSize(8)
, m_blueBufferSize(8)
, m_alphaBufferSize(8)
, m_depthBufferSize(24)
, m_stencilBufferSize(0)
, m_stereo(false)
, m_swapBehavior(SwapBehavior::DoubleBuffering)
, m_samples(0)
{
}
ContextFormat::~ContextFormat()
{
}
void ContextFormat::setVersion(
const unsigned int majorVersion
, const unsigned int minorVersion)
{
setVersion(glbinding::Version(majorVersion, minorVersion));
}
void ContextFormat::setVersion(const glbinding::Version & version)
{
m_version = version;
}
glbinding::Version ContextFormat::validateVersion(const glbinding::Version &requestedVersion
, const glbinding::Version &_maximumVersion)
{
glbinding::Version maximumVersion = _maximumVersion;
if (maximumVersion.isNull())
{
#ifdef __APPLE__
maximumVersion = glbinding::Version(3, 2);
#else
maximumVersion = glbinding::Version(3, 0);
#endif
}
if (requestedVersion.isNull() || requestedVersion > maximumVersion)
return maximumVersion;
if (!requestedVersion.isValid())
{
glbinding::Version nearest = requestedVersion.nearest();
return nearest > maximumVersion ? maximumVersion : nearest;
}
return requestedVersion;
}
int ContextFormat::majorVersion() const
{
return m_version.m_major;
}
int ContextFormat::minorVersion() const
{
return m_version.m_minor;
}
const glbinding::Version & ContextFormat::version() const
{
return m_version;
}
ContextFormat::Profile ContextFormat::profile() const
{
return m_profile;
}
void ContextFormat::setProfile(const ContextFormat::Profile profile)
{
m_profile = profile;
}
bool ContextFormat::debugContext() const
{
return m_debugContext;
}
void ContextFormat::setDebugContext(const bool on)
{
m_debugContext = on;
}
bool ContextFormat::forwardCompatible() const
{
return m_forwardCompatibility;
}
void ContextFormat::setForwardCompatible(const bool on)
{
m_forwardCompatibility = on;
}
int ContextFormat::redBufferSize() const
{
return m_redBufferSize;
}
void ContextFormat::setRedBufferSize(const int size)
{
m_redBufferSize = size;
}
int ContextFormat::greenBufferSize() const
{
return m_greenBufferSize;
}
void ContextFormat::setGreenBufferSize(const int size)
{
m_greenBufferSize = size;
}
int ContextFormat::blueBufferSize() const
{
return m_blueBufferSize;
}
void ContextFormat::setBlueBufferSize(const int size)
{
m_blueBufferSize = size;
}
int ContextFormat::alphaBufferSize() const
{
return m_alphaBufferSize;
}
void ContextFormat::setAlphaBufferSize(const int size)
{
m_alphaBufferSize = size;
}
int ContextFormat::depthBufferSize() const
{
return m_depthBufferSize;
}
void ContextFormat::setDepthBufferSize(const int size)
{
m_depthBufferSize = size;
}
int ContextFormat::stencilBufferSize() const
{
return m_stencilBufferSize;
}
void ContextFormat::setStencilBufferSize(const int size)
{
m_stencilBufferSize = size;
}
ContextFormat::SwapBehavior ContextFormat::swapBehavior() const
{
return m_swapBehavior;
}
void ContextFormat::setSwapBehavior(const ContextFormat::SwapBehavior behavior)
{
m_swapBehavior = behavior;
}
bool ContextFormat::stereo() const
{
return m_stereo;
}
void ContextFormat::setStereo(const bool enable)
{
m_stereo = enable;
}
int ContextFormat::samples() const
{
return m_samples;
}
void ContextFormat::setSamples(const int samples)
{
m_samples = samples;
}
const std::string & ContextFormat::profileString(const Profile profile)
{
static const std::map<Profile, std::string> profileIdentifier = {
{ Profile::Core, "Core" }
, { Profile::Compatibility, "Compatibility" }
, { Profile::None, "None" } };
return profileIdentifier.at(profile);
}
const std::string & ContextFormat::swapBehaviorString(const SwapBehavior swapBehavior)
{
static const std::map<SwapBehavior, std::string> swapbIdentifier = {
{ SwapBehavior::Default, "Default" }
, { SwapBehavior::DoubleBuffering, "DoubleBuffering" }
, { SwapBehavior::SingleBuffering, "SingleBuffering" }
, { SwapBehavior::TripleBuffering, "TripleBuffering" } };
return swapbIdentifier.at(swapBehavior);
}
bool ContextFormat::verify(const ContextFormat & requested, const ContextFormat & created)
{
return
verifyVersionAndProfile(requested, created) &&
verifyPixelFormat(requested, created);
}
bool ContextFormat::verify(const ContextFormat & requested) const
{
return verify(requested, *this);
}
bool ContextFormat::verifyVersionAndProfile(const ContextFormat & requested, const ContextFormat & created)
{
const bool sameProfiles(requested.profile() == created.profile());
if (!sameProfiles)
{
warning() << "Profile mismatch for the current context: "
<< profileString(requested.profile()) << " requested, "
<< profileString(created.profile()) << " created.";
}
if (requested.version() != created.version())
{
warning() << "Version mismatch for the current context: "
<< requested.version().toString() << " requested, "
<< created.version().toString() << " created.";
if (requested.profile() == Profile::Core)
return false;
}
return sameProfiles;
}
inline void ContextFormat::verifyBufferSize(
const unsigned int sizeRequested
, const unsigned int sizeInitialized
, const std::string & warning
, std::vector<std::string> & issues)
{
if (sizeRequested == sizeInitialized)
return;
std::stringstream ss;
ss << warning << " size mismatch: " << sizeRequested << " requested, " << sizeInitialized << " created.";
issues.push_back(ss.str());
}
bool ContextFormat::verifyPixelFormat(
const ContextFormat & requested
, const ContextFormat & created)
{
std::vector<std::string> issues;
const bool sameSwapBehaviors(requested.swapBehavior() == created.swapBehavior());
if (!sameSwapBehaviors)
{
warning() << "Swap behavior mismatch for the current context: "
<< swapBehaviorString(requested.swapBehavior()) << " requested, "
<< swapBehaviorString(created.swapBehavior()) << " created.";
}
if (requested.depthBufferSize())
{
if (!created.depthBufferSize())
issues.push_back("- Depth Buffer requested, but none created.");
else
verifyBufferSize(requested.depthBufferSize(), created.depthBufferSize()
, "- Depth Buffer", issues);
}
verifyBufferSize(requested.redBufferSize(), created.redBufferSize()
, "- Red Buffer", issues);
verifyBufferSize(requested.greenBufferSize(), created.greenBufferSize()
, "- Green Buffer", issues);
verifyBufferSize(requested.blueBufferSize(), created.blueBufferSize()
, "- Blue Buffer", issues);
verifyBufferSize(requested.alphaBufferSize(), created.alphaBufferSize()
, "- Alpha Buffer", issues);
if (requested.stencilBufferSize())
{
if (!created.stencilBufferSize())
issues.push_back("- Stencil Buffer requested, but none created.");
else
verifyBufferSize(requested.stencilBufferSize(), created.stencilBufferSize()
, "- Stencil Buffer", issues);
}
if (requested.stereo() && !created.stereo())
issues.push_back("- Stereo Buffering requested, but not initialized.");
if (requested.samples())
{
if (!created.samples())
issues.push_back("- Sample Buffers requested, but none initialized.");
else
verifyBufferSize(requested.samples(), created.samples(), "- Samples ", issues);
}
if (issues.empty())
return true;
warning() << "Pixelformat mismatch for the current context:";
for(const std::string & issue : issues)
warning() << issue;
return false;
}
} // namespace gloperate
<commit_msg>fix access to protected glbinding::Version member<commit_after>
#include <gloperate/painter/ContextFormat.h>
#include <cassert>
#include <sstream>
#include <map>
#include <globjects/base/baselogging.h>
using namespace globjects;
namespace gloperate
{
ContextFormat::ContextFormat()
: m_version(glbinding::Version(4, 5))
, m_profile(Profile::None)
, m_debugContext(false)
, m_forwardCompatibility(false)
, m_redBufferSize(8)
, m_greenBufferSize(8)
, m_blueBufferSize(8)
, m_alphaBufferSize(8)
, m_depthBufferSize(24)
, m_stencilBufferSize(0)
, m_stereo(false)
, m_swapBehavior(SwapBehavior::DoubleBuffering)
, m_samples(0)
{
}
ContextFormat::~ContextFormat()
{
}
void ContextFormat::setVersion(
const unsigned int majorVersion
, const unsigned int minorVersion)
{
setVersion(glbinding::Version(majorVersion, minorVersion));
}
void ContextFormat::setVersion(const glbinding::Version & version)
{
m_version = version;
}
glbinding::Version ContextFormat::validateVersion(const glbinding::Version &requestedVersion
, const glbinding::Version &_maximumVersion)
{
glbinding::Version maximumVersion = _maximumVersion;
if (maximumVersion.isNull())
{
#ifdef __APPLE__
maximumVersion = glbinding::Version(3, 2);
#else
maximumVersion = glbinding::Version(3, 0);
#endif
}
if (requestedVersion.isNull() || requestedVersion > maximumVersion)
return maximumVersion;
if (!requestedVersion.isValid())
{
glbinding::Version nearest = requestedVersion.nearest();
return nearest > maximumVersion ? maximumVersion : nearest;
}
return requestedVersion;
}
int ContextFormat::majorVersion() const
{
return m_version.majorVersion();
}
int ContextFormat::minorVersion() const
{
return m_version.minorVersion();
}
const glbinding::Version & ContextFormat::version() const
{
return m_version;
}
ContextFormat::Profile ContextFormat::profile() const
{
return m_profile;
}
void ContextFormat::setProfile(const ContextFormat::Profile profile)
{
m_profile = profile;
}
bool ContextFormat::debugContext() const
{
return m_debugContext;
}
void ContextFormat::setDebugContext(const bool on)
{
m_debugContext = on;
}
bool ContextFormat::forwardCompatible() const
{
return m_forwardCompatibility;
}
void ContextFormat::setForwardCompatible(const bool on)
{
m_forwardCompatibility = on;
}
int ContextFormat::redBufferSize() const
{
return m_redBufferSize;
}
void ContextFormat::setRedBufferSize(const int size)
{
m_redBufferSize = size;
}
int ContextFormat::greenBufferSize() const
{
return m_greenBufferSize;
}
void ContextFormat::setGreenBufferSize(const int size)
{
m_greenBufferSize = size;
}
int ContextFormat::blueBufferSize() const
{
return m_blueBufferSize;
}
void ContextFormat::setBlueBufferSize(const int size)
{
m_blueBufferSize = size;
}
int ContextFormat::alphaBufferSize() const
{
return m_alphaBufferSize;
}
void ContextFormat::setAlphaBufferSize(const int size)
{
m_alphaBufferSize = size;
}
int ContextFormat::depthBufferSize() const
{
return m_depthBufferSize;
}
void ContextFormat::setDepthBufferSize(const int size)
{
m_depthBufferSize = size;
}
int ContextFormat::stencilBufferSize() const
{
return m_stencilBufferSize;
}
void ContextFormat::setStencilBufferSize(const int size)
{
m_stencilBufferSize = size;
}
ContextFormat::SwapBehavior ContextFormat::swapBehavior() const
{
return m_swapBehavior;
}
void ContextFormat::setSwapBehavior(const ContextFormat::SwapBehavior behavior)
{
m_swapBehavior = behavior;
}
bool ContextFormat::stereo() const
{
return m_stereo;
}
void ContextFormat::setStereo(const bool enable)
{
m_stereo = enable;
}
int ContextFormat::samples() const
{
return m_samples;
}
void ContextFormat::setSamples(const int samples)
{
m_samples = samples;
}
const std::string & ContextFormat::profileString(const Profile profile)
{
static const std::map<Profile, std::string> profileIdentifier = {
{ Profile::Core, "Core" }
, { Profile::Compatibility, "Compatibility" }
, { Profile::None, "None" } };
return profileIdentifier.at(profile);
}
const std::string & ContextFormat::swapBehaviorString(const SwapBehavior swapBehavior)
{
static const std::map<SwapBehavior, std::string> swapbIdentifier = {
{ SwapBehavior::Default, "Default" }
, { SwapBehavior::DoubleBuffering, "DoubleBuffering" }
, { SwapBehavior::SingleBuffering, "SingleBuffering" }
, { SwapBehavior::TripleBuffering, "TripleBuffering" } };
return swapbIdentifier.at(swapBehavior);
}
bool ContextFormat::verify(const ContextFormat & requested, const ContextFormat & created)
{
return
verifyVersionAndProfile(requested, created) &&
verifyPixelFormat(requested, created);
}
bool ContextFormat::verify(const ContextFormat & requested) const
{
return verify(requested, *this);
}
bool ContextFormat::verifyVersionAndProfile(const ContextFormat & requested, const ContextFormat & created)
{
const bool sameProfiles(requested.profile() == created.profile());
if (!sameProfiles)
{
warning() << "Profile mismatch for the current context: "
<< profileString(requested.profile()) << " requested, "
<< profileString(created.profile()) << " created.";
}
if (requested.version() != created.version())
{
warning() << "Version mismatch for the current context: "
<< requested.version().toString() << " requested, "
<< created.version().toString() << " created.";
if (requested.profile() == Profile::Core)
return false;
}
return sameProfiles;
}
inline void ContextFormat::verifyBufferSize(
const unsigned int sizeRequested
, const unsigned int sizeInitialized
, const std::string & warning
, std::vector<std::string> & issues)
{
if (sizeRequested == sizeInitialized)
return;
std::stringstream ss;
ss << warning << " size mismatch: " << sizeRequested << " requested, " << sizeInitialized << " created.";
issues.push_back(ss.str());
}
bool ContextFormat::verifyPixelFormat(
const ContextFormat & requested
, const ContextFormat & created)
{
std::vector<std::string> issues;
const bool sameSwapBehaviors(requested.swapBehavior() == created.swapBehavior());
if (!sameSwapBehaviors)
{
warning() << "Swap behavior mismatch for the current context: "
<< swapBehaviorString(requested.swapBehavior()) << " requested, "
<< swapBehaviorString(created.swapBehavior()) << " created.";
}
if (requested.depthBufferSize())
{
if (!created.depthBufferSize())
issues.push_back("- Depth Buffer requested, but none created.");
else
verifyBufferSize(requested.depthBufferSize(), created.depthBufferSize()
, "- Depth Buffer", issues);
}
verifyBufferSize(requested.redBufferSize(), created.redBufferSize()
, "- Red Buffer", issues);
verifyBufferSize(requested.greenBufferSize(), created.greenBufferSize()
, "- Green Buffer", issues);
verifyBufferSize(requested.blueBufferSize(), created.blueBufferSize()
, "- Blue Buffer", issues);
verifyBufferSize(requested.alphaBufferSize(), created.alphaBufferSize()
, "- Alpha Buffer", issues);
if (requested.stencilBufferSize())
{
if (!created.stencilBufferSize())
issues.push_back("- Stencil Buffer requested, but none created.");
else
verifyBufferSize(requested.stencilBufferSize(), created.stencilBufferSize()
, "- Stencil Buffer", issues);
}
if (requested.stereo() && !created.stereo())
issues.push_back("- Stereo Buffering requested, but not initialized.");
if (requested.samples())
{
if (!created.samples())
issues.push_back("- Sample Buffers requested, but none initialized.");
else
verifyBufferSize(requested.samples(), created.samples(), "- Samples ", issues);
}
if (issues.empty())
return true;
warning() << "Pixelformat mismatch for the current context:";
for(const std::string & issue : issues)
warning() << issue;
return false;
}
} // namespace gloperate
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
/*!
* \brief Indicates if an 1D evaluation should run in paralle
* \param n The size of the evaluation
* \param threshold The parallel threshold
* \return true if the evaluation should be done in paralle, false otherwise
*/
inline bool select_parallel(std::size_t n, std::size_t threshold = parallel_threshold) {
return threads > 1 && ((parallel_support && local_context().parallel)|| (is_parallel && n >= threshold && !local_context().serial));
}
/*!
* \brief Indicates if an 2D evaluation should run in paralle
* \param n1 The first dimension of the evaluation
* \param t1 The first parallel threshold
* \param n2 The second dimension of the evaluation
* \param t2 The second parallel threshold
* \return true if the evaluation should be done in paralle, false otherwise
*/
inline bool select_parallel_2d(std::size_t n1, std::size_t t1, std::size_t n2, std::size_t t2) {
return threads > 1 && ((parallel_support && local_context().parallel) || (is_parallel && n1 >= t1 && n2 >= t2 && !local_context().serial));
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param pool The pool to use
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param T The number of threads to use
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(cpp::default_thread_pool<>& pool, bool p, Functor&& functor, size_t T, std::size_t first, std::size_t last) {
if (p) {
const auto n = last - first;
const auto batch = n / T;
for (std::size_t t = 0; t < T - 1; ++t) {
pool.do_task(functor, first + t * batch, first + (t + 1) * batch);
}
functor(first + (T - 1) * batch, last);
pool.wait();
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param pool The pool to use
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(cpp::default_thread_pool<>& pool, bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
dispatch_1d(pool, p, std::forward<Functor>(functor), pool.size() + 1, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
thread_local cpp::default_thread_pool<> pool(threads - 1);
dispatch_1d(pool, p, std::forward<Functor>(functor), threads, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d_any(bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
auto n = last - first;
size_t T = std::min(n, threads);
thread_local cpp::default_thread_pool<> pool(threads - 1);
dispatch_1d(pool, p, std::forward<Functor>(functor), T, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner and use an accumulator functor to accumulate the results
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param acc_functor The functor to accumulate results
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename T, typename Functor, typename AccFunctor>
inline void dispatch_1d_acc(bool p, Functor&& functor, AccFunctor&& acc_functor, std::size_t first, std::size_t last) {
if (p) {
std::vector<T> futures(threads - 1);
thread_local cpp::default_thread_pool<> pool(threads - 1);
auto n = last - first;
auto batch = n / threads;
auto sub_functor = [&futures, &functor](std::size_t t, std::size_t first, std::size_t last) {
futures[t] = functor(first, last);
};
for (std::size_t t = 0; t < threads - 1; ++t) {
pool.do_task(sub_functor, t, first + t * batch, first + (t + 1) * batch);
}
acc_functor(functor(first + (threads - 1) * batch, last));
pool.wait();
for (auto fut : futures) {
acc_functor(fut);
}
} else {
acc_functor(functor(first, last));
}
}
} //end of namespace etl
<commit_msg>New dispatch function<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
/*!
* \brief Indicates if an 1D evaluation should run in paralle
* \param n The size of the evaluation
* \param threshold The parallel threshold
* \return true if the evaluation should be done in paralle, false otherwise
*/
inline bool select_parallel(std::size_t n, std::size_t threshold = parallel_threshold) {
return threads > 1 && ((parallel_support && local_context().parallel)|| (is_parallel && n >= threshold && !local_context().serial));
}
/*!
* \brief Indicates if an 2D evaluation should run in paralle
* \param n1 The first dimension of the evaluation
* \param t1 The first parallel threshold
* \param n2 The second dimension of the evaluation
* \param t2 The second parallel threshold
* \return true if the evaluation should be done in paralle, false otherwise
*/
inline bool select_parallel_2d(std::size_t n1, std::size_t t1, std::size_t n2, std::size_t t2) {
return threads > 1 && ((parallel_support && local_context().parallel) || (is_parallel && n1 >= t1 && n2 >= t2 && !local_context().serial));
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param pool The pool to use
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param T The number of threads to use
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(cpp::default_thread_pool<>& pool, bool p, Functor&& functor, size_t T, std::size_t first, std::size_t last) {
if (p) {
const auto n = last - first;
const auto batch = n / T;
for (std::size_t t = 0; t < T - 1; ++t) {
pool.do_task(functor, first + t * batch, first + (t + 1) * batch);
}
functor(first + (T - 1) * batch, last);
pool.wait();
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param pool The pool to use
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(cpp::default_thread_pool<>& pool, bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
dispatch_1d(pool, p, std::forward<Functor>(functor), pool.size() + 1, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d(bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
thread_local cpp::default_thread_pool<> pool(threads - 1);
dispatch_1d(pool, p, std::forward<Functor>(functor), threads, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename Functor>
inline void dispatch_1d_any(bool p, Functor&& functor, std::size_t first, std::size_t last) {
if (p) {
auto n = last - first;
size_t T = std::min(n, threads);
thread_local cpp::default_thread_pool<> pool(threads - 1);
dispatch_1d(pool, p, std::forward<Functor>(functor), T, first, last);
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner.
*
* The dispatching will be done in batch. That is to say that the
* functor will be called with a range of data.
*
* This will only be dispatched in parallel if etl is running in
* parallel mode and if the range is bigger than the treshold.
*
* \param functor The functor to execute
* \param first The beginning of the range
* \param last The end of the range. Must be bigger or equal to first.
* \param threshold The threshold for parallelization
*/
template <typename Functor>
inline void smart_dispatch_1d_any(Functor&& functor, size_t first, size_t last, size_t threshold) {
if (etl::is_parallel) {
auto n = last - first;
if (select_parallel(n, threshold)) {
size_t T = std::min(n, threads);
thread_local cpp::default_thread_pool<> pool(threads - 1);
dispatch_1d(pool, true, std::forward<Functor>(functor), T, first, last);
} else {
functor(first, last);
}
} else {
functor(first, last);
}
}
/*!
* \brief Dispatch the elements of a range to a functor in a parallel manner and use an accumulator functor to accumulate the results
* \param p Boolean tag to indicate if parallel dispatching must be done
* \param functor The functor to execute
* \param acc_functor The functor to accumulate results
* \param first The beginning of the range
* \param last The end of the range
*/
template <typename T, typename Functor, typename AccFunctor>
inline void dispatch_1d_acc(bool p, Functor&& functor, AccFunctor&& acc_functor, std::size_t first, std::size_t last) {
if (p) {
std::vector<T> futures(threads - 1);
thread_local cpp::default_thread_pool<> pool(threads - 1);
auto n = last - first;
auto batch = n / threads;
auto sub_functor = [&futures, &functor](std::size_t t, std::size_t first, std::size_t last) {
futures[t] = functor(first, last);
};
for (std::size_t t = 0; t < threads - 1; ++t) {
pool.do_task(sub_functor, t, first + t * batch, first + (t + 1) * batch);
}
acc_functor(functor(first + (threads - 1) * batch, last));
pool.wait();
for (auto fut : futures) {
acc_functor(fut);
}
} else {
acc_functor(functor(first, last));
}
}
} //end of namespace etl
<|endoftext|> |
<commit_before>
#include "ApplicationContext.hpp"
#include <boost/algorithm/string.hpp>
#include <cstdio>
#include "Werk/Config/ReloadConfigCommand.hpp"
#include "Werk/OS/Signals.hpp"
#include "Werk/Profiling/WriteProfilesAction.hpp"
#include "QuitCommand.hpp"
namespace werk
{
ApplicationContext::ApplicationContext(const std::string &configPath)
{
//And let's pull ourselves up by our bootstraps...
/********** Pre-Initialization **********/
//Setup handlers for certain signals
setupSegfaultHandler();
/********** Stdout Log **********/
_stdoutLog = new AsyncLog("StdoutLog", &_backgroundThread.backgroundClock());
_logManager.add(_stdoutLog);
_backgroundThread.addTask(_stdoutLog);
/********** Config **********/
_config = new Config("Config", _stdoutLog);
//Synchronously execute the reload since the values are needed for the next step
_config->addConfigSource(new IniConfigSource(configPath));
_config->reloadConfig();
_config->execute();
//Register other config files
const char *configPathsStr = _config->getString("Application.ConfigPaths");
if (nullptr != configPathsStr) {
//Add all the new configs
std::vector<std::string> configPaths;
boost::split(configPaths, configPathsStr, boost::is_any_of(","));
for (auto &path : configPaths) {
_config->addConfigSource(new IniConfigSource(path));
}
}
//Synchronously reload with everything
_config->addConfigSource(new IniConfigSource(configPath));
_config->reloadConfig();
_config->execute();
//Finally, with all files loaded, start reloading in the background
_backgroundThread.addTask(_config);
_stdoutLog->logRaw(LogLevel::SUCCESS, "<Config> Initialized.");
/********** Main Log **********/
const char *logPath = _config->getString("Application.LogPath");
FILE *file = nullptr == logPath ? stdout : std::fopen(logPath, "a");
if (nullptr == file) {
_stdoutLog->logRaw(LogLevel::ERROR, "Could not open log file, redirecting to stderr.\n");
file = stderr;
}
_log = new AsyncLog("Log", &_backgroundThread.backgroundClock(), file);
_logManager.add(_log);
_backgroundThread.addTask(_log);
_config->setLog(_log);
_log->logRaw(LogLevel::SUCCESS, "<Log> Initialized.");
/********** Command Manager **********/
_commandManager = new CommandManager(_log);
_commandManager->add("reload", new ReloadConfigCommand(*_config));
Command *quitCommand = new QuitCommand(this);
_commandManager->add("quit", quitCommand);
_log->logRaw(LogLevel::SUCCESS, "<CommandManager> Initialized.");
const char *profilesPath = _config->getString("Application.ProfilesPath");
if (nullptr != profilesPath) {
_log->log(LogLevel::INFO, "Writing profiles to %s on shutdown.", profilesPath);
_shutdownActions.push_back(new WriteProfilesAction("WriteProfiles", _log, _profileManager, profilesPath));
}
/********** Finish Initialization **********/
//Setup remaining signals
//SIGHUP -> reload config
setupSignalHandler(SIGHUP, _config->getReloadConfigAction());
//Load and run startup commands
//TODO: consider defering this until later, once the user has setup everything they need?
const char *startupCommandsStr = _config->getString("Application.StartupCommands");
if (nullptr != startupCommandsStr) {
//Split and run each command
boost::split(_startupCommands, startupCommandsStr, boost::is_any_of(";"));
for (auto &command : _startupCommands) {
_commandManager->execute(command);
}
}
_log->logRaw(LogLevel::SUCCESS, "<ApplicationContext> Initialized.");
}
ApplicationContext::~ApplicationContext()
{
//Shut down, if not already done
if (!isShutdown()) {
shutdown();
}
}
bool ApplicationContext::isShutdown()
{
return _backgroundThread.stopped();
}
void ApplicationContext::shutdown()
{
//Don't shut down twice
if (isShutdown()) {
fprintf(stderr, "ApplicationContext::shutdown - Already shut down.\n");
return;
}
//Load and run shutdown commands
const char *shutdownCommandsStr = _config->getString("Application.ShutdownCommands");
if (nullptr != shutdownCommandsStr) {
//Split on ; and run each command
boost::split(_shutdownCommands, shutdownCommandsStr, boost::is_any_of(";"));
for (auto &command : _startupCommands) {
_commandManager->execute(command);
}
}
//Run shutdown actions
_log->logRaw(LogLevel::INFO, "Running shutdown actions...");
for (Action *action : _shutdownActions) {
action->execute();
}
_log->logRaw(LogLevel::SUCCESS, "Shutdown actions complete.");
_log->logRaw(LogLevel::INFO, "Shutting down...");
_backgroundThread.stop();
}
}
<commit_msg>Add missing header<commit_after>
#include "ApplicationContext.hpp"
#include <boost/algorithm/string.hpp>
#include <cstdio>
#include <signal.h>
#include "Werk/Config/ReloadConfigCommand.hpp"
#include "Werk/OS/Signals.hpp"
#include "Werk/Profiling/WriteProfilesAction.hpp"
#include "QuitCommand.hpp"
namespace werk
{
ApplicationContext::ApplicationContext(const std::string &configPath)
{
//And let's pull ourselves up by our bootstraps...
/********** Pre-Initialization **********/
//Setup handlers for certain signals
setupSegfaultHandler();
/********** Stdout Log **********/
_stdoutLog = new AsyncLog("StdoutLog", &_backgroundThread.backgroundClock());
_logManager.add(_stdoutLog);
_backgroundThread.addTask(_stdoutLog);
/********** Config **********/
_config = new Config("Config", _stdoutLog);
//Synchronously execute the reload since the values are needed for the next step
_config->addConfigSource(new IniConfigSource(configPath));
_config->reloadConfig();
_config->execute();
//Register other config files
const char *configPathsStr = _config->getString("Application.ConfigPaths");
if (nullptr != configPathsStr) {
//Add all the new configs
std::vector<std::string> configPaths;
boost::split(configPaths, configPathsStr, boost::is_any_of(","));
for (auto &path : configPaths) {
_config->addConfigSource(new IniConfigSource(path));
}
}
//Synchronously reload with everything
_config->addConfigSource(new IniConfigSource(configPath));
_config->reloadConfig();
_config->execute();
//Finally, with all files loaded, start reloading in the background
_backgroundThread.addTask(_config);
_stdoutLog->logRaw(LogLevel::SUCCESS, "<Config> Initialized.");
/********** Main Log **********/
const char *logPath = _config->getString("Application.LogPath");
FILE *file = nullptr == logPath ? stdout : std::fopen(logPath, "a");
if (nullptr == file) {
_stdoutLog->logRaw(LogLevel::ERROR, "Could not open log file, redirecting to stderr.\n");
file = stderr;
}
_log = new AsyncLog("Log", &_backgroundThread.backgroundClock(), file);
_logManager.add(_log);
_backgroundThread.addTask(_log);
_config->setLog(_log);
_log->logRaw(LogLevel::SUCCESS, "<Log> Initialized.");
/********** Command Manager **********/
_commandManager = new CommandManager(_log);
_commandManager->add("reload", new ReloadConfigCommand(*_config));
Command *quitCommand = new QuitCommand(this);
_commandManager->add("quit", quitCommand);
_log->logRaw(LogLevel::SUCCESS, "<CommandManager> Initialized.");
const char *profilesPath = _config->getString("Application.ProfilesPath");
if (nullptr != profilesPath) {
_log->log(LogLevel::INFO, "Writing profiles to %s on shutdown.", profilesPath);
_shutdownActions.push_back(new WriteProfilesAction("WriteProfiles", _log, _profileManager, profilesPath));
}
/********** Finish Initialization **********/
//Setup remaining signals
//SIGHUP -> reload config
setupSignalHandler(SIGHUP, _config->getReloadConfigAction());
//Load and run startup commands
//TODO: consider defering this until later, once the user has setup everything they need?
const char *startupCommandsStr = _config->getString("Application.StartupCommands");
if (nullptr != startupCommandsStr) {
//Split and run each command
boost::split(_startupCommands, startupCommandsStr, boost::is_any_of(";"));
for (auto &command : _startupCommands) {
_commandManager->execute(command);
}
}
_log->logRaw(LogLevel::SUCCESS, "<ApplicationContext> Initialized.");
}
ApplicationContext::~ApplicationContext()
{
//Shut down, if not already done
if (!isShutdown()) {
shutdown();
}
}
bool ApplicationContext::isShutdown()
{
return _backgroundThread.stopped();
}
void ApplicationContext::shutdown()
{
//Don't shut down twice
if (isShutdown()) {
fprintf(stderr, "ApplicationContext::shutdown - Already shut down.\n");
return;
}
//Load and run shutdown commands
const char *shutdownCommandsStr = _config->getString("Application.ShutdownCommands");
if (nullptr != shutdownCommandsStr) {
//Split on ; and run each command
boost::split(_shutdownCommands, shutdownCommandsStr, boost::is_any_of(";"));
for (auto &command : _startupCommands) {
_commandManager->execute(command);
}
}
//Run shutdown actions
_log->logRaw(LogLevel::INFO, "Running shutdown actions...");
for (Action *action : _shutdownActions) {
action->execute();
}
_log->logRaw(LogLevel::SUCCESS, "Shutdown actions complete.");
_log->logRaw(LogLevel::INFO, "Shutting down...");
_backgroundThread.stop();
}
}
<|endoftext|> |
<commit_before>#include "data/shortlist.h"
#include "microsoft/shortlist/utils/ParameterTree.h"
#include "marian.h"
#if BLAS_FOUND
#include "3rd_party/faiss/IndexLSH.h"
#endif
namespace marian {
namespace data {
// cast current void pointer to T pointer and move forward by num elements
template <typename T>
const T* get(const void*& current, size_t num = 1) {
const T* ptr = (const T*)current;
current = (const T*)current + num;
return ptr;
}
//////////////////////////////////////////////////////////////////////////////////////
Shortlist::Shortlist(const std::vector<WordIndex>& indices)
: indices_(indices)
, done_(false) {}
Shortlist::~Shortlist() {}
WordIndex Shortlist::reverseMap(int , int , int idx) const { return indices_[idx]; }
WordIndex Shortlist::tryForwardMap(int , int , WordIndex wIdx) const {
auto first = std::lower_bound(indices_.begin(), indices_.end(), wIdx);
if(first != indices_.end() && *first == wIdx) // check if element not less than wIdx has been found and if equal to wIdx
return (int)std::distance(indices_.begin(), first); // return coordinate if found
else
return npos; // return npos if not found, @TODO: replace with std::optional once we switch to C++17?
}
void Shortlist::filter(Expr input, Expr weights, bool isLegacyUntransposedW, Expr b, Expr lemmaEt) {
if (done_) {
return;
}
auto forward = [this](Expr out, const std::vector<Expr>& ) {
out->val()->set(indices_);
};
int k = (int) indices_.size();
Shape kShape({k});
indicesExpr_ = lambda({input, weights}, kShape, Type::uint32, forward);
//std::cerr << "indicesExpr_=" << indicesExpr_->shape() << std::endl;
createCachedTensors(weights, isLegacyUntransposedW, b, lemmaEt, k);
done_ = true;
}
Expr Shortlist::getIndicesExpr() const {
int k = indicesExpr_->shape()[0];
Expr out = reshape(indicesExpr_, {1, 1, k});
return out;
}
void Shortlist::createCachedTensors(Expr weights,
bool isLegacyUntransposedW,
Expr b,
Expr lemmaEt,
int k) {
ABORT_IF(isLegacyUntransposedW, "Legacy untranspose W not yet tested");
cachedShortWt_ = index_select(weights, isLegacyUntransposedW ? -1 : 0, indicesExpr_);
cachedShortWt_ = reshape(cachedShortWt_, {1, 1, cachedShortWt_->shape()[0], cachedShortWt_->shape()[1]});
if (b) {
ABORT("Bias not yet tested");
cachedShortb_ = index_select(b, -1, indicesExpr_);
cachedShortb_ = reshape(cachedShortb_, {1, k, 1, cachedShortb_->shape()[1]}); // not tested
}
cachedShortLemmaEt_ = index_select(lemmaEt, -1, indicesExpr_);
cachedShortLemmaEt_ = reshape(cachedShortLemmaEt_, {1, 1, cachedShortLemmaEt_->shape()[0], k});
}
///////////////////////////////////////////////////////////////////////////////////
Ptr<faiss::IndexLSH> LSHShortlist::index_;
LSHShortlist::LSHShortlist(int k, int nbits)
: Shortlist(std::vector<WordIndex>())
, k_(k), nbits_(nbits) {
//std::cerr << "LSHShortlist" << std::endl;
/*
for (int i = 0; i < k_; ++i) {
indices_.push_back(i);
}
*/
}
//#define BLAS_FOUND 1
WordIndex LSHShortlist::reverseMap(int beamIdx, int batchIdx, int idx) const {
//int currBeamSize = indicesExpr_->shape()[0];
int currBatchSize = indicesExpr_->shape()[1];
idx = (k_ * currBatchSize * beamIdx) + (k_ * batchIdx) + idx;
assert(idx < indices_.size());
return indices_[idx];
}
WordIndex LSHShortlist::tryForwardMap(int , int , WordIndex wIdx) const {
auto first = std::lower_bound(indices_.begin(), indices_.end(), wIdx);
bool found = first != indices_.end();
if(found && *first == wIdx) // check if element not less than wIdx has been found and if equal to wIdx
return (int)std::distance(indices_.begin(), first); // return coordinate if found
else
return npos; // return npos if not found, @TODO: replace with std::optional once we switch to C++17?
}
Expr LSHShortlist::getIndicesExpr() const {
return indicesExpr_;
}
#define BLAS_FOUND 1
void LSHShortlist::filter(Expr input, Expr weights, bool isLegacyUntransposedW, Expr b, Expr lemmaEt) {
#if BLAS_FOUND
ABORT_IF(input->graph()->getDeviceId().type == DeviceType::gpu,
"LSH index (--output-approx-knn) currently not implemented for GPU");
int currBeamSize = input->shape()[0];
int batchSize = input->shape()[2];
int numHypos = currBeamSize * batchSize;
auto forward = [this, numHypos](Expr out, const std::vector<Expr>& inputs) {
auto query = inputs[0];
auto values = inputs[1];
int dim = values->shape()[-1];
if(!index_) {
//std::cerr << "build lsh index" << std::endl;
LOG(info, "Building LSH index for vector dim {} and with hash size {} bits", dim, nbits_);
index_.reset(new faiss::IndexLSH(dim, nbits_,
/*rotate=*/dim != nbits_,
/*train_thesholds*/false));
int vRows = 32121; //47960; //values->shape().elements() / dim;
index_->train(vRows, values->val()->data<float>());
index_->add( vRows, values->val()->data<float>());
}
int qRows = query->shape().elements() / dim;
std::vector<float> distances(qRows * k_);
std::vector<faiss::Index::idx_t> ids(qRows * k_);
index_->search(qRows, query->val()->data<float>(), k_,
distances.data(), ids.data());
indices_.clear();
for(auto iter = ids.begin(); iter != ids.end(); ++iter) {
faiss::Index::idx_t id = *iter;
indices_.push_back((WordIndex)id);
}
for (size_t hypoIdx = 0; hypoIdx < numHypos; ++hypoIdx) {
size_t startIdx = k_ * hypoIdx;
size_t endIdx = startIdx + k_;
std::sort(indices_.begin() + startIdx, indices_.begin() + endIdx);
}
out->val()->set(indices_);
};
Shape kShape({currBeamSize, batchSize, k_});
indicesExpr_ = lambda({input, weights}, kShape, Type::uint32, forward);
createCachedTensors(weights, isLegacyUntransposedW, b, lemmaEt, k_);
#else
input; weights; isLegacyUntransposedW; b; lemmaEt;
ABORT("LSH output layer requires a CPU BLAS library");
#endif
}
void LSHShortlist::createCachedTensors(Expr weights,
bool isLegacyUntransposedW,
Expr b,
Expr lemmaEt,
int k) {
int currBeamSize = indicesExpr_->shape()[0];
int batchSize = indicesExpr_->shape()[1];
ABORT_IF(isLegacyUntransposedW, "Legacy untranspose W not yet tested");
Expr indicesExprFlatten = reshape(indicesExpr_, {indicesExpr_->shape().elements()});
cachedShortWt_ = index_select(weights, isLegacyUntransposedW ? -1 : 0, indicesExprFlatten);
cachedShortWt_ = reshape(cachedShortWt_, {currBeamSize, batchSize, k, cachedShortWt_->shape()[1]});
if (b) {
ABORT("Bias not yet tested");
cachedShortb_ = index_select(b, -1, indicesExprFlatten);
cachedShortb_ = reshape(cachedShortb_, {currBeamSize, k, batchSize, cachedShortb_->shape()[1]}); // not tested
}
int dim = lemmaEt->shape()[0];
cachedShortLemmaEt_ = index_select(lemmaEt, -1, indicesExprFlatten);
cachedShortLemmaEt_ = reshape(cachedShortLemmaEt_, {dim, currBeamSize, batchSize, k});
cachedShortLemmaEt_ = transpose(cachedShortLemmaEt_, {1, 2, 0, 3});
}
LSHShortlistGenerator::LSHShortlistGenerator(int k, int nbits)
: k_(k), nbits_(nbits) {
//std::cerr << "LSHShortlistGenerator" << std::endl;
}
Ptr<Shortlist> LSHShortlistGenerator::generate(Ptr<data::CorpusBatch> batch) const {
return New<LSHShortlist>(k_, nbits_);
}
//////////////////////////////////////////////////////////////////////////////////////
QuicksandShortlistGenerator::QuicksandShortlistGenerator(Ptr<Options> options,
Ptr<const Vocab> srcVocab,
Ptr<const Vocab> trgVocab,
size_t srcIdx,
size_t /*trgIdx*/,
bool /*shared*/)
: options_(options),
srcVocab_(srcVocab),
trgVocab_(trgVocab),
srcIdx_(srcIdx) {
std::vector<std::string> vals = options_->get<std::vector<std::string>>("shortlist");
ABORT_IF(vals.empty(), "No path to filter path given");
std::string fname = vals[0];
auto firstNum = vals.size() > 1 ? std::stoi(vals[1]) : 0;
auto bestNum = vals.size() > 2 ? std::stoi(vals[2]) : 0;
float threshold = vals.size() > 3 ? std::stof(vals[3]) : 0;
if(firstNum != 0 || bestNum != 0 || threshold != 0) {
LOG(warn, "You have provided additional parameters for the Quicksand shortlist, but they are ignored.");
}
mmap_ = mio::mmap_source(fname); // memory-map the binary file once
const void* current = mmap_.data(); // pointer iterator over binary file
// compare magic number in binary file to make sure we are reading the right thing
const int32_t MAGIC_NUMBER = 1234567890;
int32_t header_magic_number = *get<int32_t>(current);
ABORT_IF(header_magic_number != MAGIC_NUMBER, "Trying to mmap Quicksand shortlist but encountered wrong magic number");
auto config = ::quicksand::ParameterTree::FromBinaryReader(current);
use16bit_ = config->GetBoolReq("use_16_bit");
LOG(info, "[data] Mapping Quicksand shortlist from {}", fname);
idSize_ = sizeof(int32_t);
if (use16bit_) {
idSize_ = sizeof(uint16_t);
}
// mmap the binary shortlist pieces
numDefaultIds_ = *get<int32_t>(current);
defaultIds_ = get<int32_t>(current, numDefaultIds_);
numSourceIds_ = *get<int32_t>(current);
sourceLengths_ = get<int32_t>(current, numSourceIds_);
sourceOffsets_ = get<int32_t>(current, numSourceIds_);
numShortlistIds_ = *get<int32_t>(current);
sourceToShortlistIds_ = get<uint8_t>(current, idSize_ * numShortlistIds_);
// display parameters
LOG(info,
"[data] Quicksand shortlist has {} source ids, {} default ids and {} shortlist ids",
numSourceIds_,
numDefaultIds_,
numShortlistIds_);
}
Ptr<Shortlist> QuicksandShortlistGenerator::generate(Ptr<data::CorpusBatch> batch) const {
auto srcBatch = (*batch)[srcIdx_];
auto maxShortlistSize = trgVocab_->size();
std::unordered_set<int32_t> indexSet;
for(int32_t i = 0; i < numDefaultIds_ && i < maxShortlistSize; ++i) {
int32_t id = defaultIds_[i];
indexSet.insert(id);
}
// State
std::vector<std::pair<const uint8_t*, int32_t>> curShortlists(maxShortlistSize);
auto curShortlistIt = curShortlists.begin();
// Because we might fill up our shortlist before reaching max_shortlist_size, we fill the shortlist in order of rank.
// E.g., first rank of word 0, first rank of word 1, ... second rank of word 0, ...
int32_t maxLength = 0;
for (Word word : srcBatch->data()) {
int32_t sourceId = (int32_t)word.toWordIndex();
srcVocab_->transcodeToShortlistInPlace((WordIndex*)&sourceId, 1);
if (sourceId < numSourceIds_) { // if it's a valid source id
const uint8_t* curShortlistIds = sourceToShortlistIds_ + idSize_ * sourceOffsets_[sourceId]; // start position for mapping
int32_t length = sourceLengths_[sourceId]; // how many mappings are there
curShortlistIt->first = curShortlistIds;
curShortlistIt->second = length;
curShortlistIt++;
if (length > maxLength)
maxLength = length;
}
}
// collect the actual shortlist mappings
for (int32_t i = 0; i < maxLength && indexSet.size() < maxShortlistSize; i++) {
for (int32_t j = 0; j < curShortlists.size() && indexSet.size() < maxShortlistSize; j++) {
int32_t length = curShortlists[j].second;
if (i < length) {
const uint8_t* source_shortlist_ids_bytes = curShortlists[j].first;
int32_t id = 0;
if (use16bit_) {
const uint16_t* source_shortlist_ids = reinterpret_cast<const uint16_t*>(source_shortlist_ids_bytes);
id = (int32_t)source_shortlist_ids[i];
}
else {
const int32_t* source_shortlist_ids = reinterpret_cast<const int32_t*>(source_shortlist_ids_bytes);
id = source_shortlist_ids[i];
}
indexSet.insert(id);
}
}
}
// turn into vector and sort (selected indices)
std::vector<WordIndex> indices;
indices.reserve(indexSet.size());
for(auto i : indexSet)
indices.push_back((WordIndex)i);
std::sort(indices.begin(), indices.end());
return New<Shortlist>(indices);
}
Ptr<ShortlistGenerator> createShortlistGenerator(Ptr<Options> options,
Ptr<const Vocab> srcVocab,
Ptr<const Vocab> trgVocab,
const std::vector<int> &lshOpts,
size_t srcIdx,
size_t trgIdx,
bool shared) {
if (lshOpts.size() == 2) {
return New<LSHShortlistGenerator>(lshOpts[0], lshOpts[1]);
}
else {
std::vector<std::string> vals = options->get<std::vector<std::string>>("shortlist");
ABORT_IF(vals.empty(), "No path to shortlist given");
std::string fname = vals[0];
if(filesystem::Path(fname).extension().string() == ".bin") {
return New<QuicksandShortlistGenerator>(options, srcVocab, trgVocab, srcIdx, trgIdx, shared);
} else {
return New<LexicalShortlistGenerator>(options, srcVocab, trgVocab, srcIdx, trgIdx, shared);
}
}
}
} // namespace data
} // namespace marian
<commit_msg>don't define BLAS_FOUND<commit_after>#include "data/shortlist.h"
#include "microsoft/shortlist/utils/ParameterTree.h"
#include "marian.h"
#if BLAS_FOUND
#include "3rd_party/faiss/IndexLSH.h"
#endif
namespace marian {
namespace data {
// cast current void pointer to T pointer and move forward by num elements
template <typename T>
const T* get(const void*& current, size_t num = 1) {
const T* ptr = (const T*)current;
current = (const T*)current + num;
return ptr;
}
//////////////////////////////////////////////////////////////////////////////////////
Shortlist::Shortlist(const std::vector<WordIndex>& indices)
: indices_(indices)
, done_(false) {}
Shortlist::~Shortlist() {}
WordIndex Shortlist::reverseMap(int , int , int idx) const { return indices_[idx]; }
WordIndex Shortlist::tryForwardMap(int , int , WordIndex wIdx) const {
auto first = std::lower_bound(indices_.begin(), indices_.end(), wIdx);
if(first != indices_.end() && *first == wIdx) // check if element not less than wIdx has been found and if equal to wIdx
return (int)std::distance(indices_.begin(), first); // return coordinate if found
else
return npos; // return npos if not found, @TODO: replace with std::optional once we switch to C++17?
}
void Shortlist::filter(Expr input, Expr weights, bool isLegacyUntransposedW, Expr b, Expr lemmaEt) {
if (done_) {
return;
}
auto forward = [this](Expr out, const std::vector<Expr>& ) {
out->val()->set(indices_);
};
int k = (int) indices_.size();
Shape kShape({k});
indicesExpr_ = lambda({input, weights}, kShape, Type::uint32, forward);
//std::cerr << "indicesExpr_=" << indicesExpr_->shape() << std::endl;
createCachedTensors(weights, isLegacyUntransposedW, b, lemmaEt, k);
done_ = true;
}
Expr Shortlist::getIndicesExpr() const {
int k = indicesExpr_->shape()[0];
Expr out = reshape(indicesExpr_, {1, 1, k});
return out;
}
void Shortlist::createCachedTensors(Expr weights,
bool isLegacyUntransposedW,
Expr b,
Expr lemmaEt,
int k) {
ABORT_IF(isLegacyUntransposedW, "Legacy untranspose W not yet tested");
cachedShortWt_ = index_select(weights, isLegacyUntransposedW ? -1 : 0, indicesExpr_);
cachedShortWt_ = reshape(cachedShortWt_, {1, 1, cachedShortWt_->shape()[0], cachedShortWt_->shape()[1]});
if (b) {
ABORT("Bias not yet tested");
cachedShortb_ = index_select(b, -1, indicesExpr_);
cachedShortb_ = reshape(cachedShortb_, {1, k, 1, cachedShortb_->shape()[1]}); // not tested
}
cachedShortLemmaEt_ = index_select(lemmaEt, -1, indicesExpr_);
cachedShortLemmaEt_ = reshape(cachedShortLemmaEt_, {1, 1, cachedShortLemmaEt_->shape()[0], k});
}
///////////////////////////////////////////////////////////////////////////////////
Ptr<faiss::IndexLSH> LSHShortlist::index_;
LSHShortlist::LSHShortlist(int k, int nbits)
: Shortlist(std::vector<WordIndex>())
, k_(k), nbits_(nbits) {
//std::cerr << "LSHShortlist" << std::endl;
/*
for (int i = 0; i < k_; ++i) {
indices_.push_back(i);
}
*/
}
//#define BLAS_FOUND 1
WordIndex LSHShortlist::reverseMap(int beamIdx, int batchIdx, int idx) const {
//int currBeamSize = indicesExpr_->shape()[0];
int currBatchSize = indicesExpr_->shape()[1];
idx = (k_ * currBatchSize * beamIdx) + (k_ * batchIdx) + idx;
assert(idx < indices_.size());
return indices_[idx];
}
WordIndex LSHShortlist::tryForwardMap(int , int , WordIndex wIdx) const {
auto first = std::lower_bound(indices_.begin(), indices_.end(), wIdx);
bool found = first != indices_.end();
if(found && *first == wIdx) // check if element not less than wIdx has been found and if equal to wIdx
return (int)std::distance(indices_.begin(), first); // return coordinate if found
else
return npos; // return npos if not found, @TODO: replace with std::optional once we switch to C++17?
}
Expr LSHShortlist::getIndicesExpr() const {
return indicesExpr_;
}
void LSHShortlist::filter(Expr input, Expr weights, bool isLegacyUntransposedW, Expr b, Expr lemmaEt) {
#if BLAS_FOUND
ABORT_IF(input->graph()->getDeviceId().type == DeviceType::gpu,
"LSH index (--output-approx-knn) currently not implemented for GPU");
int currBeamSize = input->shape()[0];
int batchSize = input->shape()[2];
int numHypos = currBeamSize * batchSize;
auto forward = [this, numHypos](Expr out, const std::vector<Expr>& inputs) {
auto query = inputs[0];
auto values = inputs[1];
int dim = values->shape()[-1];
if(!index_) {
//std::cerr << "build lsh index" << std::endl;
LOG(info, "Building LSH index for vector dim {} and with hash size {} bits", dim, nbits_);
index_.reset(new faiss::IndexLSH(dim, nbits_,
/*rotate=*/dim != nbits_,
/*train_thesholds*/false));
int vRows = 32121; //47960; //values->shape().elements() / dim;
index_->train(vRows, values->val()->data<float>());
index_->add( vRows, values->val()->data<float>());
}
int qRows = query->shape().elements() / dim;
std::vector<float> distances(qRows * k_);
std::vector<faiss::Index::idx_t> ids(qRows * k_);
index_->search(qRows, query->val()->data<float>(), k_,
distances.data(), ids.data());
indices_.clear();
for(auto iter = ids.begin(); iter != ids.end(); ++iter) {
faiss::Index::idx_t id = *iter;
indices_.push_back((WordIndex)id);
}
for (size_t hypoIdx = 0; hypoIdx < numHypos; ++hypoIdx) {
size_t startIdx = k_ * hypoIdx;
size_t endIdx = startIdx + k_;
std::sort(indices_.begin() + startIdx, indices_.begin() + endIdx);
}
out->val()->set(indices_);
};
Shape kShape({currBeamSize, batchSize, k_});
indicesExpr_ = lambda({input, weights}, kShape, Type::uint32, forward);
createCachedTensors(weights, isLegacyUntransposedW, b, lemmaEt, k_);
#else
input; weights; isLegacyUntransposedW; b; lemmaEt;
ABORT("LSH output layer requires a CPU BLAS library");
#endif
}
void LSHShortlist::createCachedTensors(Expr weights,
bool isLegacyUntransposedW,
Expr b,
Expr lemmaEt,
int k) {
int currBeamSize = indicesExpr_->shape()[0];
int batchSize = indicesExpr_->shape()[1];
ABORT_IF(isLegacyUntransposedW, "Legacy untranspose W not yet tested");
Expr indicesExprFlatten = reshape(indicesExpr_, {indicesExpr_->shape().elements()});
cachedShortWt_ = index_select(weights, isLegacyUntransposedW ? -1 : 0, indicesExprFlatten);
cachedShortWt_ = reshape(cachedShortWt_, {currBeamSize, batchSize, k, cachedShortWt_->shape()[1]});
if (b) {
ABORT("Bias not yet tested");
cachedShortb_ = index_select(b, -1, indicesExprFlatten);
cachedShortb_ = reshape(cachedShortb_, {currBeamSize, k, batchSize, cachedShortb_->shape()[1]}); // not tested
}
int dim = lemmaEt->shape()[0];
cachedShortLemmaEt_ = index_select(lemmaEt, -1, indicesExprFlatten);
cachedShortLemmaEt_ = reshape(cachedShortLemmaEt_, {dim, currBeamSize, batchSize, k});
cachedShortLemmaEt_ = transpose(cachedShortLemmaEt_, {1, 2, 0, 3});
}
LSHShortlistGenerator::LSHShortlistGenerator(int k, int nbits)
: k_(k), nbits_(nbits) {
//std::cerr << "LSHShortlistGenerator" << std::endl;
}
Ptr<Shortlist> LSHShortlistGenerator::generate(Ptr<data::CorpusBatch> batch) const {
return New<LSHShortlist>(k_, nbits_);
}
//////////////////////////////////////////////////////////////////////////////////////
QuicksandShortlistGenerator::QuicksandShortlistGenerator(Ptr<Options> options,
Ptr<const Vocab> srcVocab,
Ptr<const Vocab> trgVocab,
size_t srcIdx,
size_t /*trgIdx*/,
bool /*shared*/)
: options_(options),
srcVocab_(srcVocab),
trgVocab_(trgVocab),
srcIdx_(srcIdx) {
std::vector<std::string> vals = options_->get<std::vector<std::string>>("shortlist");
ABORT_IF(vals.empty(), "No path to filter path given");
std::string fname = vals[0];
auto firstNum = vals.size() > 1 ? std::stoi(vals[1]) : 0;
auto bestNum = vals.size() > 2 ? std::stoi(vals[2]) : 0;
float threshold = vals.size() > 3 ? std::stof(vals[3]) : 0;
if(firstNum != 0 || bestNum != 0 || threshold != 0) {
LOG(warn, "You have provided additional parameters for the Quicksand shortlist, but they are ignored.");
}
mmap_ = mio::mmap_source(fname); // memory-map the binary file once
const void* current = mmap_.data(); // pointer iterator over binary file
// compare magic number in binary file to make sure we are reading the right thing
const int32_t MAGIC_NUMBER = 1234567890;
int32_t header_magic_number = *get<int32_t>(current);
ABORT_IF(header_magic_number != MAGIC_NUMBER, "Trying to mmap Quicksand shortlist but encountered wrong magic number");
auto config = ::quicksand::ParameterTree::FromBinaryReader(current);
use16bit_ = config->GetBoolReq("use_16_bit");
LOG(info, "[data] Mapping Quicksand shortlist from {}", fname);
idSize_ = sizeof(int32_t);
if (use16bit_) {
idSize_ = sizeof(uint16_t);
}
// mmap the binary shortlist pieces
numDefaultIds_ = *get<int32_t>(current);
defaultIds_ = get<int32_t>(current, numDefaultIds_);
numSourceIds_ = *get<int32_t>(current);
sourceLengths_ = get<int32_t>(current, numSourceIds_);
sourceOffsets_ = get<int32_t>(current, numSourceIds_);
numShortlistIds_ = *get<int32_t>(current);
sourceToShortlistIds_ = get<uint8_t>(current, idSize_ * numShortlistIds_);
// display parameters
LOG(info,
"[data] Quicksand shortlist has {} source ids, {} default ids and {} shortlist ids",
numSourceIds_,
numDefaultIds_,
numShortlistIds_);
}
Ptr<Shortlist> QuicksandShortlistGenerator::generate(Ptr<data::CorpusBatch> batch) const {
auto srcBatch = (*batch)[srcIdx_];
auto maxShortlistSize = trgVocab_->size();
std::unordered_set<int32_t> indexSet;
for(int32_t i = 0; i < numDefaultIds_ && i < maxShortlistSize; ++i) {
int32_t id = defaultIds_[i];
indexSet.insert(id);
}
// State
std::vector<std::pair<const uint8_t*, int32_t>> curShortlists(maxShortlistSize);
auto curShortlistIt = curShortlists.begin();
// Because we might fill up our shortlist before reaching max_shortlist_size, we fill the shortlist in order of rank.
// E.g., first rank of word 0, first rank of word 1, ... second rank of word 0, ...
int32_t maxLength = 0;
for (Word word : srcBatch->data()) {
int32_t sourceId = (int32_t)word.toWordIndex();
srcVocab_->transcodeToShortlistInPlace((WordIndex*)&sourceId, 1);
if (sourceId < numSourceIds_) { // if it's a valid source id
const uint8_t* curShortlistIds = sourceToShortlistIds_ + idSize_ * sourceOffsets_[sourceId]; // start position for mapping
int32_t length = sourceLengths_[sourceId]; // how many mappings are there
curShortlistIt->first = curShortlistIds;
curShortlistIt->second = length;
curShortlistIt++;
if (length > maxLength)
maxLength = length;
}
}
// collect the actual shortlist mappings
for (int32_t i = 0; i < maxLength && indexSet.size() < maxShortlistSize; i++) {
for (int32_t j = 0; j < curShortlists.size() && indexSet.size() < maxShortlistSize; j++) {
int32_t length = curShortlists[j].second;
if (i < length) {
const uint8_t* source_shortlist_ids_bytes = curShortlists[j].first;
int32_t id = 0;
if (use16bit_) {
const uint16_t* source_shortlist_ids = reinterpret_cast<const uint16_t*>(source_shortlist_ids_bytes);
id = (int32_t)source_shortlist_ids[i];
}
else {
const int32_t* source_shortlist_ids = reinterpret_cast<const int32_t*>(source_shortlist_ids_bytes);
id = source_shortlist_ids[i];
}
indexSet.insert(id);
}
}
}
// turn into vector and sort (selected indices)
std::vector<WordIndex> indices;
indices.reserve(indexSet.size());
for(auto i : indexSet)
indices.push_back((WordIndex)i);
std::sort(indices.begin(), indices.end());
return New<Shortlist>(indices);
}
Ptr<ShortlistGenerator> createShortlistGenerator(Ptr<Options> options,
Ptr<const Vocab> srcVocab,
Ptr<const Vocab> trgVocab,
const std::vector<int> &lshOpts,
size_t srcIdx,
size_t trgIdx,
bool shared) {
if (lshOpts.size() == 2) {
return New<LSHShortlistGenerator>(lshOpts[0], lshOpts[1]);
}
else {
std::vector<std::string> vals = options->get<std::vector<std::string>>("shortlist");
ABORT_IF(vals.empty(), "No path to shortlist given");
std::string fname = vals[0];
if(filesystem::Path(fname).extension().string() == ".bin") {
return New<QuicksandShortlistGenerator>(options, srcVocab, trgVocab, srcIdx, trgIdx, shared);
} else {
return New<LexicalShortlistGenerator>(options, srcVocab, trgVocab, srcIdx, trgIdx, shared);
}
}
}
} // namespace data
} // namespace marian
<|endoftext|> |
<commit_before>#include "LogServerWorkThread.h"
#include <glog/logging.h>
namespace sf1r
{
LogServerWorkThread::LogServerWorkThread()
: workThread_(&LogServerWorkThread::run, this)
, drumRequestQueue_(LogServerCfg::get()->getRpcRequestQueueSize())
{
}
LogServerWorkThread::~LogServerWorkThread()
{
}
void LogServerWorkThread::stop()
{
workThread_.interrupt();
workThread_.join();
}
void LogServerWorkThread::putUuidRequestData(const UUID2DocidList& uuid2DocidList)
{
DrumRequestData drumReqData;
drumReqData.uuid2DocidList.reset(new UUID2DocidList(uuid2DocidList));
drumRequestQueue_.push(drumReqData);
}
void LogServerWorkThread::putSyncRequestData(const SynchronizeData& syncReqData)
{
DrumRequestData drumReqData;
drumReqData.syncReqData.reset(new SynchronizeData(syncReqData));
drumRequestQueue_.push(drumReqData);
}
void LogServerWorkThread::run()
{
try
{
DrumRequestData drumReqData;
while (true)
{
// process requests
drumRequestQueue_.pop(drumReqData);
process(drumReqData);
// terminate execution if interrupted
boost::this_thread::interruption_point();
}
}
catch (const std::exception& e)
{
// nothing
}
}
void LogServerWorkThread::process(const DrumRequestData& drumReqData)
{
if (drumReqData.uuid2DocidList)
{
process(*drumReqData.uuid2DocidList);
}
if (drumReqData.syncReqData)
{
process(*drumReqData.syncReqData);
}
}
void LogServerWorkThread::process(const UUID2DocidList& uuid2DocidList)
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->uuidDrumMutex());
LogServerStorage::get()->uuidDrum()->Update(uuid2DocidList.uuid_, uuid2DocidList.docidList_);
}
void LogServerWorkThread::process(const SynchronizeData& syncReqData)
{
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->uuidDrumMutex());
LOG(INFO) << "synchronizing drum for uuids (locked)";
LogServerStorage::get()->uuidDrum()->Synchronize();
LOG(INFO) << "finished synchronizing drum for uuids";
}
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->docidDrumMutex());
LOG(INFO) << "synchronizing drum for docids (locked)";
LogServerStorage::get()->docidDrum()->Synchronize();
LOG(INFO) << "finished synchronizing drum for docids";
}
}
}
<commit_msg>release memory for request queue of LogServer<commit_after>#include "LogServerWorkThread.h"
#include <glog/logging.h>
namespace sf1r
{
LogServerWorkThread::LogServerWorkThread()
: workThread_(&LogServerWorkThread::run, this)
, drumRequestQueue_(LogServerCfg::get()->getRpcRequestQueueSize())
{
}
LogServerWorkThread::~LogServerWorkThread()
{
}
void LogServerWorkThread::stop()
{
workThread_.interrupt();
workThread_.join();
}
void LogServerWorkThread::putUuidRequestData(const UUID2DocidList& uuid2DocidList)
{
DrumRequestData drumReqData;
drumReqData.uuid2DocidList.reset(new UUID2DocidList(uuid2DocidList));
drumRequestQueue_.push(drumReqData);
}
void LogServerWorkThread::putSyncRequestData(const SynchronizeData& syncReqData)
{
DrumRequestData drumReqData;
drumReqData.syncReqData.reset(new SynchronizeData(syncReqData));
drumRequestQueue_.push(drumReqData);
}
void LogServerWorkThread::run()
{
try
{
DrumRequestData drumReqData;
while (true)
{
drumRequestQueue_.pop(drumReqData);
process(drumReqData);
if (drumRequestQueue_.empty())
{
drumRequestQueue_.clear();
}
// terminate execution if interrupted
boost::this_thread::interruption_point();
}
}
catch (const std::exception& e)
{
// nothing
}
}
void LogServerWorkThread::process(const DrumRequestData& drumReqData)
{
if (drumReqData.uuid2DocidList)
{
process(*drumReqData.uuid2DocidList);
}
if (drumReqData.syncReqData)
{
process(*drumReqData.syncReqData);
}
}
void LogServerWorkThread::process(const UUID2DocidList& uuid2DocidList)
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->uuidDrumMutex());
LogServerStorage::get()->uuidDrum()->Update(uuid2DocidList.uuid_, uuid2DocidList.docidList_);
}
void LogServerWorkThread::process(const SynchronizeData& syncReqData)
{
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->uuidDrumMutex());
LOG(INFO) << "synchronizing drum for uuids (locked)";
LogServerStorage::get()->uuidDrum()->Synchronize();
LOG(INFO) << "finished synchronizing drum for uuids";
}
{
boost::lock_guard<boost::mutex> lock(LogServerStorage::get()->docidDrumMutex());
LOG(INFO) << "synchronizing drum for docids (locked)";
LogServerStorage::get()->docidDrum()->Synchronize();
LOG(INFO) << "finished synchronizing drum for docids";
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Global Phasing Ltd.
// Writing cif::Document or its parts to std::ostream.
#ifndef GEMMI_TO_CIF_HPP_
#define GEMMI_TO_CIF_HPP_
#include <ostream>
#include "cifdoc.hpp"
namespace gemmi {
namespace cif {
enum class Style {
Simple,
NoBlankLines,
PreferPairs, // write single-row loops as pairs
Pdbx, // PreferPairs + put '#' (empty comments) between categories
Indent35, // start values in pairs from 35th column
Aligned, // columns in tables are left-aligned
};
// CIF files are read in binary mode. It makes difference only for text fields.
// If the text field with \r\n would be written as is in text mode on Windows
// \r would get duplicated. As a workaround, here we convert \r\n to \n.
// Hopefully \r that gets removed here is never meaningful.
inline void write_text_field(std::ostream& os, const std::string& value) {
for (size_t pos = 0, end = 0; end != std::string::npos; pos = end + 1) {
end = value.find("\r\n", pos);
size_t len = (end == std::string::npos ? value.size() : end) - pos;
os.write(value.c_str() + pos, len);
}
}
inline void write_out_pair(std::ostream& os, const std::string& name,
const std::string& value, Style style) {
os << name;
if (is_text_field(value)) {
os.put('\n');
write_text_field(os, value);
} else {
if (name.size() + value.size() > 120)
os.put('\n');
else if ((style == Style::Indent35 || style == Style::Aligned) && name.size() < 34)
os.write(" ", 34 - name.size());
else
os.put(' ');
os << value;
}
os.put('\n');
}
inline void write_out_loop(std::ostream& os, const Loop& loop, Style style) {
constexpr size_t max_padding = 30; // if increased, adjust os.write() below
if (loop.values.empty())
return;
if ((style == Style::PreferPairs || style == Style::Pdbx) &&
loop.length() == 1) {
for (size_t i = 0; i != loop.tags.size(); ++i)
write_out_pair(os, loop.tags[i], loop.values[i], style);
return;
}
// tags
os << "loop_";
for (const std::string& tag : loop.tags)
os << '\n' << tag;
// values
size_t ncol = loop.tags.size();
std::vector<size_t> col_width;
if (style == Style::Aligned) {
col_width.resize(ncol, 1);
size_t col = 0;
for (const std::string& val : loop.values) {
col_width[col] = std::max(col_width[col], val.size());
if (++col == ncol)
col = 0;
}
for (size_t& w : col_width)
w = std::min(w, max_padding);
}
size_t col = 0;
for (const std::string& val : loop.values) {
bool text_field = is_text_field(val);
os.put(col == 0 || text_field ? '\n' : ' ');
if (text_field)
write_text_field(os, val);
else
os << val;
if (col != ncol - 1) {
if (!col_width.empty() && val.size() < col_width[col])
os.write(" ", col_width[col] - val.size());
++col;
} else {
col = 0;
}
}
os.put('\n');
}
inline void write_out_item(std::ostream& os, const Item& item, Style style) {
switch (item.type) {
case ItemType::Pair:
write_out_pair(os, item.pair[0], item.pair[1], style);
break;
case ItemType::Loop:
write_out_loop(os, item.loop, style);
break;
case ItemType::Frame:
os << "save_" << item.frame.name << '\n';
for (const Item& inner_item : item.frame.items)
write_out_item(os, inner_item, style);
os << "save_\n";
break;
case ItemType::Comment:
os << item.pair[1] << '\n';
break;
case ItemType::Erased:
break;
}
}
inline bool should_be_separated_(const Item& a, const Item& b) {
if (a.type == ItemType::Comment || b.type == ItemType::Comment)
return false;
if (a.type != ItemType::Pair || b.type != ItemType::Pair)
return true;
// check if we have mmcif-like tags from different categories
auto adot = a.pair[0].find('.');
if (adot == std::string::npos)
return false;
auto bdot = b.pair[0].find('.');
return adot != bdot || a.pair[0].compare(0, adot, b.pair[0], 0, adot) != 0;
}
inline void write_cif_block_to_stream(std::ostream& os, const Block& block,
Style style=Style::Simple) {
os << "data_" << block.name << '\n';
if (style == Style::Pdbx)
os << "#\n";
const Item* prev = nullptr;
for (const Item& item : block.items)
if (item.type != ItemType::Erased) {
if (prev && style != Style::NoBlankLines &&
should_be_separated_(*prev, item))
os << (style == Style::Pdbx ? "#\n" : "\n");
write_out_item(os, item, style);
prev = &item;
}
if (style == Style::Pdbx)
os << "#\n";
}
inline void write_cif_to_stream(std::ostream& os, const Document& doc,
Style style=Style::Simple) {
bool first = true;
for (const Block& block : doc.blocks) {
if (!first)
os.put('\n'); // extra blank line for readability
write_cif_block_to_stream(os, block, style);
first = false;
}
}
} // namespace cif
} // namespace gemmi
#endif
<commit_msg>to_cif: when calculating alignment ignore text fields<commit_after>// Copyright 2017 Global Phasing Ltd.
// Writing cif::Document or its parts to std::ostream.
#ifndef GEMMI_TO_CIF_HPP_
#define GEMMI_TO_CIF_HPP_
#include <ostream>
#include "cifdoc.hpp"
namespace gemmi {
namespace cif {
enum class Style {
Simple,
NoBlankLines,
PreferPairs, // write single-row loops as pairs
Pdbx, // PreferPairs + put '#' (empty comments) between categories
Indent35, // start values in pairs from 35th column
Aligned, // columns in tables are left-aligned
};
// CIF files are read in binary mode. It makes difference only for text fields.
// If the text field with \r\n would be written as is in text mode on Windows
// \r would get duplicated. As a workaround, here we convert \r\n to \n.
// Hopefully \r that gets removed here is never meaningful.
inline void write_text_field(std::ostream& os, const std::string& value) {
for (size_t pos = 0, end = 0; end != std::string::npos; pos = end + 1) {
end = value.find("\r\n", pos);
size_t len = (end == std::string::npos ? value.size() : end) - pos;
os.write(value.c_str() + pos, len);
}
}
inline void write_out_pair(std::ostream& os, const std::string& name,
const std::string& value, Style style) {
os << name;
if (is_text_field(value)) {
os.put('\n');
write_text_field(os, value);
} else {
if (name.size() + value.size() > 120)
os.put('\n');
else if ((style == Style::Indent35 || style == Style::Aligned) && name.size() < 34)
os.write(" ", 34 - name.size());
else
os.put(' ');
os << value;
}
os.put('\n');
}
inline void write_out_loop(std::ostream& os, const Loop& loop, Style style) {
constexpr size_t max_padding = 30; // if increased, adjust os.write() below
if (loop.values.empty())
return;
if ((style == Style::PreferPairs || style == Style::Pdbx) &&
loop.length() == 1) {
for (size_t i = 0; i != loop.tags.size(); ++i)
write_out_pair(os, loop.tags[i], loop.values[i], style);
return;
}
// tags
os << "loop_";
for (const std::string& tag : loop.tags)
os << '\n' << tag;
// values
size_t ncol = loop.tags.size();
std::vector<size_t> col_width;
if (style == Style::Aligned) {
col_width.resize(ncol, 1);
size_t col = 0;
for (const std::string& val : loop.values) {
if (!is_text_field(val))
col_width[col] = std::max(col_width[col], val.size());
if (++col == ncol)
col = 0;
}
for (size_t& w : col_width)
w = std::min(w, max_padding);
}
size_t col = 0;
for (const std::string& val : loop.values) {
bool text_field = is_text_field(val);
os.put(col == 0 || text_field ? '\n' : ' ');
if (text_field)
write_text_field(os, val);
else
os << val;
if (col != ncol - 1) {
if (!col_width.empty() && val.size() < col_width[col])
os.write(" ", col_width[col] - val.size());
++col;
} else {
col = 0;
}
}
os.put('\n');
}
inline void write_out_item(std::ostream& os, const Item& item, Style style) {
switch (item.type) {
case ItemType::Pair:
write_out_pair(os, item.pair[0], item.pair[1], style);
break;
case ItemType::Loop:
write_out_loop(os, item.loop, style);
break;
case ItemType::Frame:
os << "save_" << item.frame.name << '\n';
for (const Item& inner_item : item.frame.items)
write_out_item(os, inner_item, style);
os << "save_\n";
break;
case ItemType::Comment:
os << item.pair[1] << '\n';
break;
case ItemType::Erased:
break;
}
}
inline bool should_be_separated_(const Item& a, const Item& b) {
if (a.type == ItemType::Comment || b.type == ItemType::Comment)
return false;
if (a.type != ItemType::Pair || b.type != ItemType::Pair)
return true;
// check if we have mmcif-like tags from different categories
auto adot = a.pair[0].find('.');
if (adot == std::string::npos)
return false;
auto bdot = b.pair[0].find('.');
return adot != bdot || a.pair[0].compare(0, adot, b.pair[0], 0, adot) != 0;
}
inline void write_cif_block_to_stream(std::ostream& os, const Block& block,
Style style=Style::Simple) {
os << "data_" << block.name << '\n';
if (style == Style::Pdbx)
os << "#\n";
const Item* prev = nullptr;
for (const Item& item : block.items)
if (item.type != ItemType::Erased) {
if (prev && style != Style::NoBlankLines &&
should_be_separated_(*prev, item))
os << (style == Style::Pdbx ? "#\n" : "\n");
write_out_item(os, item, style);
prev = &item;
}
if (style == Style::Pdbx)
os << "#\n";
}
inline void write_cif_to_stream(std::ostream& os, const Document& doc,
Style style=Style::Simple) {
bool first = true;
for (const Block& block : doc.blocks) {
if (!first)
os.put('\n'); // extra blank line for readability
write_cif_block_to_stream(os, block, style);
first = false;
}
}
} // namespace cif
} // namespace gemmi
#endif
<|endoftext|> |
<commit_before>///
/// @file generate_phi.hpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes. The algorithm used is an
/// optimized version of the recursive algorithm described in
/// Tomás Oliveira e Silva's paper [2]. I have added 5
/// optimizations to my implementation which speed up the
/// computation by several orders of magnitude.
///
/// [1] In-depth description of primecount's phi(x, a) implementation:
/// https://github.com/kimwalisch/primecount/blob/master/doc/Partial-Sieve-Function.md
/// [2] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef GENERATE_PHI_HPP
#define GENERATE_PHI_HPP
#include <primecount-internal.hpp>
#include <BitSieve240.hpp>
#include <fast_div.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <PhiTiny.hpp>
#include <PiTable.hpp>
#include <pod_vector.hpp>
#include <popcnt.hpp>
#include <stdint.h>
#include <cassert>
#include <utility>
#include <vector>
namespace {
using namespace std;
using namespace primecount;
template <typename Primes>
class PhiCache : public BitSieve240
{
public:
PhiCache(uint64_t x,
uint64_t a,
const Primes& primes,
const PiTable& pi) :
primes_(primes),
pi_(pi)
{
// We cache phi(x, a) if a <= max_a.
// The value max_a = 100 has been determined empirically
// by running benchmarks. Using a smaller or larger
// max_a with the same amount of memory (max_megabytes)
// decreases the performance.
uint64_t max_a = 100;
uint64_t tiny_a = PhiTiny::max_a();
// Make sure we cache only frequently used values
a = a - min(a, 30);
max_a = min(a, max_a);
if (max_a <= tiny_a)
return;
// We cache phi(x, a) if x <= max_x.
// The value max_x = sqrt(x) has been determined by running
// S2_hard(x) and D(x) benchmarks from 1e12 to 1e21.
uint64_t max_x = isqrt(x);
// The cache (i.e. the sieve array)
// uses at most max_megabytes per thread.
uint64_t max_megabytes = 16;
uint64_t indexes = max_a - tiny_a;
uint64_t max_bytes = max_megabytes << 20;
uint64_t max_bytes_per_index = max_bytes / indexes;
uint64_t numbers_per_byte = 240 / sizeof(sieve_t);
uint64_t cache_limit = max_bytes_per_index * numbers_per_byte;
max_x = min(max_x, cache_limit);
max_x_size_ = ceil_div(max_x, 240);
// For tiny computations caching is not worth it
if (max_x_size_ < 8)
return;
// Make sure that there are no uninitialized
// bits in the last sieve array element.
assert(max_x_size_ > 0);
max_x_ = max_x_size_ * 240 - 1;
max_a_ = max_a;
sieve_.resize(max_a_ + 1);
}
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
if (x <= (int64_t) primes_[a])
return SIGN;
else if (is_phi_tiny(a))
return phi_tiny(x, a) * SIGN;
else if (is_pix(x, a))
return (pi_[x] - a + 1) * SIGN;
else if (is_cached(x, a))
return phi_cache(x, a) * SIGN;
// Cache all small phi(x, i) results with:
// x <= max_x && i <= min(a, max_a)
sieve_cache(x, a);
int64_t sqrtx = isqrt(x);
int64_t c = PhiTiny::get_c(sqrtx);
int64_t larger_c = min(a, max_a_cached_);
int64_t sum, i;
if (c >= larger_c ||
!is_cached(x, larger_c))
sum = phi_tiny(x, c) * SIGN;
else
{
c = larger_c;
assert(larger_c <= a);
sum = phi_cache(x, c) * SIGN;
}
for (i = c + 1; i <= a; i++)
{
// phi(x / prime[i], i - 1) = 1 if x / prime[i] <= prime[i-1].
// However we can do slightly better:
// If prime[i] > sqrt(x) and prime[i-1] <= sqrt(x) then
// phi(x / prime[i], i - 1) = 1 even if x / prime[i] > prime[i-1].
// This works because in this case there is no other prime
// inside the interval ]prime[i-1], x / prime[i]].
if (primes_[i] > sqrtx)
break;
int64_t xp = fast_div(x, primes_[i]);
if (is_pix(xp, i - 1))
break;
sum += phi<-SIGN>(xp, i - 1);
}
for (; i <= a; i++)
{
if (primes_[i] > sqrtx)
break;
int64_t xp = fast_div(x, primes_[i]);
// if a >= pi(sqrt(x)): phi(x, a) = pi(x) - a + 1
// phi(xp, i - 1) = pi(xp) - (i - 1) + 1
// phi(xp, i - 1) = pi(xp) - i + 2
sum += (pi_[xp] - i + 2) * -SIGN;
}
// phi(xp, i - 1) = 1 for i in [i, a]
sum += (a + 1 - i) * -SIGN;
}
private:
/// phi(x, a) counts the numbers <= x that are not divisible by any of
/// the first a primes. If a >= pi(sqrt(x)) then phi(x, a) counts the
/// number of primes <= x, minus the first a primes, plus the number 1.
/// Hence if a >= pi(sqrt(x)): phi(x, a) = pi(x) - a + 1.
///
bool is_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(primes_[a + 1]);
}
bool is_cached(uint64_t x, uint64_t a) const
{
return x <= max_x_ &&
a <= max_a_cached_;
}
int64_t phi_cache(uint64_t x, uint64_t a) const
{
assert(a < sieve_.size());
assert(x / 240 < sieve_[a].size());
uint64_t count = sieve_[a][x / 240].count;
uint64_t bits = sieve_[a][x / 240].bits;
uint64_t bitmask = unset_larger_[x % 240];
return count + popcnt64(bits & bitmask);
}
/// Cache phi(x, i) results with: x <= max_x && i <= min(a, max_a).
/// Eratosthenes-like sieving algorithm that removes the first a primes
/// and their multiples from the sieve array. Additionally this
/// algorithm counts the numbers that are not divisible by any of the
/// first a primes after sieving has completed. After sieving and
/// counting has finished phi(x, a) results can be retrieved from the
/// cache in O(1) using the phi_cache(x, a) method.
///
void sieve_cache(uint64_t x, uint64_t a)
{
a = min(a, max_a_);
if (x > max_x_ ||
a <= max_a_cached_)
return;
uint64_t i = max_a_cached_ + 1;
uint64_t tiny_a = PhiTiny::max_a();
max_a_cached_ = a;
i = max(i, 3);
for (; i <= a; i++)
{
// Each bit in the sieve array corresponds to an integer that
// is not divisible by 2, 3 and 5. The 8 bits of each byte
// correspond to the offsets { 1, 7, 11, 13, 17, 19, 23, 29 }.
if (i == 3)
sieve_[i].resize(max_x_size_);
else
{
// Initalize phi(x, i) with phi(x, i - 1)
if (i - 1 <= tiny_a)
sieve_[i] = std::move(sieve_[i - 1]);
else
sieve_[i] = sieve_[i - 1];
// Remove prime[i] and its multiples
uint64_t prime = primes_[i];
if (prime <= max_x_)
sieve_[i][prime / 240].bits &= unset_bit_[prime % 240];
for (uint64_t n = prime * prime; n <= max_x_; n += prime * 2)
sieve_[i][n / 240].bits &= unset_bit_[n % 240];
if (i > tiny_a)
{
uint64_t count = 0;
// Fill an array with the cumulative 1 bit counts.
// sieve[i][j] contains the count of numbers < j * 240 that
// are not divisible by any of the first i primes.
for (auto& sieve : sieve_[i])
{
sieve.count = (uint32_t) count;
count += popcnt64(sieve.bits);
}
}
}
}
}
uint64_t max_x_ = 0;
uint64_t max_x_size_ = 0;
uint64_t max_a_cached_ = 0;
uint64_t max_a_ = 0;
/// Packing sieve_t increases the cache's capacity by 25%
/// which improves performance by up to 10%.
#pragma pack(push, 1)
struct sieve_t
{
uint32_t count = 0;
uint64_t bits = ~0ull;
};
#pragma pack(pop)
/// sieve[a] contains only numbers that are not divisible
/// by any of the the first a primes. sieve[a][i].count
/// contains the count of numbers < i * 240 that are not
/// divisible by any of the first a primes.
vector<vector<sieve_t>> sieve_;
const Primes& primes_;
const PiTable& pi_;
};
/// Returns a vector with phi(x, i - 1) values such that
/// phi[i] = phi(x, i - 1) for 1 <= i <= a.
/// phi(x, a) counts the numbers <= x that are not
/// divisible by any of the first a primes.
///
template <typename Primes>
pod_vector<int64_t>
generate_phi(int64_t x,
int64_t a,
const Primes& primes,
const PiTable& pi)
{
int64_t size = a + 1;
pod_vector<int64_t> phi(size);
phi[0] = 0;
if (size > 1)
{
if ((int64_t) primes[a] > x)
a = pi[x];
phi[1] = x;
int64_t i = 2;
int64_t sqrtx = isqrt(x);
PhiCache<Primes> cache(x, a, primes, pi);
// 2 <= i <= pi(sqrt(x)) + 1
for (; i <= a && primes[i - 1] <= sqrtx; i++)
phi[i] = phi[i - 1] + cache.template phi<-1>(x / primes[i - 1], i - 2);
// pi(sqrt(x)) + 1 < i <= a
for (; i <= a; i++)
phi[i] = phi[i - 1] - (x > 0);
// a < i < size
for (; i < size; i++)
phi[i] = x > 0;
}
return phi;
}
} // namespace
#endif
<commit_msg>Fix copy paste bug<commit_after>///
/// @file generate_phi.hpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes. The algorithm used is an
/// optimized version of the recursive algorithm described in
/// Tomás Oliveira e Silva's paper [2]. I have added 5
/// optimizations to my implementation which speed up the
/// computation by several orders of magnitude.
///
/// [1] In-depth description of primecount's phi(x, a) implementation:
/// https://github.com/kimwalisch/primecount/blob/master/doc/Partial-Sieve-Function.md
/// [2] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef GENERATE_PHI_HPP
#define GENERATE_PHI_HPP
#include <primecount-internal.hpp>
#include <BitSieve240.hpp>
#include <fast_div.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <PhiTiny.hpp>
#include <PiTable.hpp>
#include <pod_vector.hpp>
#include <popcnt.hpp>
#include <stdint.h>
#include <cassert>
#include <utility>
#include <vector>
namespace {
using namespace std;
using namespace primecount;
template <typename Primes>
class PhiCache : public BitSieve240
{
public:
PhiCache(uint64_t x,
uint64_t a,
const Primes& primes,
const PiTable& pi) :
primes_(primes),
pi_(pi)
{
// We cache phi(x, a) if a <= max_a.
// The value max_a = 100 has been determined empirically
// by running benchmarks. Using a smaller or larger
// max_a with the same amount of memory (max_megabytes)
// decreases the performance.
uint64_t max_a = 100;
uint64_t tiny_a = PhiTiny::max_a();
// Make sure we cache only frequently used values
a = a - min(a, 30);
max_a = min(a, max_a);
if (max_a <= tiny_a)
return;
// We cache phi(x, a) if x <= max_x.
// The value max_x = sqrt(x) has been determined by running
// S2_hard(x) and D(x) benchmarks from 1e12 to 1e21.
uint64_t max_x = isqrt(x);
// The cache (i.e. the sieve array)
// uses at most max_megabytes per thread.
uint64_t max_megabytes = 16;
uint64_t indexes = max_a - tiny_a;
uint64_t max_bytes = max_megabytes << 20;
uint64_t max_bytes_per_index = max_bytes / indexes;
uint64_t numbers_per_byte = 240 / sizeof(sieve_t);
uint64_t cache_limit = max_bytes_per_index * numbers_per_byte;
max_x = min(max_x, cache_limit);
max_x_size_ = ceil_div(max_x, 240);
// For tiny computations caching is not worth it
if (max_x_size_ < 8)
return;
// Make sure that there are no uninitialized
// bits in the last sieve array element.
assert(max_x_size_ > 0);
max_x_ = max_x_size_ * 240 - 1;
max_a_ = max_a;
sieve_.resize(max_a_ + 1);
}
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
if (x <= (int64_t) primes_[a])
return SIGN;
else if (is_phi_tiny(a))
return phi_tiny(x, a) * SIGN;
else if (is_pix(x, a))
return (pi_[x] - a + 1) * SIGN;
else if (is_cached(x, a))
return phi_cache(x, a) * SIGN;
// Cache all small phi(x, i) results with:
// x <= max_x && i <= min(a, max_a)
sieve_cache(x, a);
int64_t sqrtx = isqrt(x);
int64_t c = PhiTiny::get_c(sqrtx);
int64_t larger_c = min(a, max_a_cached_);
int64_t sum, i;
if (c >= larger_c ||
!is_cached(x, larger_c))
sum = phi_tiny(x, c) * SIGN;
else
{
c = larger_c;
assert(larger_c <= a);
sum = phi_cache(x, c) * SIGN;
}
for (i = c + 1; i <= a; i++)
{
// phi(x / prime[i], i - 1) = 1 if x / prime[i] <= prime[i-1].
// However we can do slightly better:
// If prime[i] > sqrt(x) and prime[i-1] <= sqrt(x) then
// phi(x / prime[i], i - 1) = 1 even if x / prime[i] > prime[i-1].
// This works because in this case there is no other prime
// inside the interval ]prime[i-1], x / prime[i]].
if (primes_[i] > sqrtx)
break;
int64_t xp = fast_div(x, primes_[i]);
if (is_pix(xp, i - 1))
break;
sum += phi<-SIGN>(xp, i - 1);
}
for (; i <= a; i++)
{
if (primes_[i] > sqrtx)
break;
int64_t xp = fast_div(x, primes_[i]);
// if a >= pi(sqrt(x)): phi(x, a) = pi(x) - a + 1
// phi(xp, i - 1) = pi(xp) - (i - 1) + 1
// phi(xp, i - 1) = pi(xp) - i + 2
sum += (pi_[xp] - i + 2) * -SIGN;
}
// phi(xp, i - 1) = 1 for i in [i, a]
sum += (a + 1 - i) * -SIGN;
return sum;
}
private:
/// phi(x, a) counts the numbers <= x that are not divisible by any of
/// the first a primes. If a >= pi(sqrt(x)) then phi(x, a) counts the
/// number of primes <= x, minus the first a primes, plus the number 1.
/// Hence if a >= pi(sqrt(x)): phi(x, a) = pi(x) - a + 1.
///
bool is_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(primes_[a + 1]);
}
bool is_cached(uint64_t x, uint64_t a) const
{
return x <= max_x_ &&
a <= max_a_cached_;
}
int64_t phi_cache(uint64_t x, uint64_t a) const
{
assert(a < sieve_.size());
assert(x / 240 < sieve_[a].size());
uint64_t count = sieve_[a][x / 240].count;
uint64_t bits = sieve_[a][x / 240].bits;
uint64_t bitmask = unset_larger_[x % 240];
return count + popcnt64(bits & bitmask);
}
/// Cache phi(x, i) results with: x <= max_x && i <= min(a, max_a).
/// Eratosthenes-like sieving algorithm that removes the first a primes
/// and their multiples from the sieve array. Additionally this
/// algorithm counts the numbers that are not divisible by any of the
/// first a primes after sieving has completed. After sieving and
/// counting has finished phi(x, a) results can be retrieved from the
/// cache in O(1) using the phi_cache(x, a) method.
///
void sieve_cache(uint64_t x, uint64_t a)
{
a = min(a, max_a_);
if (x > max_x_ ||
a <= max_a_cached_)
return;
uint64_t i = max_a_cached_ + 1;
uint64_t tiny_a = PhiTiny::max_a();
max_a_cached_ = a;
i = max(i, 3);
for (; i <= a; i++)
{
// Each bit in the sieve array corresponds to an integer that
// is not divisible by 2, 3 and 5. The 8 bits of each byte
// correspond to the offsets { 1, 7, 11, 13, 17, 19, 23, 29 }.
if (i == 3)
sieve_[i].resize(max_x_size_);
else
{
// Initalize phi(x, i) with phi(x, i - 1)
if (i - 1 <= tiny_a)
sieve_[i] = std::move(sieve_[i - 1]);
else
sieve_[i] = sieve_[i - 1];
// Remove prime[i] and its multiples
uint64_t prime = primes_[i];
if (prime <= max_x_)
sieve_[i][prime / 240].bits &= unset_bit_[prime % 240];
for (uint64_t n = prime * prime; n <= max_x_; n += prime * 2)
sieve_[i][n / 240].bits &= unset_bit_[n % 240];
if (i > tiny_a)
{
uint64_t count = 0;
// Fill an array with the cumulative 1 bit counts.
// sieve[i][j] contains the count of numbers < j * 240 that
// are not divisible by any of the first i primes.
for (auto& sieve : sieve_[i])
{
sieve.count = (uint32_t) count;
count += popcnt64(sieve.bits);
}
}
}
}
}
uint64_t max_x_ = 0;
uint64_t max_x_size_ = 0;
uint64_t max_a_cached_ = 0;
uint64_t max_a_ = 0;
/// Packing sieve_t increases the cache's capacity by 25%
/// which improves performance by up to 10%.
#pragma pack(push, 1)
struct sieve_t
{
uint32_t count = 0;
uint64_t bits = ~0ull;
};
#pragma pack(pop)
/// sieve[a] contains only numbers that are not divisible
/// by any of the the first a primes. sieve[a][i].count
/// contains the count of numbers < i * 240 that are not
/// divisible by any of the first a primes.
vector<vector<sieve_t>> sieve_;
const Primes& primes_;
const PiTable& pi_;
};
/// Returns a vector with phi(x, i - 1) values such that
/// phi[i] = phi(x, i - 1) for 1 <= i <= a.
/// phi(x, a) counts the numbers <= x that are not
/// divisible by any of the first a primes.
///
template <typename Primes>
pod_vector<int64_t>
generate_phi(int64_t x,
int64_t a,
const Primes& primes,
const PiTable& pi)
{
int64_t size = a + 1;
pod_vector<int64_t> phi(size);
phi[0] = 0;
if (size > 1)
{
if ((int64_t) primes[a] > x)
a = pi[x];
phi[1] = x;
int64_t i = 2;
int64_t sqrtx = isqrt(x);
PhiCache<Primes> cache(x, a, primes, pi);
// 2 <= i <= pi(sqrt(x)) + 1
for (; i <= a && primes[i - 1] <= sqrtx; i++)
phi[i] = phi[i - 1] + cache.template phi<-1>(x / primes[i - 1], i - 2);
// pi(sqrt(x)) + 1 < i <= a
for (; i <= a; i++)
phi[i] = phi[i - 1] - (x > 0);
// a < i < size
for (; i < size; i++)
phi[i] = x > 0;
}
return phi;
}
} // namespace
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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
*
*****************************************************************************/
//$Id$
#ifndef VALUE_HPP
#define VALUE_HPP
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>
namespace mapnik {
struct value_null
{
};
typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;
namespace impl {
struct equals
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator() (const T &, const U &) const
{
return false;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs == rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs == rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs == rhs;
}
bool operator() (UnicodeString const& lhs,
UnicodeString const& rhs) const
{
return lhs == rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct not_equals
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator() (const T &, const U &) const
{
return true;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs != rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs != rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs != rhs;
}
bool operator() (UnicodeString const& lhs,
UnicodeString const& rhs) const
{
return lhs != rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
template <typename T>
bool operator() (value_null, const T &) const
{
return false;
}
template <typename T>
bool operator() (const T &, value_null) const
{
return false;
}
};
struct greater_than
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs > rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs > rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs > rhs;
}
bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
{
return lhs > rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct greater_or_equal
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs >= rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs >= rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs >= rhs;
}
bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
{
return lhs >= rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct less_than
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs < rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs < rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs < rhs;
}
bool operator()(UnicodeString const& lhs,
UnicodeString const& rhs ) const
{
return lhs < rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct less_or_equal
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs <= rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs <= rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs <= rhs;
}
template <typename T>
bool operator()(UnicodeString const& lhs,
UnicodeString const& rhs ) const
{
return lhs <= rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
template <typename V>
struct add : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs + rhs ;
}
value_type operator() (UnicodeString const& lhs ,
UnicodeString const& rhs ) const
{
return lhs + rhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs + rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs + rhs;
}
};
template <typename V>
struct sub : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs - rhs ;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const& ) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs - rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs - rhs;
}
};
template <typename V>
struct mult : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs , T2 const& ) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs * rhs;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const& ) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs * rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs * rhs;
}
};
template <typename V>
struct div: public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs / rhs;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const&) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs / rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs / rhs;
}
};
struct to_bool : public boost::static_visitor<bool>
{
template <typename T>
bool operator() (T val) const
{
throw config_error("Boolean value expected");
}
bool operator() (bool val) const
{
return val;
}
};
struct to_string : public boost::static_visitor<std::string>
{
template <typename T>
std::string operator() (T val) const
{
std::stringstream ss;
ss << val;
return ss.str();
}
// specializations
std::string operator() (UnicodeString const& val) const
{
//std::stringstream ss;
//std::wstring::const_iterator pos = val.begin();
//ss << std::hex ;
//for (;pos!=val.end();++pos)
//{
// wchar_t c = *pos;
// if (c < 0x80)
// {
// ss << char(c);
// }
// else
// {
// ss << "\\x";
// unsigned c0 = (c >> 8) & 0xff;
// if (c0) ss << c0;
// ss << (c & 0xff);
// }
//}
//return ss.str();
return "TODO";
}
std::string operator() (double val) const
{
std::stringstream ss;
ss << std::setprecision(16) << val;
return ss.str();
}
std::string operator() (value_null const& val) const
{
return "";
}
};
struct to_unicode : public boost::static_visitor<UnicodeString>
{
template <typename T>
UnicodeString operator() (T val) const
{
std::basic_ostringstream<char> out;
out << val;
return UnicodeString(out.str().c_str());
}
// specializations
UnicodeString const& operator() (UnicodeString const& val) const
{
return val;
}
UnicodeString operator() (double val) const
{
std::basic_ostringstream<char> out;
out << std::setprecision(16) << val;
return UnicodeString(out.str().c_str());
}
UnicodeString operator() (value_null const& val) const
{
return UnicodeString("");
}
};
struct to_expression_string : public boost::static_visitor<std::string>
{
std::string operator() (UnicodeString const& val) const
{
/*
std::stringstream ss;
UnicodeString::const_iterator pos = val.begin();
ss << std::hex ;
for (;pos!=val.end();++pos)
{
wchar_t c = *pos;
if (c < 0x80)
{
ss << char(c);
}
else
{
ss << "\\x";
unsigned c0 = (c >> 8) & 0xff;
if (c0) ss << c0;
ss << (c & 0xff);
}
}
return "\'" + ss.str() + "\'";
*/
return "TODO";
}
template <typename T>
std::string operator() (T val) const
{
std::stringstream ss;
ss << val;
return ss.str();
}
std::string operator() (double val) const
{
std::stringstream ss;
ss << std::setprecision(16) << val;
return ss.str();
}
std::string operator() (value_null const& val) const
{
return "null";
}
};
}
class value
{
value_base base_;
friend const value operator+(value const&,value const&);
friend const value operator-(value const&,value const&);
friend const value operator*(value const&,value const&);
friend const value operator/(value const&,value const&);
public:
value ()
: base_(value_null()) {}
template <typename T> value(T _val_)
: base_(_val_) {}
bool operator==(value const& other) const
{
return boost::apply_visitor(impl::equals(),base_,other.base_);
}
bool operator!=(value const& other) const
{
return boost::apply_visitor(impl::not_equals(),base_,other.base_);
}
bool operator>(value const& other) const
{
return boost::apply_visitor(impl::greater_than(),base_,other.base_);
}
bool operator>=(value const& other) const
{
return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
}
bool operator<(value const& other) const
{
return boost::apply_visitor(impl::less_than(),base_,other.base_);
}
bool operator<=(value const& other) const
{
return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
}
value_base const& base() const
{
return base_;
}
bool to_bool() const
{
return boost::apply_visitor(impl::to_bool(),base_);
}
std::string to_expression_string() const
{
return boost::apply_visitor(impl::to_expression_string(),base_);
}
std::string to_string() const
{
return boost::apply_visitor(impl::to_string(),base_);
}
UnicodeString to_unicode() const
{
return boost::apply_visitor(impl::to_unicode(),base_);
}
};
inline const value operator+(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
}
inline const value operator-(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
}
inline const value operator*(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
}
inline const value operator/(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
}
template <typename charT, typename traits>
inline std::basic_ostream<charT,traits>&
operator << (std::basic_ostream<charT,traits>& out,
value const& v)
{
out << v.to_string();
return out;
}
}
#endif //VALUE_HPP
<commit_msg>+ to_utf8 function to convert from icu::UnicodeString to utf-8 std::string<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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
*
*****************************************************************************/
//$Id$
#ifndef VALUE_HPP
#define VALUE_HPP
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/scoped_array.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>
#include <unicode/ustring.h>
namespace mapnik {
inline void to_utf8(UnicodeString const& input, std::string & target)
{
if (input.length() == 0) return;
const int BUF_SIZE = 256;
char buf [BUF_SIZE];
int len;
UErrorCode err = U_ZERO_ERROR;
u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err);
if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING )
{
boost::scoped_array<char> buf_ptr(new char [len+1]);
err = U_ZERO_ERROR;
u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err);
target.assign(buf_ptr.get() , len);
}
else
{
target.assign(buf, len);
}
}
struct value_null
{
};
typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;
namespace impl {
struct equals
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator() (const T &, const U &) const
{
return false;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs == rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs == rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs == rhs;
}
bool operator() (UnicodeString const& lhs,
UnicodeString const& rhs) const
{
return lhs == rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct not_equals
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator() (const T &, const U &) const
{
return true;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs != rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs != rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs != rhs;
}
bool operator() (UnicodeString const& lhs,
UnicodeString const& rhs) const
{
return lhs != rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
template <typename T>
bool operator() (value_null, const T &) const
{
return false;
}
template <typename T>
bool operator() (const T &, value_null) const
{
return false;
}
};
struct greater_than
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs > rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs > rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs > rhs;
}
bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
{
return lhs > rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct greater_or_equal
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator() (T lhs, T rhs) const
{
return lhs >= rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs >= rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs >= rhs;
}
bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
{
return lhs >= rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct less_than
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs < rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs < rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs < rhs;
}
bool operator()(UnicodeString const& lhs,
UnicodeString const& rhs ) const
{
return lhs < rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
struct less_or_equal
: public boost::static_visitor<bool>
{
template <typename T, typename U>
bool operator()(const T &, const U &) const
{
return false;
}
template <typename T>
bool operator()(T lhs, T rhs) const
{
return lhs <= rhs;
}
bool operator() (int lhs, double rhs) const
{
return lhs <= rhs;
}
bool operator() (double lhs, int rhs) const
{
return lhs <= rhs;
}
template <typename T>
bool operator()(UnicodeString const& lhs,
UnicodeString const& rhs ) const
{
return lhs <= rhs;
}
bool operator() (value_null, value_null) const
{
return false;
}
};
template <typename V>
struct add : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs + rhs ;
}
value_type operator() (UnicodeString const& lhs ,
UnicodeString const& rhs ) const
{
return lhs + rhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs + rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs + rhs;
}
};
template <typename V>
struct sub : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs - rhs ;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const& ) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs - rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs - rhs;
}
};
template <typename V>
struct mult : public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs , T2 const& ) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs * rhs;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const& ) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs * rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs * rhs;
}
};
template <typename V>
struct div: public boost::static_visitor<V>
{
typedef V value_type;
template <typename T1, typename T2>
value_type operator() (T1 const& lhs, T2 const&) const
{
return lhs;
}
template <typename T>
value_type operator() (T lhs, T rhs) const
{
return lhs / rhs;
}
value_type operator() (UnicodeString const& lhs,
UnicodeString const&) const
{
return lhs;
}
value_type operator() (double lhs, int rhs) const
{
return lhs / rhs;
}
value_type operator() (int lhs, double rhs) const
{
return lhs / rhs;
}
};
struct to_bool : public boost::static_visitor<bool>
{
template <typename T>
bool operator() (T val) const
{
throw config_error("Boolean value expected");
}
bool operator() (bool val) const
{
return val;
}
};
struct to_string : public boost::static_visitor<std::string>
{
template <typename T>
std::string operator() (T val) const
{
std::stringstream ss;
ss << val;
return ss.str();
}
// specializations
std::string operator() (UnicodeString const& val) const
{
//std::stringstream ss;
//std::wstring::const_iterator pos = val.begin();
//ss << std::hex ;
//for (;pos!=val.end();++pos)
//{
// wchar_t c = *pos;
// if (c < 0x80)
// {
// ss << char(c);
// }
// else
// {
// ss << "\\x";
// unsigned c0 = (c >> 8) & 0xff;
// if (c0) ss << c0;
// ss << (c & 0xff);
// }
//}
//return ss.str();
return "TODO";
}
std::string operator() (double val) const
{
std::stringstream ss;
ss << std::setprecision(16) << val;
return ss.str();
}
std::string operator() (value_null const& val) const
{
return "";
}
};
struct to_unicode : public boost::static_visitor<UnicodeString>
{
template <typename T>
UnicodeString operator() (T val) const
{
std::basic_ostringstream<char> out;
out << val;
return UnicodeString(out.str().c_str());
}
// specializations
UnicodeString const& operator() (UnicodeString const& val) const
{
return val;
}
UnicodeString operator() (double val) const
{
std::basic_ostringstream<char> out;
out << std::setprecision(16) << val;
return UnicodeString(out.str().c_str());
}
UnicodeString operator() (value_null const& val) const
{
return UnicodeString("");
}
};
struct to_expression_string : public boost::static_visitor<std::string>
{
std::string operator() (UnicodeString const& val) const
{
std::string utf8;
to_utf8(val,utf8);
return "'" + utf8 + "'";
}
template <typename T>
std::string operator() (T val) const
{
std::stringstream ss;
ss << val;
return ss.str();
}
std::string operator() (double val) const
{
std::stringstream ss;
ss << std::setprecision(16) << val;
return ss.str();
}
std::string operator() (value_null const& val) const
{
return "null";
}
};
}
class value
{
value_base base_;
friend const value operator+(value const&,value const&);
friend const value operator-(value const&,value const&);
friend const value operator*(value const&,value const&);
friend const value operator/(value const&,value const&);
public:
value ()
: base_(value_null()) {}
template <typename T> value(T _val_)
: base_(_val_) {}
bool operator==(value const& other) const
{
return boost::apply_visitor(impl::equals(),base_,other.base_);
}
bool operator!=(value const& other) const
{
return boost::apply_visitor(impl::not_equals(),base_,other.base_);
}
bool operator>(value const& other) const
{
return boost::apply_visitor(impl::greater_than(),base_,other.base_);
}
bool operator>=(value const& other) const
{
return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
}
bool operator<(value const& other) const
{
return boost::apply_visitor(impl::less_than(),base_,other.base_);
}
bool operator<=(value const& other) const
{
return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
}
value_base const& base() const
{
return base_;
}
bool to_bool() const
{
return boost::apply_visitor(impl::to_bool(),base_);
}
std::string to_expression_string() const
{
return boost::apply_visitor(impl::to_expression_string(),base_);
}
std::string to_string() const
{
return boost::apply_visitor(impl::to_string(),base_);
}
UnicodeString to_unicode() const
{
return boost::apply_visitor(impl::to_unicode(),base_);
}
};
inline const value operator+(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
}
inline const value operator-(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
}
inline const value operator*(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
}
inline const value operator/(value const& p1,value const& p2)
{
return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
}
template <typename charT, typename traits>
inline std::basic_ostream<charT,traits>&
operator << (std::basic_ostream<charT,traits>& out,
value const& v)
{
out << v.to_string();
return out;
}
}
#endif //VALUE_HPP
<|endoftext|> |
<commit_before>class AliAnalysisGrid;
const char *dataset = "";
TString anaLibs = "";
//Int_t iESDfilter = 1;
Int_t iESDfilter = 0;
Int_t iAODTagCreation = 1;
Int_t iAODAddMCBranch = 0;
//______________________________________________________________________________
void RunGrid(
const char* runtype = "local", // local, proof or grid
const char *gridmode = "test", // Set the run mode (can be "full", "test", "offline", "submit" or "terminate"). Full & Test work for proof
const bool bMCtruth = 1, // 1 = MCEvent handler is on (MC truth), 0 = MCEvent handler is off (MC reconstructed/real data)
const bool bMCphyssel = 1, // 1 = looking at MC truth or reconstructed, 0 = looking at real data
const Long64_t nentries = 2000, // for local and proof mode, ignored in grid mode. Set to 1234567890 for all events.
const Long64_t firstentry = 0, // for local and proof mode, ignored in grid mode
const char *proofdataset = "/alice/data/LHC10c_000120821_p1", // path to dataset on proof cluster, for proof analysis
const char *proofcluster = "alice-caf.cern.ch", // which proof cluster to use in proof mode
const char *taskname = "Flowd_PbPb2011"
)
{
// check run type
if(runtype != "local" && runtype != "proof" && runtype != "grid"){
Printf("\n\tIncorrect run option, check first argument of run macro");
Printf("\tint runtype = local, proof or grid\n");
return;
}
Printf("%s analysis chosen",runtype);
gROOT->ProcessLine(".include $ALICE_ROOT/include");
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gSystem->AddIncludePath("-I$ALICE_ROOT/PWGHF/vertexingHF");
// Load analysis specific libraries
//=====================================================================
gSystem->SetIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER/STEER -I$ALICE_ROOT/STEER/STEERBase -I$ALICE_ROOT/STEER/ESD -I$ALICE_ROOT/STEER/AOD -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -I$ALICE_ROOT/OADB -I$ALICE_ROOT/PWGHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWG/FLOW/Base -I$ALICE_ROOT/PWG/FLOW/Tasks -g");
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libPhysics.so");
gSystem->Load("libVMC.so");
gSystem->Load("libMinuit.so");
gSystem->Load("libSTEERBase.so");
gSystem->Load("libESD.so");
gSystem->Load("libAOD.so");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libOADB.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libCORRFW.so");
gSystem->Load("libPWGHFbase.so");
gSystem->Load("libPWGflowBase.so");
gSystem->Load("libPWGflowTasks.so");
gSystem->Load("libPWGHFvertexingHF.so");
// Load analysis specific libraries
//=====================================================================
//------ Create AlienPlugin ---------------------
AliAnalysisGrid *plugin = 0x0;
TChain *chain = 0x0;
if (runtype != "local") {
plugin = CreateAlienHandler(taskname, gridmode, proofcluster, proofdataset);
if(!plugin) return;
} else {
gROOT->LoadMacro("$ALICE_ROOT/PWGCF/Correlations/macros/dphicorrelations/CreateESDChain.C");
chain = CreateESDChain("ESDs.txt");
}
//---- Create the analysis manager
AliAnalysisManager* mgr = new AliAnalysisManager(taskname);
if(plugin) mgr->SetGridHandler(plugin);
// Input
AliESDInputHandler* iH = new AliESDInputHandler("handler","handler for my analisys");
mgr->SetInputEventHandler(iH);
//--------------------------------------------------------------
// Other tasks
// Physics selection
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AliPhysicsSelectionTask *physSel = AddTaskPhysicsSelection(kFALSE); // useMC
// Centrality selection
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AliCentralitySelectionTask *taskCentr = AddTaskCentrality();
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AliAnalysisTaskPIDResponse *pidTask = AddTaskPIDResponse(kFALSE); // useMC
gROOT->LoadMacro("./AliAnalysisTaskFlowd.cxx+g");//$ALICE_ROOT/PWGLF/STRANGENESS/Cascades/AliAnalysisTaskCheckCascadePbPb.cxx++g");
gROOT->LoadMacro("./AddTaskFlowd.C");//$ALICE_ROOT/PWGLF/STRANGENESS/Cascades/macros/AddTaskCheckCascadePbPb.C");
AliAnalysisTaskFlowd *task = AddTaskFlowd(kTRUE);
//__________________________________________________________________________
// Disable debug printouts
mgr->SetDebugLevel(3);
AliLog::SetGlobalLogLevel(AliLog::kFatal);
AliLog::SetGlobalDebugLevel(0);
//__________________________________________________________________________
if (!mgr->InitAnalysis()) return;
mgr->PrintStatus();
// Start analysis in grid.
if (runtype == "local")
mgr->StartAnalysis(runtype,chain,nentries,firstentry);
else
mgr->StartAnalysis(runtype,nentries,firstentry);
}
//______________________________________________________________________________
AliAnalysisGrid* CreateAlienHandler(const char *taskname, const char *gridmode, const char *proofcluster, const char *proofdataset)
{
AliAnalysisAlien *plugin = new AliAnalysisAlien();
// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
plugin->SetRunMode(gridmode);
// Set versions of used packages
plugin->SetAPIVersion("V1.1x");
plugin->SetROOTVersion("v5-34-08");
plugin->SetAliROOTVersion("vAN-20140915");
plugin->SetExecutableCommand("aliroot -b -q");
// Declare input data to be processed.
// Method 1: Create automatically XML collections using alien 'find' command.
// Define production directory LFN
// plugin->SetGridDataDir("/alice/data/2010/LHC10h");
// plugin->SetGridDataDir(" /alice/data/2011/LHC11h_2/"); //sim
// plugin->SetDataPattern("pass2/*AliAOD.root"); // sim
plugin->SetGridDataDir("/alice/data/2011/LHC11h_2/"); //sim
plugin->SetDataPattern("/pass2/ESDs/*AliESD.root"); // sim
plugin->SetRunPrefix("000"); // real data
Int_t runlist[1]={167693};
for(Int_t i=0;i<1;i++)
plugin->AddRunNumber(runlist[i]);
// plugin->AddRunNumber(139505);
// plugin->AddRunNumber(138652);
plugin->SetNrunsPerMaster(1);
plugin->SetOutputToRunNo();
// Method 2: Declare existing data files (raw collections, xml collections, root file)
// plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
// Define alien work directory where all files will be copied. Relative to alien $HOME.
plugin->SetGridWorkingDir(taskname);
// Declare alien output directory. Relative to working directory.
plugin->SetGridOutputDir("output"); // In this case will be $HOME/taskname/out
// plugin->SetAdditionalLibs("libTree.so libGeom.so libPhysics.so libVMC.so libMinuit.so libSTEERBase.so libESD.so libAOD.so libANALYSIS.so libOADB.so libANALYSISalice.so libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
// plugin->SetAdditionalLibs("libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
plugin->SetAnalysisSource("AliAnalysisTaskFlowd.cxx");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 1"<<endl;
// Declare the analysis source files names separated by blancs. To be compiled runtime
// using ACLiC on the worker nodes.
//plugin->SetAdditionalLibs("libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so AliAODMuonReplicator0.so");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 2"<<endl;
// plugin->SetAdditionalLibs("libTree.so libGeom.so libPhysics.so libVMC.so libMinuit.so libSTEERBase.so libESD.so libAOD.so libANALYSIS.so libOADB.so libANALYSISalice.so libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
// plugin->SetAnalysisSource("AliAnalysisTaskESDMuonFilterO.cxx");
//plugin->SetAnalysisSource("AliAODMuonReplicator0.cxx");
// Declare all libraries (other than the default ones for the framework. These will be
// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
// plugin->SetAdditionalLibs("AliAODMuonReplicator0_cxx.so");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO_cxx.so");
//questo
plugin->SetAdditionalLibs("libPWGflowBase.so libPWGflowTasks.so libPWGHFbase.so libPWGHFvertexingHF.so");
plugin->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER/STEER -I$ALICE_ROOT/STEER/STEERBase -I$ALICE_ROOT/STEER/ESD -I$ALICE_ROOT/STEER/AOD -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -I$ALICE_ROOT/OADB -I$ALICE_ROOT/PWGHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWG/FLOW/Base -I$ALICE_ROOT/PWG/FLOW/Tasks -g");
// plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
//plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 3"<<endl;
// plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
// Declare the output file names separated by blancs.
// (can be like: file.root or file.root@ALICE::Niham::File)
// To only save certain files, use SetDefaultOutputs(kFALSE), and then
// SetOutputFiles("list.root other.filename") to choose which files to save
plugin->SetDefaultOutputs();
//plugin->SetOutputFiles("list.root");
// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
plugin->SetAnalysisMacro(Form("%s.C",taskname));
// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
plugin->SetSplitMaxInputFileNumber(100);
// Optionally modify the executable name (default analysis.sh)
plugin->SetExecutable(Form("%s.sh",taskname));
// set number of test files to use in "test" mode
plugin->SetNtestFiles(10);
// Optionally resubmit threshold.
plugin->SetMasterResubmitThreshold(90);
// Optionally set time to live (default 30000 sec)
plugin->SetTTL(30000);
// Optionally set input format (default xml-single)
plugin->SetInputFormat("xml-single");
// Optionally modify the name of the generated JDL (default analysis.jdl)
plugin->SetJDLName(Form("%s.jdl",taskname));
// Optionally modify job price (default 1)
plugin->SetPrice(1);
// Optionally modify split mode (default 'se')
plugin->SetSplitMode("se");
//----------------------------------------------------------
//--- PROOF MODE SPECIFIC SETTINGS ------------
//----------------------------------------------------------
// Proof cluster
plugin->SetProofCluster(proofcluster);
// Dataset to be used
plugin->SetProofDataSet(proofdataset);
// May need to reset proof. Supported modes: 0-no reset, 1-soft, 2-hard
plugin->SetProofReset(0);
// May limit number of workers
plugin->SetNproofWorkers(0);
// May limit the number of workers per slave
plugin->SetNproofWorkersPerSlave(1);
// May use a specific version of root installed in proof
plugin->SetRootVersionForProof("current");
// May set the aliroot mode. Check http://aaf.cern.ch/node/83
plugin->SetAliRootMode("default"); // Loads AF libs by default
// May request ClearPackages (individual ClearPackage not supported)
plugin->SetClearPackages(kFALSE);
// Plugin test mode works only providing a file containing test file locations, used in "local" mode also
plugin->SetFileForTestMode("files.txt"); // file should contain path name to a local directory containg *ESDs.root etc
// Request connection to alien upon connection to grid
plugin->SetProofConnectGrid(kFALSE);
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 4"<<endl;
return plugin;
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 5"<<endl;
}
<commit_msg>Fixed data pattern<commit_after>class AliAnalysisGrid;
const char *dataset = "";
TString anaLibs = "";
//Int_t iESDfilter = 1;
Int_t iESDfilter = 0;
Int_t iAODTagCreation = 1;
Int_t iAODAddMCBranch = 0;
//______________________________________________________________________________
void RunGrid(
const char* runtype = "local", // local, proof or grid
const char *gridmode = "test", // Set the run mode (can be "full", "test", "offline", "submit" or "terminate"). Full & Test work for proof
const bool bMCtruth = 1, // 1 = MCEvent handler is on (MC truth), 0 = MCEvent handler is off (MC reconstructed/real data)
const bool bMCphyssel = 1, // 1 = looking at MC truth or reconstructed, 0 = looking at real data
const Long64_t nentries = 2000, // for local and proof mode, ignored in grid mode. Set to 1234567890 for all events.
const Long64_t firstentry = 0, // for local and proof mode, ignored in grid mode
const char *proofdataset = "/alice/data/LHC10c_000120821_p1", // path to dataset on proof cluster, for proof analysis
const char *proofcluster = "alice-caf.cern.ch", // which proof cluster to use in proof mode
const char *taskname = "Flowd_PbPb2011"
)
{
// check run type
if(runtype != "local" && runtype != "proof" && runtype != "grid"){
Printf("\n\tIncorrect run option, check first argument of run macro");
Printf("\tint runtype = local, proof or grid\n");
return;
}
Printf("%s analysis chosen",runtype);
gROOT->ProcessLine(".include $ALICE_ROOT/include");
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gSystem->AddIncludePath("-I$ALICE_ROOT/PWGHF/vertexingHF");
// Load analysis specific libraries
//=====================================================================
gSystem->SetIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER/STEER -I$ALICE_ROOT/STEER/STEERBase -I$ALICE_ROOT/STEER/ESD -I$ALICE_ROOT/STEER/AOD -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -I$ALICE_ROOT/OADB -I$ALICE_ROOT/PWGHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWG/FLOW/Base -I$ALICE_ROOT/PWG/FLOW/Tasks -g");
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libPhysics.so");
gSystem->Load("libVMC.so");
gSystem->Load("libMinuit.so");
gSystem->Load("libSTEERBase.so");
gSystem->Load("libESD.so");
gSystem->Load("libAOD.so");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libOADB.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libCORRFW.so");
gSystem->Load("libPWGHFbase.so");
gSystem->Load("libPWGflowBase.so");
gSystem->Load("libPWGflowTasks.so");
gSystem->Load("libPWGHFvertexingHF.so");
// Load analysis specific libraries
//=====================================================================
//------ Create AlienPlugin ---------------------
AliAnalysisGrid *plugin = 0x0;
TChain *chain = 0x0;
if (runtype != "local") {
plugin = CreateAlienHandler(taskname, gridmode, proofcluster, proofdataset);
if(!plugin) return;
} else {
gROOT->LoadMacro("$ALICE_ROOT/PWGCF/Correlations/macros/dphicorrelations/CreateESDChain.C");
chain = CreateESDChain("ESDs.txt");
}
//---- Create the analysis manager
AliAnalysisManager* mgr = new AliAnalysisManager(taskname);
if(plugin) mgr->SetGridHandler(plugin);
// Input
AliESDInputHandler* iH = new AliESDInputHandler("handler","handler for my analisys");
mgr->SetInputEventHandler(iH);
//--------------------------------------------------------------
// Other tasks
// Physics selection
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AliPhysicsSelectionTask *physSel = AddTaskPhysicsSelection(kFALSE); // useMC
// Centrality selection
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AliCentralitySelectionTask *taskCentr = AddTaskCentrality();
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AliAnalysisTaskPIDResponse *pidTask = AddTaskPIDResponse(kFALSE); // useMC
gROOT->LoadMacro("./AliAnalysisTaskFlowd.cxx+g");//$ALICE_ROOT/PWGLF/STRANGENESS/Cascades/AliAnalysisTaskCheckCascadePbPb.cxx++g");
gROOT->LoadMacro("./AddTaskFlowd.C");//$ALICE_ROOT/PWGLF/STRANGENESS/Cascades/macros/AddTaskCheckCascadePbPb.C");
AliAnalysisTaskFlowd *task = AddTaskFlowd(kTRUE);
//__________________________________________________________________________
// Disable debug printouts
mgr->SetDebugLevel(3);
AliLog::SetGlobalLogLevel(AliLog::kFatal);
AliLog::SetGlobalDebugLevel(0);
//__________________________________________________________________________
if (!mgr->InitAnalysis()) return;
mgr->PrintStatus();
// Start analysis in grid.
if (runtype == "local")
mgr->StartAnalysis(runtype,chain,nentries,firstentry);
else
mgr->StartAnalysis(runtype,nentries,firstentry);
}
//______________________________________________________________________________
AliAnalysisGrid* CreateAlienHandler(const char *taskname, const char *gridmode, const char *proofcluster, const char *proofdataset)
{
AliAnalysisAlien *plugin = new AliAnalysisAlien();
// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
plugin->SetRunMode(gridmode);
// Set versions of used packages
plugin->SetAPIVersion("V1.1x");
plugin->SetROOTVersion("v5-34-08");
plugin->SetAliROOTVersion("vAN-20140915");
plugin->SetExecutableCommand("aliroot -b -q");
// Declare input data to be processed.
// Method 1: Create automatically XML collections using alien 'find' command.
// Define production directory LFN
// plugin->SetGridDataDir("/alice/data/2010/LHC10h");
// plugin->SetGridDataDir(" /alice/data/2011/LHC11h_2/"); //sim
// plugin->SetDataPattern("pass2/*AliAOD.root"); // sim
plugin->SetGridDataDir("/alice/data/2011/LHC11h_2/"); //sim
plugin->SetDataPattern("*/pass2/*AliESDs.root"); // sim
plugin->SetRunPrefix("000"); // real data
Int_t runlist[1]={167693};
for(Int_t i=0;i<1;i++)
plugin->AddRunNumber(runlist[i]);
// plugin->AddRunNumber(139505);
// plugin->AddRunNumber(138652);
plugin->SetNrunsPerMaster(1);
plugin->SetOutputToRunNo();
// Method 2: Declare existing data files (raw collections, xml collections, root file)
// plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
// Define alien work directory where all files will be copied. Relative to alien $HOME.
plugin->SetGridWorkingDir(taskname);
// Declare alien output directory. Relative to working directory.
plugin->SetGridOutputDir("output"); // In this case will be $HOME/taskname/out
// plugin->SetAdditionalLibs("libTree.so libGeom.so libPhysics.so libVMC.so libMinuit.so libSTEERBase.so libESD.so libAOD.so libANALYSIS.so libOADB.so libANALYSISalice.so libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
// plugin->SetAdditionalLibs("libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
plugin->SetAnalysisSource("AliAnalysisTaskFlowd.cxx");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 1"<<endl;
// Declare the analysis source files names separated by blancs. To be compiled runtime
// using ACLiC on the worker nodes.
//plugin->SetAdditionalLibs("libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so AliAODMuonReplicator0.so");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 2"<<endl;
// plugin->SetAdditionalLibs("libTree.so libGeom.so libPhysics.so libVMC.so libMinuit.so libSTEERBase.so libESD.so libAOD.so libANALYSIS.so libOADB.so libANALYSISalice.so libCORRFW.so libPWGHFbase.so libPWGflowBase.so libPWGflowTasks.so libPWGHFvertexingHF.so");
// plugin->SetAnalysisSource("AliAnalysisTaskESDMuonFilterO.cxx");
//plugin->SetAnalysisSource("AliAODMuonReplicator0.cxx");
// Declare all libraries (other than the default ones for the framework. These will be
// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
// plugin->SetAdditionalLibs("AliAODMuonReplicator0_cxx.so");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO_cxx.so");
//questo
plugin->SetAdditionalLibs("libPWGflowBase.so libPWGflowTasks.so libPWGHFbase.so libPWGHFvertexingHF.so");
plugin->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER/STEER -I$ALICE_ROOT/STEER/STEERBase -I$ALICE_ROOT/STEER/ESD -I$ALICE_ROOT/STEER/AOD -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -I$ALICE_ROOT/OADB -I$ALICE_ROOT/PWGHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWG/FLOW/Base -I$ALICE_ROOT/PWG/FLOW/Tasks -g");
// plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
//plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 3"<<endl;
// plugin->SetAdditionalLibs("AliAODMuonReplicator0.h AliAODMuonReplicator0.cxx");
// plugin->SetAdditionalLibs("AliAnalysisTaskESDMuonFilterO.h AliAnalysisTaskESDMuonFilterO.cxx");
// Declare the output file names separated by blancs.
// (can be like: file.root or file.root@ALICE::Niham::File)
// To only save certain files, use SetDefaultOutputs(kFALSE), and then
// SetOutputFiles("list.root other.filename") to choose which files to save
plugin->SetDefaultOutputs();
//plugin->SetOutputFiles("list.root");
// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
plugin->SetAnalysisMacro(Form("%s.C",taskname));
// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
plugin->SetSplitMaxInputFileNumber(100);
// Optionally modify the executable name (default analysis.sh)
plugin->SetExecutable(Form("%s.sh",taskname));
// set number of test files to use in "test" mode
plugin->SetNtestFiles(10);
// Optionally resubmit threshold.
plugin->SetMasterResubmitThreshold(90);
// Optionally set time to live (default 30000 sec)
plugin->SetTTL(30000);
// Optionally set input format (default xml-single)
plugin->SetInputFormat("xml-single");
// Optionally modify the name of the generated JDL (default analysis.jdl)
plugin->SetJDLName(Form("%s.jdl",taskname));
// Optionally modify job price (default 1)
plugin->SetPrice(1);
// Optionally modify split mode (default 'se')
plugin->SetSplitMode("se");
//----------------------------------------------------------
//--- PROOF MODE SPECIFIC SETTINGS ------------
//----------------------------------------------------------
// Proof cluster
plugin->SetProofCluster(proofcluster);
// Dataset to be used
plugin->SetProofDataSet(proofdataset);
// May need to reset proof. Supported modes: 0-no reset, 1-soft, 2-hard
plugin->SetProofReset(0);
// May limit number of workers
plugin->SetNproofWorkers(0);
// May limit the number of workers per slave
plugin->SetNproofWorkersPerSlave(1);
// May use a specific version of root installed in proof
plugin->SetRootVersionForProof("current");
// May set the aliroot mode. Check http://aaf.cern.ch/node/83
plugin->SetAliRootMode("default"); // Loads AF libs by default
// May request ClearPackages (individual ClearPackage not supported)
plugin->SetClearPackages(kFALSE);
// Plugin test mode works only providing a file containing test file locations, used in "local" mode also
plugin->SetFileForTestMode("files.txt"); // file should contain path name to a local directory containg *ESDs.root etc
// Request connection to alien upon connection to grid
plugin->SetProofConnectGrid(kFALSE);
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 4"<<endl;
return plugin;
cout<<"-->>>>>>>>>>>>>>>>>>>>>>>>> 5"<<endl;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#include "TextUtils.h"
/* system headers */
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#ifdef __APPLE__
#include <sstream>
#include <CoreServices/CoreServices.h>
#include <sys/sysctl.h>
#endif
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/utsname.h>
#endif
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
# define BZ_PROTO_VERSION "0108"
#endif
// ditto for bzrobots
#ifndef BZROBOTS_PROTO_VERSION
# define BZROBOTS_PROTO_VERSION "0001"
#endif
// version numbers - also update:
// README
// configure.ac
// include/version.h
// package/win32/nsis/BZFlag.nsi
#ifndef BZ_MAJOR_VERSION
# define BZ_MAJOR_VERSION 2
#endif
#ifndef BZ_MINOR_VERSION
# define BZ_MINOR_VERSION 99
#endif
#ifndef BZ_REV
# define BZ_REV 50
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
# define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2009 Tim Riker";
//
// Although the ./configure process will generate
// -DBZ_BUILD_DATE for the build, here it's voided.
//
// Could someone explain the reason for the
// inconience caused by the ./configure method? This
// way is simple, touch the *.cxx to get a new time
// stamp (no big recompiles). If this file is updated,
// you are also forced to get a new timestamp.
//
// Using __DATE__ for all OSes is more consistent.
//
#undef BZ_BUILD_DATE
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horrible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
static const char buildDate[] = {__DATE__};
static const char monthsOfYear[][4] = {"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"};
int getBuildDate()
{
int year = 1900, month, day = 0;
char monthStr[4];
sscanf(buildDate, "%4s %d %d", monthStr, &day, &year);
for (month = 12; month > 1; --month) {
if (strcmp(monthStr, monthsOfYear[month-1]) == 0)
break;
}
return 10000*year + 100*month + day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getRobotsProtocolVersion()
{
static std::string robotsProtVersion = BZROBOTS_PROTO_VERSION;
return robotsProtVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getMajorMinorVersion()
{
static std::string version = "";
if (!version.size()){
std::ostringstream versionStream;
versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
version = versionStream.str();
}
return version.c_str();
}
const char* getMajorMinorRevVersion()
{
static std::string version = "";
if (!version.size()){
std::ostringstream versionStream;
versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
version = versionStream.str();
}
return version.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
std::string getOSString()
{
#ifdef __APPLE__
OSErr err = noErr;
long systemMajor, systemMinor, systemBugFix = 0;
err = Gestalt(gestaltSystemVersionMajor, &systemMajor);
if (err == noErr){
err = Gestalt(gestaltSystemVersionMinor, &systemMinor);
if (err == noErr){
err = Gestalt(gestaltSystemVersionBugFix, &systemBugFix);
}
}
std::stringstream reply;
if (err == noErr) {
reply << "Mac OS X Version ";
reply << systemMajor;
reply << ".";
reply << systemMinor;
reply << ".";
reply << systemBugFix;
} else {
reply << "unknown system version (Gestalt error)";
}
long systemArchitecture = 0;
err = Gestalt(gestaltSysArchitecture, &systemArchitecture);
if (err == noErr) {
switch (systemArchitecture) {
case gestalt68k: {reply << " 68k"; break;}
case gestaltPowerPC: {reply << " PPC"; break;}
case gestaltIntel: {reply << " x86"; break;}
default: {reply << " unknown CPU architecture (Gestalt reply is ";
reply << systemArchitecture; reply << ")";}
}
} else {
reply << " unknown CPU architecture (Gestalt error)";
}
int value = 0;
size_t length = sizeof(value);
if (sysctlbyname("hw.cpu64bit_capable", &value, &length, NULL, 0) == 0) {
if (value) {
reply << "; CPU 64 bit cabable";
}
}
return std::string(reply.str());
#else
#ifdef _WIN32
// build up version string
OSVERSIONINFOEX versionInfo;
SYSTEM_INFO systemInfo;
versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((LPOSVERSIONINFO)&versionInfo);
GetNativeSystemInfo(&systemInfo);
std::string versionString;
std::string platform = "Win32";
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
platform = "Win64";
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
platform = "WinIA64";
versionString = TextUtils::format("%s%d.%d.%d sp%d.$d",platform.c_str(),versionInfo.dwMajorVersion,versionInfo.dwMinorVersion,versionInfo.dwBuildNumber, versionInfo.wServicePackMajor,versionInfo.wServicePackMinor);
return versionString;
#else
std::string versionString;
struct utsname buf;
if (uname(&buf) == 0) {
std::vector<std::string> rtok = TextUtils::tokenize(buf.release, ".", 4);
std::string rel;
unsigned int i;
// use up to three period separated elements of the release string
for (i = 0; i < 3 && i < rtok.size(); i++) {
if (rel.size() > 0)
rel += ".";
rel += rtok[i];
}
// "Linux 2.6.27 x86_64" for example
versionString = TextUtils::format("%s %s %s", buf.sysname, rel.c_str(), buf.machine);
}
else {
perror("uname");
versionString = "unix unknown";
}
return versionString;
#endif
#endif
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Refactor getOSString() with better #ifdef structure. Fix whitespace.<commit_after>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* system headers */
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#ifdef __APPLE__
#include <sstream>
#include <CoreServices/CoreServices.h>
#include <sys/sysctl.h>
#else
#include <sys/utsname.h>
#endif // __APPLE__
#endif // _WIN32
// common headers
#include "TextUtils.h"
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
# define BZ_PROTO_VERSION "0108"
#endif
// ditto for bzrobots
#ifndef BZROBOTS_PROTO_VERSION
# define BZROBOTS_PROTO_VERSION "0001"
#endif
// version numbers - also update:
// README
// configure.ac
// include/version.h
// package/win32/nsis/BZFlag.nsi
#ifndef BZ_MAJOR_VERSION
# define BZ_MAJOR_VERSION 2
#endif
#ifndef BZ_MINOR_VERSION
# define BZ_MINOR_VERSION 99
#endif
#ifndef BZ_REV
# define BZ_REV 50
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
# define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2009 Tim Riker";
//
// Although the ./configure process will generate
// -DBZ_BUILD_DATE for the build, here it's voided.
//
// Could someone explain the reason for the
// inconience caused by the ./configure method? This
// way is simple, touch the *.cxx to get a new time
// stamp (no big recompiles). If this file is updated,
// you are also forced to get a new timestamp.
//
// Using __DATE__ for all OSes is more consistent.
//
#undef BZ_BUILD_DATE
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horrible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
static const char buildDate[] = {__DATE__};
static const char monthsOfYear[][4] = {"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"};
int getBuildDate()
{
int year = 1900, month, day = 0;
char monthStr[4];
sscanf(buildDate, "%4s %d %d", monthStr, &day, &year);
for (month = 12; month > 1; --month) {
if (strcmp(monthStr, monthsOfYear[month-1]) == 0)
break;
}
return 10000*year + 100*month + day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getRobotsProtocolVersion()
{
static std::string robotsProtVersion = BZROBOTS_PROTO_VERSION;
return robotsProtVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getMajorMinorVersion()
{
static std::string version = "";
if (!version.size()){
std::ostringstream versionStream;
versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
version = versionStream.str();
}
return version.c_str();
}
const char* getMajorMinorRevVersion()
{
static std::string version = "";
if (!version.size()){
std::ostringstream versionStream;
versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
version = versionStream.str();
}
return version.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
std::string getOSString()
{
std::string versionString = "unknown";
#ifdef _WIN32
// build up version string
OSVERSIONINFOEX versionInfo;
SYSTEM_INFO systemInfo;
versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((LPOSVERSIONINFO)&versionInfo);
GetNativeSystemInfo(&systemInfo);
std::string platform = "Win32";
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
platform = "Win64";
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
platform = "WinIA64";
versionString = TextUtils::format("%s%d.%d.%d sp%d.$d",platform.c_str(),versionInfo.dwMajorVersion,versionInfo.dwMinorVersion,versionInfo.dwBuildNumber, versionInfo.wServicePackMajor,versionInfo.wServicePackMinor);
#else
#ifdef __APPLE__
OSErr err = noErr;
long systemMajor, systemMinor, systemBugFix = 0;
err = Gestalt(gestaltSystemVersionMajor, &systemMajor);
if (err == noErr){
err = Gestalt(gestaltSystemVersionMinor, &systemMinor);
if (err == noErr){
err = Gestalt(gestaltSystemVersionBugFix, &systemBugFix);
}
}
std::stringstream reply;
if (err == noErr) {
reply << "Mac OS X Version ";
reply << systemMajor;
reply << ".";
reply << systemMinor;
reply << ".";
reply << systemBugFix;
} else {
reply << "unknown system version (Gestalt error)";
}
long systemArchitecture = 0;
err = Gestalt(gestaltSysArchitecture, &systemArchitecture);
if (err == noErr) {
switch (systemArchitecture) {
case gestalt68k: {reply << " 68k"; break;}
case gestaltPowerPC: {reply << " PPC"; break;}
case gestaltIntel: {reply << " x86"; break;}
default: {reply << " unknown CPU architecture (Gestalt reply is ";
reply << systemArchitecture; reply << ")";}
}
} else {
reply << " unknown CPU architecture (Gestalt error)";
}
int value = 0;
size_t length = sizeof(value);
if (sysctlbyname("hw.cpu64bit_capable", &value, &length, NULL, 0) == 0) {
if (value) {
reply << "; CPU 64 bit cabable";
}
}
versionString = reply.str();
#else
struct utsname buf;
if (uname(&buf) == 0) {
std::vector<std::string> rtok = TextUtils::tokenize(buf.release, ".", 4);
std::string rel;
unsigned int i;
// use up to three period separated elements of the release string
for (i = 0; i < 3 && i < rtok.size(); i++) {
if (rel.size() > 0)
rel += ".";
rel += rtok[i];
}
// "Linux 2.6.27 x86_64" for example
versionString = TextUtils::format("%s %s %s", buf.sysname, rel.c_str(), buf.machine);
}
else {
perror("uname");
versionString = "unix unknown";
}
#endif // __APPLE__
#endif // _WIN32
return versionString;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <[email protected]>
#ifdef _WIN32
#ifdef NIXEXPORT
#define NIXAPI __declspec(dllexport)
#else
#define NIXAPI __declspec(dllimport)
#endif
#pragma warning(disable: 4250 4251)
//workaround for missing ssize_t on windows
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#else
#define NIXAPI
#endif
#ifdef _MSC_VER
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif
<commit_msg>[win] only typedef ssize_t if not yet defined<commit_after>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <[email protected]>
#ifdef _WIN32
#ifdef NIXEXPORT
#define NIXAPI __declspec(dllexport)
#else
#define NIXAPI __declspec(dllimport)
#endif
#pragma warning(disable: 4250 4251)
//workaround for missing ssize_t on windows
#ifndef ssize_t
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#else
#define NIXAPI
#endif
#ifdef _MSC_VER
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <[email protected]>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Scene.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <libxml/parser.h>
using namespace FFLD;
using namespace std;
Scene::Scene() : width_(0), height_(0), depth_(0)
{
}
Scene::Scene(int width, int height, int depth, const string & filename,
const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}
bool Scene::empty() const
{
return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
objects().empty();
}
template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
return Result();
istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
Result result;
// iss >> result;
result = iss.str()
return result;
}
Scene::Scene(const string & filename)
{
// const string Names[20] =
// {
// "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
// "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
// "train", "tvmonitor"
// };
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
const string Poses[4] =
{
"Frontal", "Left", "Rear", "Right"
};
xmlDoc * doc = xmlParseFile(filename.c_str());
if (doc == NULL) {
cerr << "Could not open " << filename << endl;
return;
}
xmlNodePtr cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
// Full path
size_t last = filename.rfind('/');
if (last != string::npos) {
last = filename.rfind('/', last - 1);
if (last != string::npos)
filename_ = filename.substr(0, last) + "/JPEGImages/" +
content<string>(cur);
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
width_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
height_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
depth_ = content<int>(cur2);
cur2 = cur2->next;
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
objects_.push_back(Object());
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
const string * iter =
find(Names, Names + 80, content<string>(cur2));
std::cout << "XML NAME: " << content<string>(cur2) << std::endl;
if (iter != Names + 80)
objects_.back().setName(static_cast<Object::Name>(iter - Names));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
const string * iter =
find(Poses, Poses + 4, content<string>(cur2));
if (iter != Poses + 4)
objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
objects_.back().setTruncated(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
objects_.back().setDifficult(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
Rectangle bndbox;
xmlNodePtr cur3 = cur2->xmlChildrenNode;
while (cur3 != NULL) {
if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
bndbox.setX(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
bndbox.setY(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
bndbox.setWidth(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
bndbox.setHeight(content<int>(cur3));
cur3 = cur3->next;
}
// Only set the bounding box if all values have been assigned
if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
bndbox.setX(bndbox.x() - 1);
bndbox.setY(bndbox.y() - 1);
bndbox.setWidth(bndbox.width() - bndbox.x());
bndbox.setHeight(bndbox.height() - bndbox.y());
objects_.back().setBndbox(bndbox);
}
}
cur2 = cur2->next;
}
}
cur = cur->next;
}
xmlFreeDoc(doc);
}
int Scene::width() const
{
return width_;
}
void Scene::setWidth(int width)
{
width_ = width;
}
int Scene::height() const
{
return height_;
}
void Scene::setHeight(int height)
{
height_ = height;
}
int Scene::depth() const
{
return depth_;
}
void Scene::setDepth(int depth)
{
depth_ = depth;
}
const string & Scene::filename() const
{
return filename_;
}
void Scene::setFilename(const string &filename)
{
filename_ = filename;
}
const vector<Object> & Scene::objects() const
{
return objects_;
}
void Scene::setObjects(const vector<Object> &objects)
{
objects_ = objects;
}
ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
<< scene.objects().size() << ' ' << scene.filename() << endl;
for (int i = 0; i < scene.objects().size(); ++i)
os << scene.objects()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Scene & scene)
{
int width, height, depth, nbObjects;
is >> width >> height >> depth >> nbObjects;
is.get(); // Remove the space
string filename;
getline(is, filename);
vector<Object> objects(nbObjects);
for (int i = 0; i < nbObjects; ++i)
is >> objects[i];
if (!is) {
scene = Scene();
return is;
}
scene = Scene(width, height, depth, filename, objects);
return is;
}
<commit_msg>use noskiws for Scene.ccp:content<commit_after>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <[email protected]>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Scene.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <libxml/parser.h>
using namespace FFLD;
using namespace std;
Scene::Scene() : width_(0), height_(0), depth_(0)
{
}
Scene::Scene(int width, int height, int depth, const string & filename,
const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}
bool Scene::empty() const
{
return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
objects().empty();
}
template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
return Result();
istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
Result result;
iss >> noskipws >> result;
return result;
}
Scene::Scene(const string & filename)
{
// const string Names[20] =
// {
// "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
// "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
// "train", "tvmonitor"
// };
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
const string Poses[4] =
{
"Frontal", "Left", "Rear", "Right"
};
xmlDoc * doc = xmlParseFile(filename.c_str());
if (doc == NULL) {
cerr << "Could not open " << filename << endl;
return;
}
xmlNodePtr cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
// Full path
size_t last = filename.rfind('/');
if (last != string::npos) {
last = filename.rfind('/', last - 1);
if (last != string::npos)
filename_ = filename.substr(0, last) + "/JPEGImages/" +
content<string>(cur);
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
width_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
height_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
depth_ = content<int>(cur2);
cur2 = cur2->next;
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
objects_.push_back(Object());
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
const string * iter =
find(Names, Names + 80, content<string>(cur2));
if (iter != Names + 80)
objects_.back().setName(static_cast<Object::Name>(iter - Names));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
const string * iter =
find(Poses, Poses + 4, content<string>(cur2));
if (iter != Poses + 4)
objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
objects_.back().setTruncated(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
objects_.back().setDifficult(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
Rectangle bndbox;
xmlNodePtr cur3 = cur2->xmlChildrenNode;
while (cur3 != NULL) {
if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
bndbox.setX(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
bndbox.setY(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
bndbox.setWidth(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
bndbox.setHeight(content<int>(cur3));
cur3 = cur3->next;
}
// Only set the bounding box if all values have been assigned
if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
bndbox.setX(bndbox.x() - 1);
bndbox.setY(bndbox.y() - 1);
bndbox.setWidth(bndbox.width() - bndbox.x());
bndbox.setHeight(bndbox.height() - bndbox.y());
objects_.back().setBndbox(bndbox);
}
}
cur2 = cur2->next;
}
}
cur = cur->next;
}
xmlFreeDoc(doc);
}
int Scene::width() const
{
return width_;
}
void Scene::setWidth(int width)
{
width_ = width;
}
int Scene::height() const
{
return height_;
}
void Scene::setHeight(int height)
{
height_ = height;
}
int Scene::depth() const
{
return depth_;
}
void Scene::setDepth(int depth)
{
depth_ = depth;
}
const string & Scene::filename() const
{
return filename_;
}
void Scene::setFilename(const string &filename)
{
filename_ = filename;
}
const vector<Object> & Scene::objects() const
{
return objects_;
}
void Scene::setObjects(const vector<Object> &objects)
{
objects_ = objects;
}
ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
<< scene.objects().size() << ' ' << scene.filename() << endl;
for (int i = 0; i < scene.objects().size(); ++i)
os << scene.objects()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Scene & scene)
{
int width, height, depth, nbObjects;
is >> width >> height >> depth >> nbObjects;
is.get(); // Remove the space
string filename;
getline(is, filename);
vector<Object> objects(nbObjects);
for (int i = 0; i < nbObjects; ++i)
is >> objects[i];
if (!is) {
scene = Scene();
return is;
}
scene = Scene(width, height, depth, filename, objects);
return is;
}
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <[email protected]>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Scene.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <libxml/parser.h>
using namespace FFLD;
using namespace std;
Scene::Scene() : width_(0), height_(0), depth_(0)
{
}
Scene::Scene(int width, int height, int depth, const string & filename,
const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}
bool Scene::empty() const
{
return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
objects().empty();
}
template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
return Result();
istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
Result result;
iss >> result;
return result;
}
Scene::Scene(const string & filename)
{
// const string Names[20] =
// {
// "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
// "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
// "train", "tvmonitor"
// };
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
const string Poses[4] =
{
"Frontal", "Left", "Rear", "Right"
};
xmlDoc * doc = xmlParseFile(filename.c_str());
if (doc == NULL) {
cerr << "Could not open " << filename << endl;
return;
}
xmlNodePtr cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
// Full path
size_t last = filename.rfind('/');
if (last != string::npos) {
last = filename.rfind('/', last - 1);
if (last != string::npos)
filename_ = filename.substr(0, last) + "/JPEGImages/" +
content<string>(cur);
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
width_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
height_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
depth_ = content<int>(cur2);
cur2 = cur2->next;
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
objects_.push_back(Object());
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
const string * iter =
find(Names, Names + 80, content<string>(cur2));
if (iter != Names + 80)
objects_.back().setName(static_cast<Object::Name>(iter - Names));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
const string * iter =
find(Poses, Poses + 4, content<string>(cur2));
if (iter != Poses + 4)
objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
objects_.back().setTruncated(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
objects_.back().setDifficult(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
Rectangle bndbox;
xmlNodePtr cur3 = cur2->xmlChildrenNode;
while (cur3 != NULL) {
if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
bndbox.setX(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
bndbox.setY(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
bndbox.setWidth(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
bndbox.setHeight(content<int>(cur3));
cur3 = cur3->next;
}
// Only set the bounding box if all values have been assigned
if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
bndbox.setX(bndbox.x() - 1);
bndbox.setY(bndbox.y() - 1);
bndbox.setWidth(bndbox.width() - bndbox.x());
bndbox.setHeight(bndbox.height() - bndbox.y());
objects_.back().setBndbox(bndbox);
}
}
cur2 = cur2->next;
}
}
cur = cur->next;
}
xmlFreeDoc(doc);
}
int Scene::width() const
{
return width_;
}
void Scene::setWidth(int width)
{
width_ = width;
}
int Scene::height() const
{
return height_;
}
void Scene::setHeight(int height)
{
height_ = height;
}
int Scene::depth() const
{
return depth_;
}
void Scene::setDepth(int depth)
{
depth_ = depth;
}
const string & Scene::filename() const
{
return filename_;
}
void Scene::setFilename(const string &filename)
{
filename_ = filename;
}
const vector<Object> & Scene::objects() const
{
return objects_;
}
void Scene::setObjects(const vector<Object> &objects)
{
objects_ = objects;
}
ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
<< scene.objects().size() << ' ' << scene.filename() << endl;
for (int i = 0; i < scene.objects().size(); ++i)
os << scene.objects()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Scene & scene)
{
int width, height, depth, nbObjects;
is >> width >> height >> depth >> nbObjects;
is.get(); // Remove the space
string filename;
getline(is, filename);
vector<Object> objects(nbObjects);
for (int i = 0; i < nbObjects; ++i)
is >> objects[i];
if (!is) {
scene = Scene();
return is;
}
scene = Scene(width, height, depth, filename, objects);
return is;
}
<commit_msg>noskipws<commit_after>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <[email protected]>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Scene.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <libxml/parser.h>
using namespace FFLD;
using namespace std;
Scene::Scene() : width_(0), height_(0), depth_(0)
{
}
Scene::Scene(int width, int height, int depth, const string & filename,
const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}
bool Scene::empty() const
{
return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
objects().empty();
}
template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
return Result();
istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
Result result;
iss >> noskipws >> result;
return result;
}
Scene::Scene(const string & filename)
{
// const string Names[20] =
// {
// "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
// "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
// "train", "tvmonitor"
// };
const string Names[80] =
{
"airplane", "apple", "backpack", "banana", "baseball bat",
"baseball glove", "bear", "bed", "bench", "bicycle", "bird",
"boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
"car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
"cow", "cup", "dining table", "dog", "donut", "elephant",
"fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
"handbag", "horse", "hot dog", "keyboard", "kite", "knife",
"laptop", "microwave", "motorcycle", "mouse", "orange",
"oven", "parking meter", "person", "pizza", "potted plant",
"refrigerator", "remote", "sandwich", "scissors", "sheep",
"sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
"stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
"tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
"truck", "tv", "umbrella", "vase", "wine", "zebra"
};
const string Poses[4] =
{
"Frontal", "Left", "Rear", "Right"
};
xmlDoc * doc = xmlParseFile(filename.c_str());
if (doc == NULL) {
cerr << "Could not open " << filename << endl;
return;
}
xmlNodePtr cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
xmlFreeDoc(doc);
cerr << "Could not open " << filename << endl;
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
// Full path
size_t last = filename.rfind('/');
if (last != string::npos) {
last = filename.rfind('/', last - 1);
if (last != string::npos)
filename_ = filename.substr(0, last) + "/JPEGImages/" +
content<string>(cur);
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
width_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
height_ = content<int>(cur2);
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
depth_ = content<int>(cur2);
cur2 = cur2->next;
}
}
else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
objects_.push_back(Object());
xmlNodePtr cur2 = cur->xmlChildrenNode;
while (cur2 != NULL) {
if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
const string * iter =
find(Names, Names + 80, content<string>(cur2));
if (iter != Names + 80)
objects_.back().setName(static_cast<Object::Name>(iter - Names));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
const string * iter =
find(Poses, Poses + 4, content<string>(cur2));
if (iter != Poses + 4)
objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
objects_.back().setTruncated(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
objects_.back().setDifficult(content<bool>(cur2));
}
else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
Rectangle bndbox;
xmlNodePtr cur3 = cur2->xmlChildrenNode;
while (cur3 != NULL) {
if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
bndbox.setX(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
bndbox.setY(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
bndbox.setWidth(content<int>(cur3));
else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
bndbox.setHeight(content<int>(cur3));
cur3 = cur3->next;
}
// Only set the bounding box if all values have been assigned
if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
bndbox.setX(bndbox.x() - 1);
bndbox.setY(bndbox.y() - 1);
bndbox.setWidth(bndbox.width() - bndbox.x());
bndbox.setHeight(bndbox.height() - bndbox.y());
objects_.back().setBndbox(bndbox);
}
}
cur2 = cur2->next;
}
}
cur = cur->next;
}
xmlFreeDoc(doc);
}
int Scene::width() const
{
return width_;
}
void Scene::setWidth(int width)
{
width_ = width;
}
int Scene::height() const
{
return height_;
}
void Scene::setHeight(int height)
{
height_ = height;
}
int Scene::depth() const
{
return depth_;
}
void Scene::setDepth(int depth)
{
depth_ = depth;
}
const string & Scene::filename() const
{
return filename_;
}
void Scene::setFilename(const string &filename)
{
filename_ = filename;
}
const vector<Object> & Scene::objects() const
{
return objects_;
}
void Scene::setObjects(const vector<Object> &objects)
{
objects_ = objects;
}
ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
<< scene.objects().size() << ' ' << scene.filename() << endl;
for (int i = 0; i < scene.objects().size(); ++i)
os << scene.objects()[i] << endl;
return os;
}
istream & FFLD::operator>>(istream & is, Scene & scene)
{
int width, height, depth, nbObjects;
is >> width >> height >> depth >> nbObjects;
is.get(); // Remove the space
string filename;
getline(is, filename);
vector<Object> objects(nbObjects);
for (int i = 0; i < nbObjects; ++i)
is >> objects[i];
if (!is) {
scene = Scene();
return is;
}
scene = Scene(width, height, depth, filename, objects);
return is;
}
<|endoftext|> |
<commit_before>#include "State.h"
Context::Context(char * cursor) : start(0) {
this->cursor = cursor;
this->currentState = new OpenDTA();
}
void * Context::advance() {
for (start = cursor; cursor && *cursor != '>'; cursor++);
if (cursor && *cursor == '>') {
cursor++;
strncpy(buffer, start, cursor - start);
buffer[cursor-start]='\0';
}
while(this->currentState->check(this->buffer))
{
currentState->process(*this);
this->currentState = this->currentState->advanceState();
}
return (void *)(start);
}
// OpenDTA State
bool OpenDTA::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenDTA::advanceState() {
return new OpenHeader();
}
// OpenHeader State
bool OpenHeader::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenHeader::advanceState()
{
return new OpenRelease();
}
// OpenRelease State
State * OpenRelease::advanceState() {
return new OpenByteOrder();
}
bool OpenRelease::process(Context & ctx)
{
string version = ctx.getChars(3);
cout << version << endl;
switch(strtol(version.c_str(), NULL, 10))
{
case 117:
ctx.hdr.fileRelease = R117;
break;
default:
ctx.hdr.fileRelease = R117;
break;
}
ctx.advance(); // CONTENT
ctx.advance(); // </release>
return true;
}
// OpenByteOrder State
State * OpenByteOrder::advanceState()
{
return new OpenK();
}
bool OpenByteOrder::process(Context & ctx)
{
string byteOrder = ctx.getChars(3);
if (!strcasecmp(byteOrder.c_str(), XML_LSF))
ctx.hdr.fileByteorder = LSF;
else
ctx.hdr.fileByteorder = MSF;
ctx.advance(); // ORDER
ctx.advance(); // </byteorder>
return true;
}
// OpenK State
State * OpenK::advanceState()
{
return new OpenN();
}
bool OpenK::process(Context & ctx)
{
if (ctx.hdr.fileByteorder == LSF) {
char * ctxbuf = (char *) ctx.advance();
switch(ctx.hdr.fileRelease)
{
// 4 byte
case R119:
case R118:
ctx.hdr.variables = GetLSF<int>(ctxbuf, 4);
break;
// 2 byte
case R117:
ctx.hdr.variables = GetLSF<int>(ctxbuf, 2);
break;
default:
break;
}
} else {
// MSF not implemented yet
}
ctx.advance();
return true;
}
// OpenN State
State * OpenN::advanceState()
{
return new OpenLabel();
}
bool OpenN::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
if (ctx.hdr.fileByteorder == LSF)
{
switch(ctx.hdr.fileRelease)
{
// 8 byte
case R119:
case R118:
ctx.hdr.observations = GetLSF<uint64_t>(ctxbuf, 8);
break;
// 4 byte
case R117:
ctx.hdr.observations = GetLSF<int>(ctxbuf, 4);
break;
default:
break;
}
}
else
{
// MSF not implemented yet
}
cout << "Observations: " << ctx.hdr.observations << endl;
ctx.advance();
return true;
}
// OpenLabel State
State * OpenLabel::advanceState()
{
return new OpenTimeStamp();
}
bool OpenLabel::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
int label_count = 0;
if (ctx.hdr.fileByteorder == LSF)
{
switch(ctx.hdr.fileRelease)
{
case R119:
case R118:
label_count = GetLSF<int>(ctxbuf, 2);
ctx.hdr.datalabel.assign(&ctxbuf[2],label_count);
break;
case R117:
label_count = GetLSF<int>(ctxbuf, 1);
ctx.hdr.datalabel.assign(&ctxbuf[1],label_count);
break;
default:
break;
}
}
else
{
// not implemented yet
}
cout << "Label Count: " << label_count << " " << ctx.hdr.datalabel << endl;
ctx.advance();
return true;
}
State * OpenTimeStamp::advanceState()
{
return new CloseHeader();
}
bool OpenTimeStamp::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
int label_count = 0;
switch(ctx.hdr.fileRelease)
{
case R119:
case R118:
case R117:
label_count = GetLSF<int>(ctxbuf, 1);
ctx.hdr.ts.assign(&ctxbuf[1],label_count);
break;
}
cout << "timeStamp: " << ctx.hdr.ts << endl;
ctx.advance();
return true;
}
State * CloseHeader::advanceState()
{
return new OpenMap();
}
bool CloseHeader::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenMap::advanceState()
{
return new OpenMap();
}
bool OpenMap::process(Context & ctx)
{
#define MAP_COUNT 14
char * ctxbuf = (char *)ctx.advance();
int i, j;
cout << "here" << endl;
string map_names[] = {
"stata_data_start",
"map",
"variable_types",
"varnames",
"sortlist",
"formats",
"value_label_names",
"variable_labels",
"characteristics",
"data",
"strls",
"value_labels",
"stata_data_end",
"eof"
};
for (i = 0; i < MAP_COUNT; i++, ctxbuf += 8)
{
ctx.map.stata_map[map_names[i].c_str()] = GetLSF<uint64_t>(ctxbuf, 8);
cout << map_names[i].c_str() << " " << ctx.map.stata_map[map_names[i].c_str()] << endl;
}
return true;
}<commit_msg>done with vartypes<commit_after>#include "State.h"
Context::Context(char * cursor) : start(0) {
this->cursor = cursor;
this->currentState = new OpenDTA();
}
void * Context::advance() {
for (start = cursor; cursor && *cursor != '>'; cursor++);
if (cursor && *cursor == '>') {
cursor++;
strncpy(buffer, start, cursor - start);
buffer[cursor-start]='\0';
}
while(this->currentState->check(this->buffer))
{
currentState->process(*this);
this->currentState = this->currentState->advanceState();
}
return (void *)(start);
}
// OpenDTA State
bool OpenDTA::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenDTA::advanceState() {
return new OpenHeader();
}
// OpenHeader State
bool OpenHeader::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenHeader::advanceState()
{
return new OpenRelease();
}
// OpenRelease State
State * OpenRelease::advanceState() {
return new OpenByteOrder();
}
bool OpenRelease::process(Context & ctx)
{
string version = ctx.getChars(3);
cout << version << endl;
switch(strtol(version.c_str(), NULL, 10))
{
case 117:
ctx.hdr.fileRelease = R117;
break;
default:
ctx.hdr.fileRelease = R117;
break;
}
ctx.advance(); // CONTENT
ctx.advance(); // </release>
return true;
}
// OpenByteOrder State
State * OpenByteOrder::advanceState()
{
return new OpenK();
}
bool OpenByteOrder::process(Context & ctx)
{
string byteOrder = ctx.getChars(3);
if (!strcasecmp(byteOrder.c_str(), XML_LSF))
ctx.hdr.fileByteorder = LSF;
else
ctx.hdr.fileByteorder = MSF;
ctx.advance(); // ORDER
ctx.advance(); // </byteorder>
return true;
}
// OpenK State
State * OpenK::advanceState()
{
return new OpenN();
}
bool OpenK::process(Context & ctx)
{
if (ctx.hdr.fileByteorder == LSF) {
char * ctxbuf = (char *) ctx.advance();
switch(ctx.hdr.fileRelease)
{
// 4 byte
case R119:
case R118:
ctx.hdr.variables = GetLSF<int>(ctxbuf, 4);
break;
// 2 byte
case R117:
ctx.hdr.variables = GetLSF<int>(ctxbuf, 2);
break;
default:
break;
}
} else {
// MSF not implemented yet
}
ctx.advance();
return true;
}
// OpenN State
State * OpenN::advanceState()
{
return new OpenLabel();
}
bool OpenN::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
if (ctx.hdr.fileByteorder == LSF)
{
switch(ctx.hdr.fileRelease)
{
// 8 byte
case R119:
case R118:
ctx.hdr.observations = GetLSF<uint64_t>(ctxbuf, 8);
break;
// 4 byte
case R117:
ctx.hdr.observations = GetLSF<int>(ctxbuf, 4);
break;
default:
break;
}
}
else
{
// MSF not implemented yet
}
cout << "Observations: " << ctx.hdr.observations << endl;
ctx.advance();
return true;
}
// OpenLabel State
State * OpenLabel::advanceState()
{
return new OpenTimeStamp();
}
bool OpenLabel::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
int label_count = 0;
if (ctx.hdr.fileByteorder == LSF)
{
switch(ctx.hdr.fileRelease)
{
case R119:
case R118:
label_count = GetLSF<int>(ctxbuf, 2);
ctx.hdr.datalabel.assign(&ctxbuf[2],label_count);
break;
case R117:
label_count = GetLSF<int>(ctxbuf, 1);
ctx.hdr.datalabel.assign(&ctxbuf[1],label_count);
break;
default:
break;
}
}
else
{
// not implemented yet
}
cout << "Label Count: " << label_count << " " << ctx.hdr.datalabel << endl;
ctx.advance();
return true;
}
State * OpenTimeStamp::advanceState()
{
return new CloseHeader();
}
bool OpenTimeStamp::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
int label_count = 0;
switch(ctx.hdr.fileRelease)
{
case R119:
case R118:
case R117:
label_count = GetLSF<int>(ctxbuf, 1);
ctx.hdr.ts.assign(&ctxbuf[1],label_count);
break;
}
cout << "timeStamp: " << ctx.hdr.ts << endl;
ctx.advance();
return true;
}
State * CloseHeader::advanceState()
{
return new OpenMap();
}
bool CloseHeader::process(Context & ctx)
{
ctx.advance();
return true;
}
State * OpenMap::advanceState()
{
return new OpenVarTypes();
}
bool OpenMap::process(Context & ctx)
{
#define MAP_COUNT 14
char * ctxbuf = (char *)ctx.advance();
int i, j;
string map_names[] = {
"stata_data_start",
"map",
"variable_types",
"varnames",
"sortlist",
"formats",
"value_label_names",
"variable_labels",
"characteristics",
"data",
"strls",
"value_labels",
"stata_data_end",
"eof"
};
for (i = 0; i < MAP_COUNT; i++, ctxbuf += 8)
ctx.map.stata_map[map_names[i].c_str()] = GetLSF<uint64_t>(ctxbuf, 8);
ctx.advance();
return true;
}
State * OpenVarTypes::advanceState()
{
cout << "done vartypes" << endl;
return NULL; //new OpenMap();
}
bool OpenVarTypes::process(Context & ctx)
{
char * ctxbuf = (char *) ctx.advance();
int curr = 0;
if (ctx.hdr.fileByteorder == LSF) {
while (*ctxbuf != '<') {
StataVariables * sta = new StataVariables();
sta->type = GetLSF<unsigned int>(ctxbuf, 2);
cout << "type: " << sta->type << endl;
ctx.vList.push_back(sta);
ctxbuf += 2;
curr++;
}
} else {
// not implemented yet
}
ctx.advance();
return true;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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: Ali Saidi
*/
#include "base/trace.hh"
#include "dev/arm/rv_ctrl.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
RealViewCtrl::RealViewCtrl(Params *p)
: BasicPioDevice(p)
{
pioSize = 0xD4;
}
Tick
RealViewCtrl::read(PacketPtr pkt)
{
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 4);
Addr daddr = pkt->getAddr() - pioAddr;
pkt->allocate();
switch(daddr) {
case ProcId:
pkt->set(params()->proc_id);
break;
case Clock24:
Tick clk;
clk = (Tick)(curTick() / (24 * SimClock::Float::MHz));
pkt->set((uint32_t)(clk));
break;
case Clock100:
Tick clk100;
clk100 = (Tick)(curTick() / (100 * SimClock::Float::MHz));
pkt->set((uint32_t)(clk100));
break;
case Flash:
pkt->set<uint32_t>(0);
break;
case Clcd:
pkt->set<uint32_t>(0x00001F00);
break;
case Osc0:
pkt->set<uint32_t>(0x00012C5C);
break;
case Osc1:
pkt->set<uint32_t>(0x00002CC0);
break;
case Osc2:
pkt->set<uint32_t>(0x00002C75);
break;
case Osc3:
pkt->set<uint32_t>(0x00020211);
break;
case Osc4:
pkt->set<uint32_t>(0x00002C75);
break;
case Lock:
pkt->set<uint32_t>(sysLock);
break;
default:
panic("Tried to read RealView I/O at offset %#x that doesn't exist\n", daddr);
break;
}
pkt->makeAtomicResponse();
return pioDelay;
}
Tick
RealViewCtrl::write(PacketPtr pkt)
{
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
Addr daddr = pkt->getAddr() - pioAddr;
switch (daddr) {
case Flash:
case Clcd:
case Osc0:
case Osc1:
case Osc2:
case Osc3:
case Osc4:
break;
case Lock:
sysLock.lockVal = pkt->get<uint16_t>();
break;
default:
panic("Tried to write RVIO at offset %#x that doesn't exist\n", daddr);
break;
}
pkt->makeAtomicResponse();
return pioDelay;
}
void
RealViewCtrl::serialize(std::ostream &os)
{
}
void
RealViewCtrl::unserialize(Checkpoint *cp, const std::string §ion)
{
}
RealViewCtrl *
RealViewCtrlParams::create()
{
return new RealViewCtrl(this);
}
<commit_msg>RealView: Fix the 24 and 100MHz clocks which were providing incorrect values.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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: Ali Saidi
*/
#include "base/trace.hh"
#include "dev/arm/rv_ctrl.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
RealViewCtrl::RealViewCtrl(Params *p)
: BasicPioDevice(p)
{
pioSize = 0xD4;
}
Tick
RealViewCtrl::read(PacketPtr pkt)
{
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 4);
Addr daddr = pkt->getAddr() - pioAddr;
pkt->allocate();
switch(daddr) {
case ProcId:
pkt->set(params()->proc_id);
break;
case Clock24:
Tick clk;
clk = (Tick)(curTick() / (24 * SimClock::Int::us));
pkt->set((uint32_t)(clk));
break;
case Clock100:
Tick clk100;
clk100 = (Tick)(curTick() / (100 * SimClock::Int::us));
pkt->set((uint32_t)(clk100));
break;
case Flash:
pkt->set<uint32_t>(0);
break;
case Clcd:
pkt->set<uint32_t>(0x00001F00);
break;
case Osc0:
pkt->set<uint32_t>(0x00012C5C);
break;
case Osc1:
pkt->set<uint32_t>(0x00002CC0);
break;
case Osc2:
pkt->set<uint32_t>(0x00002C75);
break;
case Osc3:
pkt->set<uint32_t>(0x00020211);
break;
case Osc4:
pkt->set<uint32_t>(0x00002C75);
break;
case Lock:
pkt->set<uint32_t>(sysLock);
break;
default:
panic("Tried to read RealView I/O at offset %#x that doesn't exist\n", daddr);
break;
}
pkt->makeAtomicResponse();
return pioDelay;
}
Tick
RealViewCtrl::write(PacketPtr pkt)
{
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
Addr daddr = pkt->getAddr() - pioAddr;
switch (daddr) {
case Flash:
case Clcd:
case Osc0:
case Osc1:
case Osc2:
case Osc3:
case Osc4:
break;
case Lock:
sysLock.lockVal = pkt->get<uint16_t>();
break;
default:
panic("Tried to write RVIO at offset %#x that doesn't exist\n", daddr);
break;
}
pkt->makeAtomicResponse();
return pioDelay;
}
void
RealViewCtrl::serialize(std::ostream &os)
{
}
void
RealViewCtrl::unserialize(Checkpoint *cp, const std::string §ion)
{
}
RealViewCtrl *
RealViewCtrlParams::create()
{
return new RealViewCtrl(this);
}
<|endoftext|> |
<commit_before>///
/// @file tos_counters.hpp
/// @brief This file contains functions to initialize, update and query
/// the special tree data structure used for summing the
/// number of unsieved elements in the Lagarias-Miller-Odlyzko
/// and Deleglise-Rivat prime summing algorithms.
///
/// The implementation is a modified version of the
/// algorithm described in the paper:
///
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial method,
/// Revista do DETUA, vol. 4, no. 6, March 2006, pp. 767-768.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef TOS_COUNTERS_HPP
#define TOS_COUNTERS_HPP
#include <stdint.h>
#include <vector>
namespace primesum {
/// Initialize the counters from the sieve array.
/// @pre segment_size is a power of 2.
/// @pre sieve[i] = 1 for unsieved elements and sieve[i] = 0
/// for crossed-off elements.
/// Runtime: O(N log N).
///
template <typename T1, typename T2>
inline void cnt_finit(const T1& sieve,
std::vector<T2>& cnt,
int64_t low,
int64_t segment_size)
{
for (T2 i = 0; i < segment_size; i++)
{
cnt[i] = (low + i) * sieve[i];
for (T2 k = (i + 1) & ~i, j = i; k >>= 1; j &= j - 1)
cnt[i] += cnt[j - 1];
}
}
/// Update the counters after that an element has been
/// crossed-off for the first time in the sieve array.
/// @pre segment_size is a power of 2.
/// Runtime: O(log N).
///
template <typename T>
inline void cnt_update(std::vector<T>& cnt,
int64_t n,
int64_t low,
int64_t segment_size)
{
int64_t i = n - low;
do
{
cnt[i] -= n;
i |= i + 1;
}
while (i < segment_size);
}
/// Get the sum of the unsieved elements <= pos
/// in the current segment (sieve array).
/// Runtime: O(log N).
///
template <typename T>
inline T cnt_query(const std::vector<T>& cnt, int64_t pos)
{
T sum = cnt[pos++];
for (; pos &= pos - 1; sum += cnt[pos - 1]);
return sum;
}
} // namespace
#endif
<commit_msg>Silence compiler warning<commit_after>///
/// @file tos_counters.hpp
/// @brief This file contains functions to initialize, update and query
/// the special tree data structure used for summing the
/// number of unsieved elements in the Lagarias-Miller-Odlyzko
/// and Deleglise-Rivat prime summing algorithms.
///
/// The implementation is a modified version of the
/// algorithm described in the paper:
///
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial method,
/// Revista do DETUA, vol. 4, no. 6, March 2006, pp. 767-768.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef TOS_COUNTERS_HPP
#define TOS_COUNTERS_HPP
#include <stdint.h>
#include <vector>
namespace primesum {
/// Initialize the counters from the sieve array.
/// @pre segment_size is a power of 2.
/// @pre sieve[i] = 1 for unsieved elements and sieve[i] = 0
/// for crossed-off elements.
/// Runtime: O(N log N).
///
template <typename T1, typename T2>
inline void cnt_finit(const T1& sieve,
std::vector<T2>& cnt,
int64_t low,
int64_t segment_size)
{
for (int64_t i = 0; i < segment_size; i++)
{
cnt[i] = (low + i) * sieve[i];
for (int64_t k = (i + 1) & ~i, j = i; k >>= 1; j &= j - 1)
cnt[i] += cnt[j - 1];
}
}
/// Update the counters after that an element has been
/// crossed-off for the first time in the sieve array.
/// @pre segment_size is a power of 2.
/// Runtime: O(log N).
///
template <typename T>
inline void cnt_update(std::vector<T>& cnt,
int64_t n,
int64_t low,
int64_t segment_size)
{
int64_t i = n - low;
do
{
cnt[i] -= n;
i |= i + 1;
}
while (i < segment_size);
}
/// Get the sum of the unsieved elements <= pos
/// in the current segment (sieve array).
/// Runtime: O(log N).
///
template <typename T>
inline T cnt_query(const std::vector<T>& cnt, int64_t pos)
{
T sum = cnt[pos++];
for (; pos &= pos - 1; sum += cnt[pos - 1]);
return sum;
}
} // namespace
#endif
<|endoftext|> |
<commit_before>#ifndef VSMC_RNG_AES_HPP
#define VSMC_RNG_AES_HPP
#include <vsmc/rng/ars.hpp>
#define VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(N, val) \
template <> struct AESRoundConstantValue< N > : \
public cxx11::integral_constant<int, val > {};
/// \brief AESEngine default blocks
/// \ingroup Config
#ifndef VSMC_RNG_AES_BLOCKS
#define VSMC_RNG_AES_BLOCKS 1
#endif
namespace vsmc {
namespace internal {
template <std::size_t N> struct AESRoundConstantValue;
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(0, 0x01)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(1, 0x02)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(2, 0x04)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(3, 0x08)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(4, 0x10)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(5, 0x20)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(6, 0x40)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(7, 0x80)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(8, 0x1B)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(9, 0x36)
} // namespace vsmc::internal
namespace traits {
/// \brief AESEngine round constant traits
/// \ingroup Traits
///
/// The specialization for `N = 0` to `N = 9` are used as the ten round
/// constants in AESEngine
template <std::size_t N>
struct AESRoundConstantTrait :
public ::vsmc::internal::AESRoundConstantValue<N> {};
} // namespace traits
/// \brief Default AESEngine key sequence generator
/// \ingroup R123RNG
template <std::size_t R>
class AESKeySeq
{
public :
typedef StaticVector<__m128i, R + 1> key_seq_type;
AESKeySeq () : tmp0_(), tmp1_(), tmp2_() {}
void generate (const __m128i &ukey, key_seq_type &key_seq)
{
tmp0_ = ukey;
generate<0>(key_seq, cxx11::true_type());
}
private :
__m128i tmp0_;
__m128i tmp1_;
__m128i tmp2_;
template <std::size_t>
void generate (key_seq_type &key_seq, cxx11::false_type)
{key_seq.back() = tmp0_;}
template <std::size_t N>
void generate (key_seq_type &key_seq, cxx11::true_type)
{
key_seq[Position<N>()] = tmp0_;
tmp1_ = _mm_aeskeygenassist_si128(tmp0_,
traits::AESRoundConstantTrait<N>::value);
generate_assit();
generate<N + 1>(key_seq, cxx11::integral_constant<bool, N + 1 < R>());
}
void generate_assit ()
{
tmp1_ = _mm_shuffle_epi32 (tmp1_ ,0xFF);
tmp2_ = _mm_slli_si128 (tmp0_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp2_ = _mm_slli_si128 (tmp2_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp2_ = _mm_slli_si128 (tmp2_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp0_ = _mm_xor_si128 (tmp0_, tmp1_);
}
}; // class AESKeySeq
/// \brief AES RNG engine reimplemented
/// \ingroup R123RNG
///
/// \details
/// This is a reimplementation of the algorithm AES as described in [Parallel
/// Random Numbers: As Easy as 1, 2, 3][r123paper] and implemented in
/// [Random123][r123lib].
///
/// [r123paper]:http://sc11.supercomputing.org/schedule/event_detail.php?evid=pap274
/// [r123lib]: https://www.deshawresearch.com/resources_random123.html
///
/// The algorithm is almost identical to the original. Compared to
/// `r123:Engine<r123::AESNI4x32>`, when using the default constructor or the
/// one with a single seed, the output shall be exactly the same for the first
/// \f$2^32\f$ iterations. Further iterations may produce different results, as
/// vSMC increment the counter slightly differently, but it still cover the
/// same range and has the same period as the original.
///
/// The implementation however is much different the original. See the source
/// for how the ARSEngine is used as the base of AESEngine, and how to
/// implement similar engines.
///
/// The second template argument specify the number of blocks
///
/// \sa AESKeySeq.
/// \sa ARSEngine.
template <typename ResultType, std::size_t Blocks = VSMC_RNG_AES_BLOCKS>
class AESEngine : public ARSEngine<ResultType, Blocks, 10, AESKeySeq<10> >
{
typedef ARSEngine<ResultType, Blocks, 10, AESKeySeq<10> > base;
public :
explicit AESEngine (ResultType s = 0) : base(s) {}
template <typename SeedSeq>
explicit AESEngine (SeedSeq &seq, typename cxx11::enable_if<
!internal::is_seed_seq<SeedSeq, ResultType>::value>::type * =
VSMC_NULLPTR) : base(seq) {}
}; // class AESEngine
/// \brief AES RNG engine returning 32-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<uint32_t> AES4x32;
/// \brief AES RNG engine returning 64-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<uint64_t> AES2x64;
/// \brief AES RNG engine returning 128-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<__m128i> AES1x128;
/// \brief AES RNG engine returning 32-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 1> AES4x32_1;
/// \brief AES RNG engine returning 64-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 1> AES2x64_1;
/// \brief AES RNG engine returning 128-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 1> AES1x128_1;
/// \brief AES RNG engine returning 32-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 2> AES4x32_2;
/// \brief AES RNG engine returning 64-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 2> AES2x64_2;
/// \brief AES RNG engine returning 128-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 2> AES1x128_2;
/// \brief AES RNG engine returning 32-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 4> AES4x32_4;
/// \brief AES RNG engine returning 64-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 4> AES2x64_4;
/// \brief AES RNG engine returning 128-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 4> AES1x128_4;
/// \brief AES RNG engine returning 32-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 8> AES4x32_8;
/// \brief AES RNG engine returning 64-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 8> AES2x64_8;
/// \brief AES RNG engine returning 128-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 8> AES1x128_8;
} // namespace vsmc
#endif // VSMC_RNG_AES_HPP
<commit_msg>doc fix<commit_after>#ifndef VSMC_RNG_AES_HPP
#define VSMC_RNG_AES_HPP
#include <vsmc/rng/ars.hpp>
#define VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(N, val) \
template <> struct AESRoundConstantValue< N > : \
public cxx11::integral_constant<int, val > {};
/// \brief AESEngine default blocks
/// \ingroup Config
#ifndef VSMC_RNG_AES_BLOCKS
#define VSMC_RNG_AES_BLOCKS 1
#endif
namespace vsmc {
namespace internal {
template <std::size_t N> struct AESRoundConstantValue;
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(0, 0x01)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(1, 0x02)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(2, 0x04)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(3, 0x08)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(4, 0x10)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(5, 0x20)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(6, 0x40)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(7, 0x80)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(8, 0x1B)
VSMC_DEFINE_RNG_AES_ROUND_CONSTANT(9, 0x36)
} // namespace vsmc::internal
namespace traits {
/// \brief AESEngine round constant traits
/// \ingroup Traits
///
/// The specialization for `N = 0` to `N = 9` are used as the ten round
/// constants in AESEngine
template <std::size_t N>
struct AESRoundConstantTrait :
public ::vsmc::internal::AESRoundConstantValue<N> {};
} // namespace traits
/// \brief AESEngine key sequence generator
/// \ingroup R123RNG
template <std::size_t R>
class AESKeySeq
{
public :
typedef StaticVector<__m128i, R + 1> key_seq_type;
AESKeySeq () : tmp0_(), tmp1_(), tmp2_() {}
void generate (const __m128i &ukey, key_seq_type &key_seq)
{
tmp0_ = ukey;
generate<0>(key_seq, cxx11::true_type());
}
private :
__m128i tmp0_;
__m128i tmp1_;
__m128i tmp2_;
template <std::size_t>
void generate (key_seq_type &key_seq, cxx11::false_type)
{key_seq.back() = tmp0_;}
template <std::size_t N>
void generate (key_seq_type &key_seq, cxx11::true_type)
{
key_seq[Position<N>()] = tmp0_;
tmp1_ = _mm_aeskeygenassist_si128(tmp0_,
traits::AESRoundConstantTrait<N>::value);
generate_assit();
generate<N + 1>(key_seq, cxx11::integral_constant<bool, N + 1 < R>());
}
void generate_assit ()
{
tmp1_ = _mm_shuffle_epi32 (tmp1_ ,0xFF);
tmp2_ = _mm_slli_si128 (tmp0_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp2_ = _mm_slli_si128 (tmp2_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp2_ = _mm_slli_si128 (tmp2_, 0x04);
tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);
tmp0_ = _mm_xor_si128 (tmp0_, tmp1_);
}
}; // class AESKeySeq
/// \brief AES RNG engine reimplemented
/// \ingroup R123RNG
///
/// \details
/// This is a reimplementation of the algorithm AES as described in [Parallel
/// Random Numbers: As Easy as 1, 2, 3][r123paper] and implemented in
/// [Random123][r123lib].
///
/// [r123paper]:http://sc11.supercomputing.org/schedule/event_detail.php?evid=pap274
/// [r123lib]: https://www.deshawresearch.com/resources_random123.html
///
/// The algorithm is almost identical to the original. Compared to
/// `r123:Engine<r123::AESNI4x32>`, when using the default constructor or the
/// one with a single seed, the output shall be exactly the same for the first
/// \f$2^32\f$ iterations. Further iterations may produce different results, as
/// vSMC increment the counter slightly differently, but it still cover the
/// same range and has the same period as the original.
///
/// The implementation however is much different the original. See the source
/// for how the ARSEngine is used as the base of AESEngine, and how to
/// implement similar engines.
///
/// The second template argument specify the number of blocks
///
/// \sa AESKeySeq.
/// \sa ARSEngine.
template <typename ResultType, std::size_t Blocks = VSMC_RNG_AES_BLOCKS>
class AESEngine : public ARSEngine<ResultType, Blocks, 10, AESKeySeq<10> >
{
typedef ARSEngine<ResultType, Blocks, 10, AESKeySeq<10> > base;
public :
explicit AESEngine (ResultType s = 0) : base(s) {}
template <typename SeedSeq>
explicit AESEngine (SeedSeq &seq, typename cxx11::enable_if<
!internal::is_seed_seq<SeedSeq, ResultType>::value>::type * =
VSMC_NULLPTR) : base(seq) {}
}; // class AESEngine
/// \brief AES RNG engine returning 32-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<uint32_t> AES4x32;
/// \brief AES RNG engine returning 64-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<uint64_t> AES2x64;
/// \brief AES RNG engine returning 128-bits integers with default blocks
/// \ingroup R123RNG
typedef AESEngine<__m128i> AES1x128;
/// \brief AES RNG engine returning 32-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 1> AES4x32_1;
/// \brief AES RNG engine returning 64-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 1> AES2x64_1;
/// \brief AES RNG engine returning 128-bits integers with 1 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 1> AES1x128_1;
/// \brief AES RNG engine returning 32-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 2> AES4x32_2;
/// \brief AES RNG engine returning 64-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 2> AES2x64_2;
/// \brief AES RNG engine returning 128-bits integers with 2 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 2> AES1x128_2;
/// \brief AES RNG engine returning 32-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 4> AES4x32_4;
/// \brief AES RNG engine returning 64-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 4> AES2x64_4;
/// \brief AES RNG engine returning 128-bits integers with 4 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 4> AES1x128_4;
/// \brief AES RNG engine returning 32-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<uint32_t, 8> AES4x32_8;
/// \brief AES RNG engine returning 64-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<uint64_t, 8> AES2x64_8;
/// \brief AES RNG engine returning 128-bits integers with 8 block
/// \ingroup R123RNG
typedef AESEngine<__m128i, 8> AES1x128_8;
} // namespace vsmc
#endif // VSMC_RNG_AES_HPP
<|endoftext|> |
<commit_before>#ifndef VG_FEATURES_HPP_INCLUDED
#define VG_FEATURES_HPP_INCLUDED
/// \file
/// features.hpp: utilities for working with Feature and FeatureType from the VG Protobuf
#include <vg.pb.h>
#include "json2pb.h"
#include <vector>
#include <string>
#include <type_traits>
namespace vg {
using namespace std;
// We template over Alignment and MultipathAlignment because they have the same
// features methods but no base class.
// We use a Protobuf-style pointer-for-mutable interface. All the mutator
// methods take pointers, while the read methods take const references.
////////////////////////////////////////////////////////////////////////
// API
////////////////////////////////////////////////////////////////////////
/// Determine if the given alignment has ther given tag feature, or any
/// instances of the given numerical or list feature.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
bool has_feature(const Item& item, const FeatureType& feature);
template<typename Item>
bool has_feature(const Item* item, const FeatureType& feature);
/// Get the numerical value of the given single-value feature on the given
/// item. Throws an error if the feature isn't present. Should not be called on
/// multi-valued features.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
double get_feature(const Item& item, const FeatureType& feature);
template<typename Item>
double get_feature(const Item* item, const FeatureType& feature);
/// Get the numerical values of the given multi-valued feature, or an empty
/// vector if the feature isn't present.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
vector<double> get_features(const Item& item, const FeatureType& feature);
template<typename Item>
vector<double> get_features(const Item* item, const FeatureType& feature);
/// Add the given tag feature to the given item, assuming it is not present already.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature);
/// Add the given tag feature if the given flkag is set, assuming it is not present already.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const bool& flag);
/// Append the given value to the given multi-valued feature, or add the given
/// value for the given single-valued feature it it is not yet set.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const double& value);
/// Append the given value to the given multi-valued feature, or add the given
/// value for the given single-valued feature it it is not yet set.
/// Coerces integral values to double.
template<typename Item, typename Integral,
typename Enabled = typename enable_if<is_integral<Integral>::value && !is_same<Integral, bool>::value>::type>
void add_feature(Item* item, const FeatureType& feature, const Integral& value);
/// Set the given tag feature to the given value, even if it is already present.
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const bool& flag);
/// Set the given single-valued feature to the given value, adding it if it doesn't exist yet.
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const double& value);
/// Set the given single-valued feature to the given value, adding it if it doesn't exist yet.
/// Coerces integral values to double.
template<typename Item, typename Integral,
typename Enabled = typename enable_if<is_integral<Integral>::value && !is_same<Integral, bool>::value>::type>
void set_feature(Item* item, const FeatureType& feature, const Integral& value);
/// Remove the given tag frature, or all instances of the given single- or
/// multi-valued feature, form the given item, if any are present.
template<typename Item>
void remove_feature(Item* item, const FeatureType& feature);
////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////
template<typename Item, typename Enabled>
bool has_feature(const Item& item, const FeatureType& feature) {
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, return it
return true;
}
}
// Otherwise we didn't find it
return false;
}
template<typename Item>
bool has_feature(const Item* item, const FeatureType& feature) {
return has_feature(*item, feature);
}
template<typename Item, typename Enabled>
double get_feature(const Item& item, const FeatureType& feature) {
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, return it
return record.value();
}
}
// Otherwise we didn't find it
throw runtime_error("Feature " + to_string(feature) + " not found in " + pb2json(item));
}
template<typename Item>
double get_feature(const Item* item, const FeatureType& feature) {
return get_feature(*item, feature);
}
template<typename Item, typename Enabled>
vector<double> get_features(const Item& item, const FeatureType& feature) {
vector<double> to_return;
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, gather it up
to_return.push_back(record.value());
}
}
return to_return;
}
template<typename Item>
vector<double> get_features(const Item* item, const FeatureType& feature) {
return get_features(*item, feature);
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature) {
Feature* added = item->add_feature();
added->set_type(feature);
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const bool& flag) {
if (flag) {
// If the flag is true, actually add it.
add_feature(item, feature);
}
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const double& value) {
// Always add it
Feature* added = item->add_feature();
added->set_type(feature);
// And set the value
added->set_value(value);
}
template<typename Item, typename Integral, typename Enabled>
void add_feature(Item* item, const FeatureType& feature, const Integral& value) {
add_feature(item, feature, (double)value);
}
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const bool& flag) {
remove_feature(item, feature);
add_feature(item, feature, flag);
}
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const double& value) {
remove_feature(item, feature);
add_feature(item, feature, value);
}
template<typename Item, typename Integral, typename Enabled>
void set_feature(Item* item, const FeatureType& feature, const Integral& value) {
set_feature(item, feature, (double)value);
}
template<typename Item>
void remove_feature(Item* item, const FeatureType& feature) {
for (size_t i = 0; i < item->feature_size();) {
if (item->feature(i).type() == feature) {
// We need to remove it
// So swap it last
item->mutable_feature()->SwapElements(i, item->feature_size());
// And remove the last element
item->mutable_feature()->RemoveLast();
// Stay here so we can look at what we swapped into this position
} else {
// Don't need to remove anything, so look at the next item
i++;
}
}
}
}
#endif
<commit_msg>Fix off-by-1 error in feature removal<commit_after>#ifndef VG_FEATURES_HPP_INCLUDED
#define VG_FEATURES_HPP_INCLUDED
/// \file
/// features.hpp: utilities for working with Feature and FeatureType from the VG Protobuf
#include <vg.pb.h>
#include "json2pb.h"
#include <vector>
#include <string>
#include <type_traits>
namespace vg {
using namespace std;
// We template over Alignment and MultipathAlignment because they have the same
// features methods but no base class.
// We use a Protobuf-style pointer-for-mutable interface. All the mutator
// methods take pointers, while the read methods take const references.
////////////////////////////////////////////////////////////////////////
// API
////////////////////////////////////////////////////////////////////////
/// Determine if the given alignment has ther given tag feature, or any
/// instances of the given numerical or list feature.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
bool has_feature(const Item& item, const FeatureType& feature);
template<typename Item>
bool has_feature(const Item* item, const FeatureType& feature);
/// Get the numerical value of the given single-value feature on the given
/// item. Throws an error if the feature isn't present. Should not be called on
/// multi-valued features.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
double get_feature(const Item& item, const FeatureType& feature);
template<typename Item>
double get_feature(const Item* item, const FeatureType& feature);
/// Get the numerical values of the given multi-valued feature, or an empty
/// vector if the feature isn't present.
template<typename Item, typename Enabled = typename enable_if<!is_pointer<Item>::value>::type>
vector<double> get_features(const Item& item, const FeatureType& feature);
template<typename Item>
vector<double> get_features(const Item* item, const FeatureType& feature);
/// Add the given tag feature to the given item, assuming it is not present already.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature);
/// Add the given tag feature if the given flkag is set, assuming it is not present already.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const bool& flag);
/// Append the given value to the given multi-valued feature, or add the given
/// value for the given single-valued feature it it is not yet set.
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const double& value);
/// Append the given value to the given multi-valued feature, or add the given
/// value for the given single-valued feature it it is not yet set.
/// Coerces integral values to double.
template<typename Item, typename Integral,
typename Enabled = typename enable_if<is_integral<Integral>::value && !is_same<Integral, bool>::value>::type>
void add_feature(Item* item, const FeatureType& feature, const Integral& value);
/// Set the given tag feature to the given value, even if it is already present.
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const bool& flag);
/// Set the given single-valued feature to the given value, adding it if it doesn't exist yet.
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const double& value);
/// Set the given single-valued feature to the given value, adding it if it doesn't exist yet.
/// Coerces integral values to double.
template<typename Item, typename Integral,
typename Enabled = typename enable_if<is_integral<Integral>::value && !is_same<Integral, bool>::value>::type>
void set_feature(Item* item, const FeatureType& feature, const Integral& value);
/// Remove the given tag frature, or all instances of the given single- or
/// multi-valued feature, form the given item, if any are present.
template<typename Item>
void remove_feature(Item* item, const FeatureType& feature);
////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////
template<typename Item, typename Enabled>
bool has_feature(const Item& item, const FeatureType& feature) {
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, return it
return true;
}
}
// Otherwise we didn't find it
return false;
}
template<typename Item>
bool has_feature(const Item* item, const FeatureType& feature) {
return has_feature(*item, feature);
}
template<typename Item, typename Enabled>
double get_feature(const Item& item, const FeatureType& feature) {
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, return it
return record.value();
}
}
// Otherwise we didn't find it
throw runtime_error("Feature " + to_string(feature) + " not found in " + pb2json(item));
}
template<typename Item>
double get_feature(const Item* item, const FeatureType& feature) {
return get_feature(*item, feature);
}
template<typename Item, typename Enabled>
vector<double> get_features(const Item& item, const FeatureType& feature) {
vector<double> to_return;
for (auto& record : item.feature()) {
// Do a linear scan
if (record.type() == feature) {
// And if we find it, gather it up
to_return.push_back(record.value());
}
}
return to_return;
}
template<typename Item>
vector<double> get_features(const Item* item, const FeatureType& feature) {
return get_features(*item, feature);
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature) {
Feature* added = item->add_feature();
added->set_type(feature);
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const bool& flag) {
if (flag) {
// If the flag is true, actually add it.
add_feature(item, feature);
}
}
template<typename Item>
void add_feature(Item* item, const FeatureType& feature, const double& value) {
// Always add it
Feature* added = item->add_feature();
added->set_type(feature);
// And set the value
added->set_value(value);
}
template<typename Item, typename Integral, typename Enabled>
void add_feature(Item* item, const FeatureType& feature, const Integral& value) {
add_feature(item, feature, (double)value);
}
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const bool& flag) {
remove_feature(item, feature);
add_feature(item, feature, flag);
}
template<typename Item>
void set_feature(Item* item, const FeatureType& feature, const double& value) {
remove_feature(item, feature);
add_feature(item, feature, value);
}
template<typename Item, typename Integral, typename Enabled>
void set_feature(Item* item, const FeatureType& feature, const Integral& value) {
set_feature(item, feature, (double)value);
}
template<typename Item>
void remove_feature(Item* item, const FeatureType& feature) {
for (size_t i = 0; i < item->feature_size();) {
if (item->feature(i).type() == feature) {
// We need to remove it
// So swap it last
item->mutable_feature()->SwapElements(i, item->feature_size() - 1);
// And remove the last element
item->mutable_feature()->RemoveLast();
// Stay here so we can look at what we swapped into this position
} else {
// Don't need to remove anything, so look at the next item
i++;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
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 author 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 "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::wstring safe_convert(std::string const& s)
{
try
{
return libtorrent::utf8_wchar(s);
}
catch (std::exception)
{
std::wstring ret;
for (const char* i = &*s.begin(); i < &*s.end(); ++i)
{
wchar_t c;
c = '.';
std::mbtowc(&c, i, 1);
ret += c;
}
return ret;
}
}
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
ret.resize(size-1);
return ret;
}
catch(std::exception)
{
return s;
}
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(safe_convert(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
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 author 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 "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::wstring safe_convert(std::string const& s)
{
try
{
return libtorrent::utf8_wchar(s);
}
catch (std::exception)
{
std::wstring ret;
for (const char* i = &*s.begin(); i < &*s.end(); ++i)
{
wchar_t c;
c = '.';
std::mbtowc(&c, i, 1);
ret += c;
}
return ret;
}
}
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(safe_convert(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>#include "openmc/finalize.h"
#include "openmc/bank.h"
#include "openmc/capi.h"
#include "openmc/cmfd_solver.h"
#include "openmc/constants.h"
#include "openmc/cross_sections.h"
#include "openmc/dagmc.h"
#include "openmc/eigenvalue.h"
#include "openmc/geometry.h"
#include "openmc/geometry_aux.h"
#include "openmc/material.h"
#include "openmc/mesh.h"
#include "openmc/message_passing.h"
#include "openmc/nuclide.h"
#include "openmc/photon.h"
#include "openmc/random_lcg.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/source.h"
#include "openmc/surface.h"
#include "openmc/thermal.h"
#include "openmc/timer.h"
#include "openmc/tallies/tally.h"
#include "openmc/volume_calc.h"
#include "xtensor/xview.hpp"
namespace openmc {
void free_memory()
{
free_memory_geometry();
free_memory_surfaces();
free_memory_material();
free_memory_volume();
free_memory_simulation();
free_memory_photon();
free_memory_settings();
free_memory_thermal();
library_clear();
nuclides_clear();
free_memory_source();
free_memory_mesh();
free_memory_tally();
free_memory_bank();
free_memory_cmfd();
#ifdef DAGMC
free_memory_dagmc();
#endif
}
}
using namespace openmc;
int openmc_finalize()
{
// Clear results
openmc_reset();
// Reset timers
reset_timers();
// Reset global variables
settings::assume_separate = false;
settings::check_overlaps = false;
settings::confidence_intervals = false;
settings::create_fission_neutrons = true;
settings::electron_treatment = ELECTRON_LED;
settings::energy_cutoff = {0.0, 1000.0, 0.0, 0.0};
settings::entropy_on = false;
settings::gen_per_batch = 1;
settings::legendre_to_tabular = true;
settings::legendre_to_tabular_points = -1;
settings::n_particles = -1;
settings::output_summary = true;
settings::output_tallies = true;
settings::particle_restart_run = false;
settings::photon_transport = false;
settings::reduce_tallies = true;
settings::res_scat_on = false;
settings::res_scat_method = ResScatMethod::rvs;
settings::res_scat_energy_min = 0.01;
settings::res_scat_energy_max = 1000.0;
settings::restart_run = false;
settings::run_CE = true;
settings::run_mode = -1;
settings::dagmc = false;
settings::source_latest = false;
settings::source_separate = false;
settings::source_write = true;
settings::survival_biasing = false;
settings::temperature_default = 293.6;
settings::temperature_method = TEMPERATURE_NEAREST;
settings::temperature_multipole = false;
settings::temperature_range = {0.0, 0.0};
settings::temperature_tolerance = 10.0;
settings::trigger_on = false;
settings::trigger_predict = false;
settings::trigger_batch_interval = 1;
settings::ufs_on = false;
settings::urr_ptables_on = true;
settings::verbosity = 7;
settings::weight_cutoff = 0.25;
settings::weight_survive = 1.0;
settings::write_all_tracks = false;
settings::write_initial_source = false;
simulation::keff = 1.0;
simulation::n_lost_particles = 0;
simulation::satisfy_triggers = false;
simulation::total_gen = 0;
simulation::entropy_mesh = nullptr;
simulation::ufs_mesh = nullptr;
data::energy_max = {INFTY, INFTY};
data::energy_min = {0.0, 0.0};
data::temperature_min = 0.0;
data::temperature_max = INFTY;
model::root_universe = -1;
openmc::openmc_set_seed(DEFAULT_SEED);
// Deallocate arrays
free_memory();
// Free all MPI types
#ifdef OPENMC_MPI
int init_called;
MPI_Initialized(&init_called);
if (init_called) MPI_Type_free(&mpi::bank);
#endif
return 0;
}
int openmc_reset()
{
for (auto& t : model::tallies) {
t->reset();
}
// Reset global tallies
simulation::n_realizations = 0;
xt::view(simulation::global_tallies, xt::all()) = 0.0;
simulation::k_col_abs = 0.0;
simulation::k_col_tra = 0.0;
simulation::k_abs_tra = 0.0;
simulation::k_sum = {0.0, 0.0};
return 0;
}
int openmc_hard_reset()
{
// Reset all tallies and timers
openmc_reset();
reset_timers();
// Reset total generations and keff guess
simulation::keff = 1.0;
simulation::total_gen = 0;
// Reset the random number generator state
openmc::openmc_set_seed(DEFAULT_SEED);
return 0;
}
<commit_msg>Better conditional for call to MPI_Type_free (thanks Cliff Dugal)<commit_after>#include "openmc/finalize.h"
#include "openmc/bank.h"
#include "openmc/capi.h"
#include "openmc/cmfd_solver.h"
#include "openmc/constants.h"
#include "openmc/cross_sections.h"
#include "openmc/dagmc.h"
#include "openmc/eigenvalue.h"
#include "openmc/geometry.h"
#include "openmc/geometry_aux.h"
#include "openmc/material.h"
#include "openmc/mesh.h"
#include "openmc/message_passing.h"
#include "openmc/nuclide.h"
#include "openmc/photon.h"
#include "openmc/random_lcg.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/source.h"
#include "openmc/surface.h"
#include "openmc/thermal.h"
#include "openmc/timer.h"
#include "openmc/tallies/tally.h"
#include "openmc/volume_calc.h"
#include "xtensor/xview.hpp"
namespace openmc {
void free_memory()
{
free_memory_geometry();
free_memory_surfaces();
free_memory_material();
free_memory_volume();
free_memory_simulation();
free_memory_photon();
free_memory_settings();
free_memory_thermal();
library_clear();
nuclides_clear();
free_memory_source();
free_memory_mesh();
free_memory_tally();
free_memory_bank();
free_memory_cmfd();
#ifdef DAGMC
free_memory_dagmc();
#endif
}
}
using namespace openmc;
int openmc_finalize()
{
// Clear results
openmc_reset();
// Reset timers
reset_timers();
// Reset global variables
settings::assume_separate = false;
settings::check_overlaps = false;
settings::confidence_intervals = false;
settings::create_fission_neutrons = true;
settings::electron_treatment = ELECTRON_LED;
settings::energy_cutoff = {0.0, 1000.0, 0.0, 0.0};
settings::entropy_on = false;
settings::gen_per_batch = 1;
settings::legendre_to_tabular = true;
settings::legendre_to_tabular_points = -1;
settings::n_particles = -1;
settings::output_summary = true;
settings::output_tallies = true;
settings::particle_restart_run = false;
settings::photon_transport = false;
settings::reduce_tallies = true;
settings::res_scat_on = false;
settings::res_scat_method = ResScatMethod::rvs;
settings::res_scat_energy_min = 0.01;
settings::res_scat_energy_max = 1000.0;
settings::restart_run = false;
settings::run_CE = true;
settings::run_mode = -1;
settings::dagmc = false;
settings::source_latest = false;
settings::source_separate = false;
settings::source_write = true;
settings::survival_biasing = false;
settings::temperature_default = 293.6;
settings::temperature_method = TEMPERATURE_NEAREST;
settings::temperature_multipole = false;
settings::temperature_range = {0.0, 0.0};
settings::temperature_tolerance = 10.0;
settings::trigger_on = false;
settings::trigger_predict = false;
settings::trigger_batch_interval = 1;
settings::ufs_on = false;
settings::urr_ptables_on = true;
settings::verbosity = 7;
settings::weight_cutoff = 0.25;
settings::weight_survive = 1.0;
settings::write_all_tracks = false;
settings::write_initial_source = false;
simulation::keff = 1.0;
simulation::n_lost_particles = 0;
simulation::satisfy_triggers = false;
simulation::total_gen = 0;
simulation::entropy_mesh = nullptr;
simulation::ufs_mesh = nullptr;
data::energy_max = {INFTY, INFTY};
data::energy_min = {0.0, 0.0};
data::temperature_min = 0.0;
data::temperature_max = INFTY;
model::root_universe = -1;
openmc::openmc_set_seed(DEFAULT_SEED);
// Deallocate arrays
free_memory();
// Free all MPI types
#ifdef OPENMC_MPI
if (mpi::bank != MPI_DATATYPE_NULL) MPI_Type_free(&mpi::bank);
#endif
return 0;
}
int openmc_reset()
{
for (auto& t : model::tallies) {
t->reset();
}
// Reset global tallies
simulation::n_realizations = 0;
xt::view(simulation::global_tallies, xt::all()) = 0.0;
simulation::k_col_abs = 0.0;
simulation::k_col_tra = 0.0;
simulation::k_abs_tra = 0.0;
simulation::k_sum = {0.0, 0.0};
return 0;
}
int openmc_hard_reset()
{
// Reset all tallies and timers
openmc_reset();
reset_timers();
// Reset total generations and keff guess
simulation::keff = 1.0;
simulation::total_gen = 0;
// Reset the random number generator state
openmc::openmc_set_seed(DEFAULT_SEED);
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include "image_reader.hh"
#include <tiffio.h>
#include <iostream>
namespace mapnik
{
class TiffReader : public ImageReader
{
private:
std::string file_name_;
int read_method_;
unsigned width_;
unsigned height_;
int rows_per_strip_;
int tile_width_;
int tile_height_;
public:
enum
{
generic=1,
stripped,
tiled
};
explicit TiffReader(const std::string& file_name);
virtual ~TiffReader();
unsigned width() const;
unsigned height() const;
void read(unsigned x,unsigned y,ImageData32& image);
private:
TiffReader(const TiffReader&);
TiffReader& operator=(const TiffReader&);
void init();
void read_generic(unsigned x,unsigned y,ImageData32& image);
void read_stripped(unsigned x,unsigned y,ImageData32& image);
void read_tiled(unsigned x,unsigned y,ImageData32& image);
};
namespace
{
ImageReader* createTiffReader(const std::string& file)
{
return new TiffReader(file);
}
const bool registered = register_image_reader("tiff",createTiffReader);
}
TiffReader::TiffReader(const std::string& file_name)
: file_name_(file_name),
read_method_(generic),
width_(0),
height_(0),
rows_per_strip_(0),
tile_width_(0),
tile_height_(0)
{
try
{
init();
}
catch (ImageReaderException& ex)
{
std::cerr<<ex.what()<<std::endl;
throw;
}
}
void TiffReader::init()
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (!tif) throw ImageReaderException("cannot open "+file_name_);
char msg[1024];
if (TIFFRGBAImageOK(tif,msg))
{
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width_);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height_);
if (TIFFIsTiled(tif))
{
TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width_);
TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height_);
read_method_=tiled;
}
else if (TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rows_per_strip_)!=0)
{
read_method_=stripped;
}
TIFFClose(tif);
}
else
{
TIFFClose(tif);
throw ImageReaderException(msg);
}
}
TiffReader::~TiffReader()
{
//
}
unsigned TiffReader::width() const
{
return width_;
}
unsigned TiffReader::height() const
{
return height_;
}
void TiffReader::read(unsigned x,unsigned y,ImageData32& image)
{
if (read_method_==stripped)
{
read_stripped(x,y,image);
}
else if (read_method_==tiled)
{
read_tiled(x,y,image);
}
else
{
read_generic(x,y,image);
}
}
void TiffReader::read_generic(unsigned x,unsigned y,ImageData32& image)
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
//todo
TIFFClose(tif);
}
}
void TiffReader::read_tiled(unsigned x0,unsigned y0,ImageData32& image)
{
TIFF* tif=TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
uint32* buf = (uint32*)_TIFFmalloc(tile_width_*tile_height_*sizeof(uint32));
int width=image.width();
int height=image.height();
int start_y=(y0/tile_height_)*tile_height_;
int end_y=((y0+height)/tile_height_+1)*tile_height_;
int start_x=(x0/tile_width_)*tile_width_;
int end_x=((x0+width)/tile_width_+1)*tile_width_;
int row=0;
int tx0,tx1,ty0,ty1;
for (int y=start_y;y<end_y;y+=tile_height_)
{
ty0=std::max(y0,(unsigned)y)-y;
ty1=std::min(height+y0,(unsigned)(y+tile_height_))-y;
for (int x=start_x;x<end_x;x+=tile_width_)
{
if (!TIFFReadRGBATile(tif,x,y,buf)) break;
tx0=std::max(x0,(unsigned)x)-x;
tx1=std::min(width+x0,(unsigned)(x+tile_width_))-x;
row=y+ty0-y0;
for (int n=tile_height_-ty0-1;n>=tile_height_-ty1;--n)
{
image.setRow(row,x+tx0-x0,x+tx1-x0,(const unsigned*)&buf[n*tile_width_+tx0]);
++row;
}
}
}
_TIFFfree(buf);
TIFFClose(tif);
}
}
void TiffReader::read_stripped(unsigned x,unsigned y,ImageData32& image)
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
uint32* buf = (uint32*)_TIFFmalloc(width_*rows_per_strip_*sizeof(uint32));
int width=image.width();
int height=image.height();
int start=(y/rows_per_strip_)*rows_per_strip_;
int end=((y+height)/rows_per_strip_+1)*rows_per_strip_;
int extra=y%rows_per_strip_;
int j=-extra;
int w=std::min(width_,(unsigned)width);//todo should be unsigned
for (int row=start; row < end; row+=rows_per_strip_)
{
if (!TIFFReadRGBAStrip(tif,row,buf)) break;
for (int i=rows_per_strip_-1;i>=0;--i)
{
if (j>=0 && j<height)
{
image.setRow(j,(const unsigned*)&buf[i*width_+x],
w*sizeof(uint32));
}
++j;
}
}
_TIFFfree(buf);
TIFFClose(tif);
}
}
}
<commit_msg>fixed: reading tiled and stripped TIFFs<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include "image_reader.hh"
#include <tiffio.h>
#include <iostream>
namespace mapnik
{
class TiffReader : public ImageReader
{
private:
std::string file_name_;
int read_method_;
unsigned width_;
unsigned height_;
int rows_per_strip_;
int tile_width_;
int tile_height_;
public:
enum
{
generic=1,
stripped,
tiled
};
explicit TiffReader(const std::string& file_name);
virtual ~TiffReader();
unsigned width() const;
unsigned height() const;
void read(unsigned x,unsigned y,ImageData32& image);
private:
TiffReader(const TiffReader&);
TiffReader& operator=(const TiffReader&);
void init();
void read_generic(unsigned x,unsigned y,ImageData32& image);
void read_stripped(unsigned x,unsigned y,ImageData32& image);
void read_tiled(unsigned x,unsigned y,ImageData32& image);
};
namespace
{
ImageReader* createTiffReader(const std::string& file)
{
return new TiffReader(file);
}
const bool registered = register_image_reader("tiff",createTiffReader);
}
TiffReader::TiffReader(const std::string& file_name)
: file_name_(file_name),
read_method_(generic),
width_(0),
height_(0),
rows_per_strip_(0),
tile_width_(0),
tile_height_(0)
{
try
{
init();
}
catch (ImageReaderException& ex)
{
std::cerr<<ex.what()<<std::endl;
throw;
}
}
void TiffReader::init()
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (!tif) throw ImageReaderException("cannot open "+file_name_);
char msg[1024];
if (TIFFRGBAImageOK(tif,msg))
{
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width_);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height_);
if (TIFFIsTiled(tif))
{
TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width_);
TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height_);
read_method_=tiled;
}
else if (TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rows_per_strip_)!=0)
{
read_method_=stripped;
}
TIFFClose(tif);
}
else
{
TIFFClose(tif);
throw ImageReaderException(msg);
}
}
TiffReader::~TiffReader()
{
//
}
unsigned TiffReader::width() const
{
return width_;
}
unsigned TiffReader::height() const
{
return height_;
}
void TiffReader::read(unsigned x,unsigned y,ImageData32& image)
{
if (read_method_==stripped)
{
read_stripped(x,y,image);
}
else if (read_method_==tiled)
{
read_tiled(x,y,image);
}
else
{
read_generic(x,y,image);
}
}
void TiffReader::read_generic(unsigned x,unsigned y,ImageData32& image)
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
std::cerr<<"TODO:tiff is not stripped or tiled\n";
TIFFClose(tif);
}
}
void TiffReader::read_tiled(unsigned x0,unsigned y0,ImageData32& image)
{
TIFF* tif=TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
uint32* buf = (uint32*)_TIFFmalloc(tile_width_*tile_height_*sizeof(uint32));
int width=image.width();
int height=image.height();
int start_y=(y0/tile_height_)*tile_height_;
int end_y=((y0+height)/tile_height_+1)*tile_height_;
bool bottomtiles=((unsigned)end_y > height_)?true:false;
int start_x=(x0/tile_width_)*tile_width_;
int end_x=((x0+width)/tile_width_+1)*tile_width_;
int row,tx0,tx1,ty0,ty1;
for (int y=start_y;y<end_y;y+=tile_height_)
{
ty0=std::max(y0,(unsigned)y)-y;
ty1=std::min(height+y0,(unsigned)(y+tile_height_))-y;
int n0=bottomtiles ? 0:(tile_height_-ty1);
int n1=bottomtiles ? (ty1-ty0-1):(tile_height_-ty0-1);
for (int x=start_x;x<end_x;x+=tile_width_)
{
if (!TIFFReadRGBATile(tif,x,y,buf)) break;
tx0=std::max(x0,(unsigned)x);
tx1=std::min(width+x0,(unsigned)(x+tile_width_));
row=y+ty0-y0;
for (int n=n1;n>=n0;--n)
{
image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*tile_width_+tx0-x]);
++row;
}
}
}
_TIFFfree(buf);
TIFFClose(tif);
}
}
void TiffReader::read_stripped(unsigned x0,unsigned y0,ImageData32& image)
{
TIFF* tif = TIFFOpen(file_name_.c_str(), "r");
if (tif)
{
uint32* buf = (uint32*)_TIFFmalloc(width_*rows_per_strip_*sizeof(uint32));
int width=image.width();
int height=image.height();
int start_y=(y0/rows_per_strip_)*rows_per_strip_;
int end_y=((y0+height)/rows_per_strip_+1)*rows_per_strip_;
bool laststrip=((unsigned)end_y > height_)?true:false;
int row,tx0,tx1,ty0,ty1;
tx0=x0;
tx1=std::min(width+x0,(unsigned)width_);
for (unsigned y=start_y; y < end_y; y+=rows_per_strip_)
{
ty0=std::max(y0,y)-y;
ty1=std::min(height+y0,y+rows_per_strip_)-y;
memset(buf,0xff,width_*rows_per_strip_*sizeof(uint32));
if (!TIFFReadRGBAStrip(tif,y,buf)) break;
row=y+ty0-y0;
int n0=laststrip ? 0:(rows_per_strip_-ty1);
int n1=laststrip ? (ty1-ty0-1):(rows_per_strip_-ty0-1);
for (int n=n1;n>=n0;--n)
{
image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*width_+tx0]);
++row;
}
}
_TIFFfree(buf);
TIFFClose(tif);
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <QFileDialog>
#include <QMessageBox>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/image_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace image_annotator {
namespace fs = boost::filesystem;
namespace { //anonymous
static const std::vector<std::string> kDirExtensions = {
".jpg", ".png", ".bmp", ".tif", ".jpeg",
".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};
} // anonymous namespace
MainWindow::MainWindow(QWidget *parent)
: annotations_(new ImageAnnotationList)
, scene_(new QGraphicsScene)
, ui_(new Ui::MainWidget)
, species_controls_(new SpeciesControls(this))
, image_files_() {
ui_->setupUi(this);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
setStyleSheet("QPushButton { background-color: rgb(230, 230, 230);"
"border-style: outset; border-radius: 5px; border-width: 2px; "
"border-color: grey; padding: 6px;}"
"QPushButton:pressed{background-color: rgb(190, 190, 190); "
"border-style: outset; border-radius: 5px;"
"border-width: 2px; border-color: grey; padding: 6px;}");
ui_->next->setEnabled(false);
ui_->prev->setEnabled(false);
ui_->saveAnnotations->setEnabled(false);
ui_->imageSlider->setEnabled(false);
ui_->sideBarLayout->addWidget(species_controls_.get());
QObject::connect(species_controls_.get(),
SIGNAL(individualAdded(std::string, std::string)),
this, SLOT(addIndividual(std::string, std::string)));
}
void MainWindow::on_next_clicked() {
int next_val = ui_->imageSlider->value() + 1;
if(next_val <= ui_->imageSlider->maximum()) {
ui_->imageSlider->setValue(next_val);
}
}
void MainWindow::on_prev_clicked() {
int prev_val = ui_->imageSlider->value() - 1;
if(prev_val >= ui_->imageSlider->minimum()) {
ui_->imageSlider->setValue(prev_val);
}
}
void MainWindow::on_loadImageDir_clicked() {
QString image_dir = QFileDialog::getExistingDirectory(this,
"Select an image directory.");
if(!image_dir.isEmpty()) {
onLoadDirectorySuccess(image_dir);
}
}
void MainWindow::on_saveAnnotations_clicked() {
if(image_files_.size() > 0) {
annotations_->write(image_files_);
}
}
void MainWindow::on_imageSlider_valueChanged() {
scene_->clear();
ui_->idSelection->clear();
ui_->speciesValue->setText("");
ui_->subspeciesValue->setText("");
#ifdef _WIN32
QString filename(image_files_[ui_->imageSlider->value()].string().c_str());
#else
QString filename(image_files_[ui_->imageSlider->value()].c_str());
#endif
QImage current(filename);
if(!current.isNull()) {
scene_->addPixmap(QPixmap::fromImage(current));
scene_->setSceneRect(current.rect());
ui_->imageWindow->setScene(scene_.get());
ui_->imageWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
ui_->imageWindow->show();
ui_->fileNameValue->setText(filename);
fs::path img_path(filename.toStdString());
auto annotations =
annotations_->getImageAnnotations(img_path.filename());
for(auto annotation : annotations) {
if(ui_->showAnnotations->isChecked()) {
auto region = new AnnotatedRegion<ImageAnnotation>(
annotation->id_, annotation, current.rect());
scene_->addItem(region);
}
ui_->idSelection->addItem(QString::number(annotation->id_));
}
species_controls_->resetCounts();
auto counts = annotations_->getCounts(filename.toStdString());
for(auto it = counts.begin(); it != counts.end(); it++) {
species_controls_->setCount(it->second, it->first);
}
}
else {
QMessageBox err;
err.critical(0, "Error", std::string(
std::string("Error loading image ")
+ filename.toStdString()
+ std::string(".")).c_str());
}
}
void MainWindow::on_showAnnotations_stateChanged() {
on_imageSlider_valueChanged();
}
void MainWindow::on_idSelection_currentIndexChanged(const QString &id) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
ui_->speciesValue->setText(annotation->species_.c_str());
ui_->subspeciesValue->setText(annotation->subspecies_.c_str());
}
}
}
}
void MainWindow::on_removeAnnotation_clicked() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
int id = ui_->idSelection->currentText().toInt();
annotations_->remove(current_image, id);
on_imageSlider_valueChanged();
}
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
uint64_t id = annotations_->nextId(current_image);
auto annotation = std::make_shared<ImageAnnotation>(
current_image.filename().string(), species, subspecies, id,
Rect(0, 0, 0, 0));
annotations_->insert(annotation);
on_imageSlider_valueChanged();
}
}
void MainWindow::onLoadDirectorySuccess(const QString &image_dir) {
image_files_.clear();
fs::directory_iterator dir_it(image_dir.toStdString());
fs::directory_iterator dir_end;
for(; dir_it != dir_end; ++dir_it) {
fs::path ext(dir_it->path().extension());
for(auto &ok_ext : kDirExtensions) {
if(ext == ok_ext) {
image_files_.push_back(dir_it->path());
}
}
}
std::sort(image_files_.begin(), image_files_.end());
if(image_files_.size() > 0) {
ui_->next->setEnabled(true);
ui_->prev->setEnabled(true);
ui_->saveAnnotations->setEnabled(true);
ui_->imageSlider->setEnabled(true);
ui_->imageSlider->setMinimum(0);
ui_->imageSlider->setMaximum(static_cast<int>(image_files_.size() - 1));
ui_->imageSlider->setSingleStep(1);
ui_->imageSlider->setValue(0);
annotations_->read(image_files_);
species_controls_->loadFromVector(annotations_->getAllSpecies());
on_imageSlider_valueChanged();
}
else {
QMessageBox err;
err.critical(0, "Error", "No images found in this directory.");
}
}
#include "../../include/fish_annotator/image_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::image_annotator
<commit_msg>Set icons on buttons, fill in values for type and subtype menus<commit_after>#include <algorithm>
#include <QFileDialog>
#include <QMessageBox>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/image_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace image_annotator {
namespace fs = boost::filesystem;
namespace { //anonymous
static const std::vector<std::string> kDirExtensions = {
".jpg", ".png", ".bmp", ".tif", ".jpeg",
".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};
} // anonymous namespace
MainWindow::MainWindow(QWidget *parent)
: annotations_(new ImageAnnotationList)
, scene_(new QGraphicsScene)
, ui_(new Ui::MainWidget)
, species_controls_(new SpeciesControls(this))
, image_files_() {
ui_->setupUi(this);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
setStyleSheet("QPushButton { background-color: rgb(230, 230, 230);"
"border-style: outset; border-radius: 5px; border-width: 2px; "
"border-color: grey; padding: 6px;}"
"QPushButton:pressed{background-color: rgb(190, 190, 190); "
"border-style: outset; border-radius: 5px;"
"border-width: 2px; border-color: grey; padding: 6px;}");
ui_->next->setIcon(":/icons/image_controls/next.svg");
ui_->prev->setIcon(":/icons/image_controls/prev.svg");
ui_->sideBarLayout->addWidget(species_controls_.get());
QObject::connect(species_controls_.get(),
SIGNAL(individualAdded(std::string, std::string)),
this, SLOT(addIndividual(std::string, std::string)));
}
void MainWindow::on_next_clicked() {
int next_val = ui_->imageSlider->value() + 1;
if(next_val <= ui_->imageSlider->maximum()) {
ui_->imageSlider->setValue(next_val);
}
}
void MainWindow::on_prev_clicked() {
int prev_val = ui_->imageSlider->value() - 1;
if(prev_val >= ui_->imageSlider->minimum()) {
ui_->imageSlider->setValue(prev_val);
}
}
void MainWindow::on_loadImageDir_triggered() {
QString image_dir = QFileDialog::getExistingDirectory(this,
"Select an image directory.");
if(!image_dir.isEmpty()) {
onLoadDirectorySuccess(image_dir);
}
}
void MainWindow::on_saveAnnotations_triggered() {
if(image_files_.size() > 0) {
annotations_->write(image_files_);
}
}
void MainWindow::on_imageSlider_valueChanged() {
scene_->clear();
ui_->idSelection->clear();
#ifdef _WIN32
QString filename(image_files_[ui_->imageSlider->value()].string().c_str());
#else
QString filename(image_files_[ui_->imageSlider->value()].c_str());
#endif
QImage current(filename);
if(!current.isNull()) {
scene_->addPixmap(QPixmap::fromImage(current));
scene_->setSceneRect(current.rect());
ui_->imageWindow->setScene(scene_.get());
ui_->imageWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
ui_->imageWindow->show();
ui_->fileNameValue->setText(filename);
fs::path img_path(filename.toStdString());
auto annotations =
annotations_->getImageAnnotations(img_path.filename());
for(auto annotation : annotations) {
if(ui_->showAnnotations->isChecked()) {
auto region = new AnnotatedRegion<ImageAnnotation>(
annotation->id_, annotation, current.rect());
scene_->addItem(region);
}
ui_->idSelection->addItem(QString::number(annotation->id_));
}
species_controls_->resetCounts();
auto counts = annotations_->getCounts(filename.toStdString());
for(auto it = counts.begin(); it != counts.end(); it++) {
species_controls_->setCount(it->second, it->first);
}
}
else {
QMessageBox err;
err.critical(0, "Error", std::string(
std::string("Error loading image ")
+ filename.toStdString()
+ std::string(".")).c_str());
}
}
void MainWindow::on_showAnnotations_stateChanged() {
on_imageSlider_valueChanged();
}
void MainWindow::on_idSelection_currentIndexChanged(const QString &id) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
ui_->typeMenu->clear();
ui_->subTypeMenu->clear();
auto species = species_controls_->getSpecies();
for(auto &s : species) {
ui_->typeMenu->addItem(s.getName().c_str());
if(s.getName() == annotation->species_) {
ui_->typeMenu->setCurrentText(s.getName().c_str());
auto subspecies = s.getSubspecies();
for(auto &sub : subspecies) {
ui_->subTypeMenu->addItem(sub.c_str());
if(sub == annotation->subspecies_) {
ui_->subTypeMenu->setCurrentText(sub.c_str());
}
}
}
}
}
}
}
}
void on_typeMenu_activated(const QString &text) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
ui_->subTypeMenu->clear();
auto species = species_controls_->getSpecies();
annotation->species_ = ui_->typeMenu->text().toStdString();
}
}
}
}
void on_subTypeMenu_activated(const QString &text) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
annotation->subspecies_ = ui_->subTypeMenu->text().toStdString();
}
}
}
}
void MainWindow::on_removeAnnotation_clicked() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
int id = ui_->idSelection->currentText().toInt();
annotations_->remove(current_image, id);
on_imageSlider_valueChanged();
}
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
uint64_t id = annotations_->nextId(current_image);
auto annotation = std::make_shared<ImageAnnotation>(
current_image.filename().string(), species, subspecies, id,
Rect(0, 0, 0, 0));
annotations_->insert(annotation);
on_imageSlider_valueChanged();
}
}
void MainWindow::onLoadDirectorySuccess(const QString &image_dir) {
image_files_.clear();
fs::directory_iterator dir_it(image_dir.toStdString());
fs::directory_iterator dir_end;
for(; dir_it != dir_end; ++dir_it) {
fs::path ext(dir_it->path().extension());
for(auto &ok_ext : kDirExtensions) {
if(ext == ok_ext) {
image_files_.push_back(dir_it->path());
}
}
}
std::sort(image_files_.begin(), image_files_.end());
if(image_files_.size() > 0) {
ui_->idLabel->setEnabled(true);
ui_->speciesLabel->setEnabled(true);
ui_->subspeciesLabel->setEnabled(true);
ui_->idSelection->setEnabled(true);
ui_->typeMenu->setEnabled(true);
ui_->subTypeMenu->setEnabled(true);
ui_->removeAnnotation->setEnabled(true);
ui_->showAnnotations->setEnabled(true);
ui_->setMetadata->setEnabled(true);
ui_->next->setEnabled(true);
ui_->prev->setEnabled(true);
ui_->saveAnnotations->setEnabled(true);
ui_->imageSlider->setEnabled(true);
ui_->imageSlider->setMinimum(0);
ui_->imageSlider->setMaximum(static_cast<int>(image_files_.size() - 1));
ui_->imageSlider->setSingleStep(1);
ui_->imageSlider->setValue(0);
annotations_->read(image_files_);
species_controls_->loadFromVector(annotations_->getAllSpecies());
on_imageSlider_valueChanged();
}
else {
QMessageBox err;
err.critical(0, "Error", "No images found in this directory.");
}
}
#include "../../include/fish_annotator/image_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::image_annotator
<|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. *
**************************************************************************/
/*
$Log$
Revision 1.8 2000/09/06 14:26:24 morsch
Decayer functionality of AliPythia has been moved to AliDecayerPythia.
Class is now a singleton.
Revision 1.7 2000/06/09 20:34:50 morsch
All coding rule violations except RS3 corrected
Revision 1.6 1999/11/09 07:38:48 fca
Changes for compatibility with version 2.23 of ROOT
Revision 1.5 1999/11/03 17:43:20 fca
New version from G.Martinez & A.Morsch
Revision 1.4 1999/09/29 09:24:14 fca
Introduction of the Copyright and cvs Log
*/
#include "AliPythia.h"
#include "AliRun.h"
ClassImp(AliPythia)
//_____________________________________________________________________________
AliPythia* AliPythia::fgAliPythia=NULL;
AliPythia::AliPythia()
{
// Default Constructor
}
void AliPythia::ProcInit(Process_t process, Float_t energy, StrucFunc_t strucfunc)
{
// Initialise the process to generate
fProcess = process;
fEcms = energy;
fStrucFunc = strucfunc;
// don't decay p0
SetMDCY(Pycomp(111),1,0);
// select structure function
SetMSTP(52,2);
SetMSTP(51,strucfunc);
//
// Pythia initialisation for selected processes//
//
// Make MSEL clean
//
for (Int_t i=1; i<= 200; i++) {
SetMSUB(i,0);
}
// select charm production
switch (process)
{
case charm:
SetMSEL(4);
//
// heavy quark masses
SetPMAS(4,1,1.2);
//
// primordial pT
SetMSTP(91,1);
SetPARP(91,1);
SetPARP(93,3);
//
break;
case beauty:
SetMSEL(5);
SetPMAS(5,1,4.75);
break;
case jpsi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
break;
case jpsi_chi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
// gg-> chi_0c g
SetMSUB(87,1);
// gg-> chi_1c g
SetMSUB(88,1);
// gg-> chi_2c g
SetMSUB(89,1);
case charm_unforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
case beauty_unforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case mb:
// Minimum Bias pp-Collisions
//
// Tuning of parameters descibed in G. Ciapetti and A. Di Ciaccio
// Proc. of the LHC Workshop, Aachen 1990, Vol. II p. 155
//
// select Pythia min. bias model
SetMSEL(2);
SetMSUB(92,1);
SetMSUB(93,1);
SetMSUB(94,1);
SetMSUB(95,1);
// Multiple interactions switched on
SetMSTP(81,1);
SetMSTP(82,1);
// Low-pT cut-off for hard scattering
SetPARP(81,1.9);
// model for subsequent non-hardest interaction
// 90% gg->gg 10% gg->qq
SetPARP(86,0.9);
// 90% of gluon interactions have minimum string length
SetPARP(85,0.9);
}
//
// Initialize PYTHIA
SetMSTP(41,1);
Initialize("CMS","p","p",fEcms);
}
Int_t AliPythia::CheckedLuComp(Int_t kf)
{
// Check Lund particle code (for debugging)
Int_t kc=Pycomp(kf);
printf("\n Lucomp kf,kc %d %d",kf,kc);
return kc;
}
void AliPythia::SetNuclei(Int_t a1, Int_t a2)
{
// Treat protons as inside nuclei with mass numbers a1 and a2
// The MSTP array in the PYPARS common block is used to enable and
// select the nuclear structure functions.
// MSTP(52) : (D=1) choice of proton and nuclear structure-function library
// =1: internal PYTHIA acording to MSTP(51)
// =2: PDFLIB proton s.f., with MSTP(51) = 1000xNGROUP+NSET
// =3: PDFLIB proton s.f. with nuclar correction:
// MSTP( 51) = 1000xNPGROUP+NPSET
// MSTP(151) = 1000xNAGROUP+NASET
// MSTP(192) : Mass number of nucleus side 1
// MSTP(193) : Mass number of nucleus side 2
SetMSTP(52,3);
SetMSTP(191, 1001);
SetMSTP(192, a1);
SetMSTP(193, a2);
}
AliPythia* AliPythia::Instance()
{
if (fgAliPythia) {
return fgAliPythia;
} else {
fgAliPythia = new AliPythia();
return fgAliPythia;
}
}
void AliPythia::Streamer(TBuffer &R__b) {}
<commit_msg>Upper cut of prim. pT distribution set to 5. GeV<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. *
**************************************************************************/
/*
$Log$
Revision 1.9 2000/09/18 10:41:35 morsch
Add possibility to use nuclear structure functions from PDF library V8.
Revision 1.8 2000/09/06 14:26:24 morsch
Decayer functionality of AliPythia has been moved to AliDecayerPythia.
Class is now a singleton.
Revision 1.7 2000/06/09 20:34:50 morsch
All coding rule violations except RS3 corrected
Revision 1.6 1999/11/09 07:38:48 fca
Changes for compatibility with version 2.23 of ROOT
Revision 1.5 1999/11/03 17:43:20 fca
New version from G.Martinez & A.Morsch
Revision 1.4 1999/09/29 09:24:14 fca
Introduction of the Copyright and cvs Log
*/
#include "AliPythia.h"
#include "AliRun.h"
ClassImp(AliPythia)
//_____________________________________________________________________________
AliPythia* AliPythia::fgAliPythia=NULL;
AliPythia::AliPythia()
{
// Default Constructor
}
void AliPythia::ProcInit(Process_t process, Float_t energy, StrucFunc_t strucfunc)
{
// Initialise the process to generate
fProcess = process;
fEcms = energy;
fStrucFunc = strucfunc;
// don't decay p0
SetMDCY(Pycomp(111),1,0);
// select structure function
SetMSTP(52,2);
SetMSTP(51,strucfunc);
//
// Pythia initialisation for selected processes//
//
// Make MSEL clean
//
for (Int_t i=1; i<= 200; i++) {
SetMSUB(i,0);
}
// select charm production
switch (process)
{
case charm:
SetMSEL(4);
//
// heavy quark masses
SetPMAS(4,1,1.2);
//
// primordial pT
SetMSTP(91,1);
SetPARP(91,1.);
SetPARP(93,5.);
//
break;
case beauty:
SetMSEL(5);
SetPMAS(5,1,4.75);
break;
case jpsi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
break;
case jpsi_chi:
SetMSEL(0);
// gg->J/Psi g
SetMSUB(86,1);
// gg-> chi_0c g
SetMSUB(87,1);
// gg-> chi_1c g
SetMSUB(88,1);
// gg-> chi_2c g
SetMSUB(89,1);
case charm_unforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
case beauty_unforced:
SetMSEL(0);
// gq->qg
SetMSUB(28,1);
// gg->qq
SetMSUB(53,1);
// gg->gg
SetMSUB(68,1);
break;
case mb:
// Minimum Bias pp-Collisions
//
// Tuning of parameters descibed in G. Ciapetti and A. Di Ciaccio
// Proc. of the LHC Workshop, Aachen 1990, Vol. II p. 155
//
// select Pythia min. bias model
SetMSEL(2);
SetMSUB(92,1);
SetMSUB(93,1);
SetMSUB(94,1);
SetMSUB(95,1);
// Multiple interactions switched on
SetMSTP(81,1);
SetMSTP(82,1);
// Low-pT cut-off for hard scattering
SetPARP(81,1.9);
// model for subsequent non-hardest interaction
// 90% gg->gg 10% gg->qq
SetPARP(86,0.9);
// 90% of gluon interactions have minimum string length
SetPARP(85,0.9);
}
//
// Initialize PYTHIA
SetMSTP(41,1);
Initialize("CMS","p","p",fEcms);
}
Int_t AliPythia::CheckedLuComp(Int_t kf)
{
// Check Lund particle code (for debugging)
Int_t kc=Pycomp(kf);
printf("\n Lucomp kf,kc %d %d",kf,kc);
return kc;
}
void AliPythia::SetNuclei(Int_t a1, Int_t a2)
{
// Treat protons as inside nuclei with mass numbers a1 and a2
// The MSTP array in the PYPARS common block is used to enable and
// select the nuclear structure functions.
// MSTP(52) : (D=1) choice of proton and nuclear structure-function library
// =1: internal PYTHIA acording to MSTP(51)
// =2: PDFLIB proton s.f., with MSTP(51) = 1000xNGROUP+NSET
// =3: PDFLIB proton s.f. with nuclar correction:
// MSTP( 51) = 1000xNPGROUP+NPSET
// MSTP(151) = 1000xNAGROUP+NASET
// MSTP(192) : Mass number of nucleus side 1
// MSTP(193) : Mass number of nucleus side 2
SetMSTP(52,3);
SetMSTP(191, 1001);
SetMSTP(192, a1);
SetMSTP(193, a2);
}
AliPythia* AliPythia::Instance()
{
if (fgAliPythia) {
return fgAliPythia;
} else {
fgAliPythia = new AliPythia();
return fgAliPythia;
}
}
void AliPythia::Streamer(TBuffer &R__b) {}
<|endoftext|> |
<commit_before>// Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <vector>
#include <assert.h>
#include <crypto/common.h>
namespace {
constexpr uint32_t INVALID = 0xFFFFFFFF;
uint32_t DecodeBits(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos, uint8_t minval, const std::vector<uint8_t> &bit_sizes)
{
uint32_t val = minval;
bool bit;
for (std::vector<uint8_t>::const_iterator bit_sizes_it = bit_sizes.begin();
bit_sizes_it != bit_sizes.end(); ++bit_sizes_it) {
if (bit_sizes_it + 1 != bit_sizes.end()) {
if (bitpos == endpos) break;
bit = *bitpos;
bitpos++;
} else {
bit = 0;
}
if (bit) {
val += (1 << *bit_sizes_it);
} else {
for (int b = 0; b < *bit_sizes_it; b++) {
if (bitpos == endpos) return INVALID; // Reached EOF in mantissa
bit = *bitpos;
bitpos++;
val += bit << (*bit_sizes_it - 1 - b);
}
return val;
}
}
return INVALID; // Reached EOF in exponent
}
enum class Instruction : uint32_t
{
RETURN = 0,
JUMP = 1,
MATCH = 2,
DEFAULT = 3,
};
const std::vector<uint8_t> TYPE_BIT_SIZES{0, 0, 1};
Instruction DecodeType(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return Instruction(DecodeBits(bitpos, endpos, 0, TYPE_BIT_SIZES));
}
const std::vector<uint8_t> ASN_BIT_SIZES{15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
uint32_t DecodeASN(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 1, ASN_BIT_SIZES);
}
const std::vector<uint8_t> MATCH_BIT_SIZES{1, 2, 3, 4, 5, 6, 7, 8};
uint32_t DecodeMatch(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 2, MATCH_BIT_SIZES);
}
const std::vector<uint8_t> JUMP_BIT_SIZES{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
uint32_t DecodeJump(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 17, JUMP_BIT_SIZES);
}
}
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip)
{
std::vector<bool>::const_iterator pos = asmap.begin();
const std::vector<bool>::const_iterator endpos = asmap.end();
uint8_t bits = ip.size();
uint32_t default_asn = 0;
uint32_t jump, match, matchlen;
Instruction opcode;
while (pos != endpos) {
opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
return default_asn;
} else if (opcode == Instruction::JUMP) {
jump = DecodeJump(pos, endpos);
if (jump == INVALID) break; // Jump offset straddles EOF
if (bits == 0) break; // No input bits left
if (jump >= endpos - pos) break; // Jumping past EOF
if (ip[ip.size() - bits]) {
pos += jump;
}
bits--;
} else if (opcode == Instruction::MATCH) {
match = DecodeMatch(pos, endpos);
if (match == INVALID) break; // Match bits straddle EOF
matchlen = CountBits(match) - 1;
if (bits < matchlen) break; // Not enough input bits
for (uint32_t bit = 0; bit < matchlen; bit++) {
if ((ip[ip.size() - bits]) != ((match >> (matchlen - 1 - bit)) & 1)) {
return default_asn;
}
bits--;
}
} else if (opcode == Instruction::DEFAULT) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
} else {
break; // Instruction straddles EOF
}
}
assert(false); // Reached EOF without RETURN, or aborted (see any of the breaks above) - should have been caught by SanityCheckASMap below
return 0; // 0 is not a valid ASN
}
bool SanityCheckASMap(const std::vector<bool>& asmap, int bits)
{
const std::vector<bool>::const_iterator begin = asmap.begin(), endpos = asmap.end();
std::vector<bool>::const_iterator pos = begin;
std::vector<std::pair<uint32_t, int>> jumps; // All future positions we may jump to (bit offset in asmap -> bits to consume left)
jumps.reserve(bits);
Instruction prevopcode = Instruction::JUMP;
bool had_incomplete_match = false;
while (pos != endpos) {
uint32_t offset = pos - begin;
if (!jumps.empty() && offset >= jumps.back().first) return false; // There was a jump into the middle of the previous instruction
Instruction opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
if (prevopcode == Instruction::DEFAULT) return false; // There should not be any RETURN immediately after a DEFAULT (could be combined into just RETURN)
uint32_t asn = DecodeASN(pos, endpos);
if (asn == INVALID) return false; // ASN straddles EOF
if (jumps.empty()) {
// Nothing to execute anymore
if (endpos - pos > 7) return false; // Excessive padding
while (pos != endpos) {
if (*pos) return false; // Nonzero padding bit
++pos;
}
return true; // Sanely reached EOF
} else {
// Continue by pretending we jumped to the next instruction
offset = pos - begin;
if (offset != jumps.back().first) return false; // Unreachable code
bits = jumps.back().second; // Restore the number of bits we would have had left after this jump
jumps.pop_back();
prevopcode = Instruction::JUMP;
}
} else if (opcode == Instruction::JUMP) {
uint32_t jump = DecodeJump(pos, endpos);
if (jump == INVALID) return false; // Jump offset straddles EOF
if (jump > endpos - pos) return false; // Jump out of range
if (bits == 0) return false; // Consuming bits past the end of the input
--bits;
uint32_t jump_offset = pos - begin + jump;
if (!jumps.empty() && jump_offset >= jumps.back().first) return false; // Intersecting jumps
jumps.emplace_back(jump_offset, bits);
prevopcode = Instruction::JUMP;
} else if (opcode == Instruction::MATCH) {
uint32_t match = DecodeMatch(pos, endpos);
if (match == INVALID) return false; // Match bits straddle EOF
int matchlen = CountBits(match) - 1;
if (prevopcode != Instruction::MATCH) had_incomplete_match = false;
if (matchlen < 8 && had_incomplete_match) return false; // Within a sequence of matches only at most one should be incomplete
had_incomplete_match = (matchlen < 8);
if (bits < matchlen) return false; // Consuming bits past the end of the input
bits -= matchlen;
prevopcode = Instruction::MATCH;
} else if (opcode == Instruction::DEFAULT) {
if (prevopcode == Instruction::DEFAULT) return false; // There should not be two successive DEFAULTs (they could be combined into one)
uint32_t asn = DecodeASN(pos, endpos);
if (asn == INVALID) return false; // ASN straddles EOF
prevopcode = Instruction::DEFAULT;
} else {
return false; // Instruction straddles EOF
}
}
return false; // Reached EOF without RETURN instruction
}
<commit_msg>refactor: Rework asmap Interpret to avoid ptrdiff_t<commit_after>// Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <vector>
#include <assert.h>
#include <crypto/common.h>
namespace {
constexpr uint32_t INVALID = 0xFFFFFFFF;
uint32_t DecodeBits(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos, uint8_t minval, const std::vector<uint8_t> &bit_sizes)
{
uint32_t val = minval;
bool bit;
for (std::vector<uint8_t>::const_iterator bit_sizes_it = bit_sizes.begin();
bit_sizes_it != bit_sizes.end(); ++bit_sizes_it) {
if (bit_sizes_it + 1 != bit_sizes.end()) {
if (bitpos == endpos) break;
bit = *bitpos;
bitpos++;
} else {
bit = 0;
}
if (bit) {
val += (1 << *bit_sizes_it);
} else {
for (int b = 0; b < *bit_sizes_it; b++) {
if (bitpos == endpos) return INVALID; // Reached EOF in mantissa
bit = *bitpos;
bitpos++;
val += bit << (*bit_sizes_it - 1 - b);
}
return val;
}
}
return INVALID; // Reached EOF in exponent
}
enum class Instruction : uint32_t
{
RETURN = 0,
JUMP = 1,
MATCH = 2,
DEFAULT = 3,
};
const std::vector<uint8_t> TYPE_BIT_SIZES{0, 0, 1};
Instruction DecodeType(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return Instruction(DecodeBits(bitpos, endpos, 0, TYPE_BIT_SIZES));
}
const std::vector<uint8_t> ASN_BIT_SIZES{15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
uint32_t DecodeASN(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 1, ASN_BIT_SIZES);
}
const std::vector<uint8_t> MATCH_BIT_SIZES{1, 2, 3, 4, 5, 6, 7, 8};
uint32_t DecodeMatch(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 2, MATCH_BIT_SIZES);
}
const std::vector<uint8_t> JUMP_BIT_SIZES{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
uint32_t DecodeJump(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 17, JUMP_BIT_SIZES);
}
}
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip)
{
std::vector<bool>::const_iterator pos = asmap.begin();
const std::vector<bool>::const_iterator endpos = asmap.end();
uint8_t bits = ip.size();
uint32_t default_asn = 0;
uint32_t jump, match, matchlen;
Instruction opcode;
while (pos != endpos) {
opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
return default_asn;
} else if (opcode == Instruction::JUMP) {
jump = DecodeJump(pos, endpos);
if (jump == INVALID) break; // Jump offset straddles EOF
if (bits == 0) break; // No input bits left
if (pos + jump < pos) break; // overflow
if (pos + jump >= endpos) break; // Jumping past EOF
if (ip[ip.size() - bits]) {
pos += jump;
}
bits--;
} else if (opcode == Instruction::MATCH) {
match = DecodeMatch(pos, endpos);
if (match == INVALID) break; // Match bits straddle EOF
matchlen = CountBits(match) - 1;
if (bits < matchlen) break; // Not enough input bits
for (uint32_t bit = 0; bit < matchlen; bit++) {
if ((ip[ip.size() - bits]) != ((match >> (matchlen - 1 - bit)) & 1)) {
return default_asn;
}
bits--;
}
} else if (opcode == Instruction::DEFAULT) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
} else {
break; // Instruction straddles EOF
}
}
assert(false); // Reached EOF without RETURN, or aborted (see any of the breaks above) - should have been caught by SanityCheckASMap below
return 0; // 0 is not a valid ASN
}
bool SanityCheckASMap(const std::vector<bool>& asmap, int bits)
{
const std::vector<bool>::const_iterator begin = asmap.begin(), endpos = asmap.end();
std::vector<bool>::const_iterator pos = begin;
std::vector<std::pair<uint32_t, int>> jumps; // All future positions we may jump to (bit offset in asmap -> bits to consume left)
jumps.reserve(bits);
Instruction prevopcode = Instruction::JUMP;
bool had_incomplete_match = false;
while (pos != endpos) {
uint32_t offset = pos - begin;
if (!jumps.empty() && offset >= jumps.back().first) return false; // There was a jump into the middle of the previous instruction
Instruction opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
if (prevopcode == Instruction::DEFAULT) return false; // There should not be any RETURN immediately after a DEFAULT (could be combined into just RETURN)
uint32_t asn = DecodeASN(pos, endpos);
if (asn == INVALID) return false; // ASN straddles EOF
if (jumps.empty()) {
// Nothing to execute anymore
if (endpos - pos > 7) return false; // Excessive padding
while (pos != endpos) {
if (*pos) return false; // Nonzero padding bit
++pos;
}
return true; // Sanely reached EOF
} else {
// Continue by pretending we jumped to the next instruction
offset = pos - begin;
if (offset != jumps.back().first) return false; // Unreachable code
bits = jumps.back().second; // Restore the number of bits we would have had left after this jump
jumps.pop_back();
prevopcode = Instruction::JUMP;
}
} else if (opcode == Instruction::JUMP) {
uint32_t jump = DecodeJump(pos, endpos);
if (jump == INVALID) return false; // Jump offset straddles EOF
if (pos + jump < pos) return false; // overflow
if (pos + jump > endpos) return false; // Jump out of range
if (bits == 0) return false; // Consuming bits past the end of the input
--bits;
uint32_t jump_offset = pos - begin + jump;
if (!jumps.empty() && jump_offset >= jumps.back().first) return false; // Intersecting jumps
jumps.emplace_back(jump_offset, bits);
prevopcode = Instruction::JUMP;
} else if (opcode == Instruction::MATCH) {
uint32_t match = DecodeMatch(pos, endpos);
if (match == INVALID) return false; // Match bits straddle EOF
int matchlen = CountBits(match) - 1;
if (prevopcode != Instruction::MATCH) had_incomplete_match = false;
if (matchlen < 8 && had_incomplete_match) return false; // Within a sequence of matches only at most one should be incomplete
had_incomplete_match = (matchlen < 8);
if (bits < matchlen) return false; // Consuming bits past the end of the input
bits -= matchlen;
prevopcode = Instruction::MATCH;
} else if (opcode == Instruction::DEFAULT) {
if (prevopcode == Instruction::DEFAULT) return false; // There should not be two successive DEFAULTs (they could be combined into one)
uint32_t asn = DecodeASN(pos, endpos);
if (asn == INVALID) return false; // ASN straddles EOF
prevopcode = Instruction::DEFAULT;
} else {
return false; // Instruction straddles EOF
}
}
return false; // Reached EOF without RETURN instruction
}
<|endoftext|> |
<commit_before>// Ouzel by Elviss Strazdins
#ifndef OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
#define OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
#include <system_error>
#include <CoreVideo/CVDisplayLink.h>
#include "CoreVideoErrorCategory.hpp"
namespace ouzel::platform::corevideo
{
class DisplayLink final
{
public:
explicit DisplayLink(CGDirectDisplayID displayId)
{
if (const auto result = CVDisplayLinkCreateWithCGDisplay(displayId, &displayLink); result != kCVReturnSuccess)
throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to create display link");
}
~DisplayLink()
{
if (displayLink) CVDisplayLinkRelease(displayLink);
}
DisplayLink(DisplayLink&& other) noexcept:
displayLink{other.displayLink}
{
other.displayLink = nullptr;
}
DisplayLink(const DisplayLink& other):
displayLink{other.displayLink}
{
if (displayLink) CVDisplayLinkRetain(displayLink);
}
DisplayLink& operator=(DisplayLink&& other) noexcept
{
if (&other == this) return *this;
if (displayLink) CVDisplayLinkRelease(displayLink);
displayLink = other.displayLink;
other.displayLink = nullptr;
return *this;
}
DisplayLink& operator=(const DisplayLink& other) noexcept
{
if (&other == this) return *this;
if (displayLink) CVDisplayLinkRelease(displayLink);
displayLink = other.displayLink;
if (displayLink) CVDisplayLinkRetain(displayLink);
return *this;
}
void setCallback(CVDisplayLinkOutputCallback callback, void* userInfo)
{
if (const auto result = CVDisplayLinkSetOutputCallback(displayLink, callback, userInfo); result != kCVReturnSuccess)
throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to set output callback for the display link");
}
void start()
{
if (displayLink)
if (const auto result = CVDisplayLinkStart(displayLink); result != kCVReturnSuccess)
throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to start display link");
}
void stop()
{
if (displayLink)
if (const auto result = CVDisplayLinkStop(displayLink); result != kCVReturnSuccess)
throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to stop display link");
}
private:
CVDisplayLinkRef displayLink = nullptr;
};
}
#endif // OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
<commit_msg>Remove the unneeded namespaces<commit_after>// Ouzel by Elviss Strazdins
#ifndef OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
#define OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
#include <system_error>
#include <CoreVideo/CVDisplayLink.h>
#include "CoreVideoErrorCategory.hpp"
namespace ouzel::platform::corevideo
{
class DisplayLink final
{
public:
explicit DisplayLink(CGDirectDisplayID displayId)
{
if (const auto result = CVDisplayLinkCreateWithCGDisplay(displayId, &displayLink); result != kCVReturnSuccess)
throw std::system_error(result, getErrorCategory(), "Failed to create display link");
}
~DisplayLink()
{
if (displayLink) CVDisplayLinkRelease(displayLink);
}
DisplayLink(DisplayLink&& other) noexcept:
displayLink{other.displayLink}
{
other.displayLink = nullptr;
}
DisplayLink(const DisplayLink& other):
displayLink{other.displayLink}
{
if (displayLink) CVDisplayLinkRetain(displayLink);
}
DisplayLink& operator=(DisplayLink&& other) noexcept
{
if (&other == this) return *this;
if (displayLink) CVDisplayLinkRelease(displayLink);
displayLink = other.displayLink;
other.displayLink = nullptr;
return *this;
}
DisplayLink& operator=(const DisplayLink& other) noexcept
{
if (&other == this) return *this;
if (displayLink) CVDisplayLinkRelease(displayLink);
displayLink = other.displayLink;
if (displayLink) CVDisplayLinkRetain(displayLink);
return *this;
}
void setCallback(CVDisplayLinkOutputCallback callback, void* userInfo)
{
if (const auto result = CVDisplayLinkSetOutputCallback(displayLink, callback, userInfo); result != kCVReturnSuccess)
throw std::system_error(result, getErrorCategory(), "Failed to set output callback for the display link");
}
void start()
{
if (displayLink)
if (const auto result = CVDisplayLinkStart(displayLink); result != kCVReturnSuccess)
throw std::system_error(result, getErrorCategory(), "Failed to start display link");
}
void stop()
{
if (displayLink)
if (const auto result = CVDisplayLinkStop(displayLink); result != kCVReturnSuccess)
throw std::system_error(result, getErrorCategory(), "Failed to stop display link");
}
private:
CVDisplayLinkRef displayLink = nullptr;
};
}
#endif // OUZEL_PLATFORM_COREVIDEO_DISPLAYLINK_HPP
<|endoftext|> |
<commit_before>// FFModule.cc
// This file is part of bes, A C++ back-end server implementation framework
// for the OPeNDAP Data Access Protocol.
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]>
//
// 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
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmostpheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
#include <iostream>
using std::endl ;
#include "FFModule.h"
#include "BESRequestHandlerList.h"
#include "FFRequestHandler.h"
#include "BESContainerStorageList.h"
#include "BESContainerStorageCatalog.h"
#include "BESCatalogDirectory.h"
#include "BESCatalogList.h"
#include "BESDebug.h"
#define FF_CATALOG "catalog"
void
FFModule::initialize( const string &modname )
{
BESDEBUG( "Initializing FF module " << modname << endl )
BESDEBUG( " adding " << modname << " request handler" << endl )
BESRequestHandler *handler = new FFRequestHandler( modname ) ;
BESRequestHandlerList::TheList()->add_handler( modname, handler ) ;
BESDEBUG( " adding " << FF_CATALOG << " catalog" << endl )
BESCatalogList::TheCatalogList()->add_catalog( new BESCatalogDirectory( FF_CATALOG ) ) ;
BESDEBUG( " adding catalog container storage" << FF_CATALOG << endl )
BESContainerStorageCatalog *csc = new BESContainerStorageCatalog( FF_CATALOG ) ;
BESContainerStorageList::TheList()->add_persistence( csc ) ;
BESDEBUG( "Done Initializing FF module " << modname << endl )
}
void
FFModule::terminate( const string &modname )
{
BESDEBUG( "Cleaning FF module " << modname << endl )
BESDEBUG( " removing FF Handler" << modname << endl )
BESRequestHandler *rh = BESRequestHandlerList::TheList()->remove_handler( modname ) ;
if( rh ) delete rh ;
BESDEBUG( " removing catalog container storage" << FF_CATALOG << endl )
BESContainerStorageList::TheList()->del_persistence( FF_CATALOG ) ;
BESDEBUG( " removing " << FF_CATALOG << " catalog" << endl )
BESCatalogList::TheCatalogList()->del_catalog( FF_CATALOG ) ;
BESDEBUG( "Done Cleaning FF module " << modname << endl )
}
/** @brief dumps information about this object
*
* Displays the pointer value of this instance
*
* @param strm C++ i/o stream to dump the information to
*/
void
FFModule::dump( ostream &strm ) const
{
strm << BESIndent::LMarg << "FFModule::dump - ("
<< (void *)this << ")" << endl ;
}
extern "C"
{
BESAbstractModule *maker()
{
return new FFModule ;
}
}
<commit_msg>BESDebug modifications, passing context to BESDEBUG and registering debug context in Module classes.<commit_after>// FFModule.cc
// This file is part of bes, A C++ back-end server implementation framework
// for the OPeNDAP Data Access Protocol.
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]>
//
// 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
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmostpheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
#include <iostream>
using std::endl ;
#include "FFModule.h"
#include "BESRequestHandlerList.h"
#include "FFRequestHandler.h"
#include "BESContainerStorageList.h"
#include "BESContainerStorageCatalog.h"
#include "BESCatalogDirectory.h"
#include "BESCatalogList.h"
#include "BESDebug.h"
#define FF_CATALOG "catalog"
void
FFModule::initialize( const string &modname )
{
BESDEBUG( "ff", "Initializing FF module " << modname << endl )
BESDEBUG( "ff", " adding " << modname << " request handler" << endl )
BESRequestHandler *handler = new FFRequestHandler( modname ) ;
BESRequestHandlerList::TheList()->add_handler( modname, handler ) ;
BESDEBUG( "ff", " adding " << FF_CATALOG << " catalog" << endl )
BESCatalogList::TheCatalogList()->add_catalog( new BESCatalogDirectory( FF_CATALOG ) ) ;
BESDEBUG( "ff", " adding catalog container storage" << FF_CATALOG << endl )
BESContainerStorageCatalog *csc = new BESContainerStorageCatalog( FF_CATALOG ) ;
BESContainerStorageList::TheList()->add_persistence( csc ) ;
BESDEBUG( "ff", " adding ff debug context" << endl )
BESDebug::Register( "ff" ) ;
BESDEBUG( "ff", "Done Initializing FF module " << modname << endl )
}
void
FFModule::terminate( const string &modname )
{
BESDEBUG( "ff", "Cleaning FF module " << modname << endl )
BESDEBUG( "ff", " removing FF Handler" << modname << endl )
BESRequestHandler *rh = BESRequestHandlerList::TheList()->remove_handler( modname ) ;
if( rh ) delete rh ;
BESDEBUG( "ff", " removing catalog container storage" << FF_CATALOG << endl )
BESContainerStorageList::TheList()->del_persistence( FF_CATALOG ) ;
BESDEBUG( "ff", " removing " << FF_CATALOG << " catalog" << endl )
BESCatalogList::TheCatalogList()->del_catalog( FF_CATALOG ) ;
BESDEBUG( "ff", "Done Cleaning FF module " << modname << endl )
}
/** @brief dumps information about this object
*
* Displays the pointer value of this instance
*
* @param strm C++ i/o stream to dump the information to
*/
void
FFModule::dump( ostream &strm ) const
{
strm << BESIndent::LMarg << "FFModule::dump - ("
<< (void *)this << ")" << endl ;
}
extern "C"
{
BESAbstractModule *maker()
{
return new FFModule ;
}
}
<|endoftext|> |
<commit_before>/***
* Removes the meta boxes from the provided mpeg4 source file, writing the result
* out to a new file given the provided filename.
*
* This sample program only works for media files that stay within 32-bit box/file sizes.
* If the file is larger than the 32-bit maximum, the following additions could be made:
*
* 1. Check for 64-bit boxes size encoding (atom size=1) and adjust according.
* 2. Find the co64 table instead of stco table, and modify those table entries.
*/
#include "stdio.h"
#include "stdint.h"
#include "stdlib.h"
#include "stddef.h"
#include "string.h"
#include <vector>
/* M4A atoms can be either data holders, or containers of other
* atoms. Actually, it's slightly more complicated than that, since there
* are a few choice atoms that are containers that also have data inside of them.
* However, we don't need to worry about this in this utility, since the only
* container that has that property is the "meta" container, but we're just
* removing it, anyway; we don't need to recurse into it.
*
* According to the docs for the m4a file type, we can find meta in the following
* places in the hierarchy:
* meta
* moov.udta.meta
* moov.udta.trak.meta
*
* So, based on that information, we track make sure to check the
* substructure of the necessary containers.
*/
const char *const containers_of_interest = "moov|udta|trak|mdia|minf|stbl";
typedef struct atom_t {
atom_t* parent;
union byte_addressable {
uint64_t word;
uint8_t bytes[8];
} len;
char name[5];
uint64_t data_size;
int64_t data_remaining;
unsigned char* data;
bool container;
std::vector<atom_t*> children;
} atom_t;
/***
* Find the next box (atom) in the provided m4a file
*
* Allocates memory for the atom if necessary, and returns
* a new atom_t with information about the new atom.
*/
atom_t* get_next_box(FILE* m4a_file) {
atom_t *atom = (atom_t*)malloc(sizeof(atom_t));
int i;
/* Read in big-endian order */
//atom->len.word = 0;
//for(i = 3; i >= 0; i--) {
// fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
//}
fread(atom->name, 1, 4, m4a_file);
/* If the standard length word is 1, then we
* expect an 8-byte length immediately follow
* the name.
*
* Also the header is effectively 16 bytes now. */
if(atom->len.word == 1) {
/* Read in big-endian order */
for(i = 7; i >= 0; i--) {
fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
}
atom->data_size = atom->len.word - 16;
} else {
atom->data_size = atom->len.word - 8;
}
/* Initialize the struct depending on whether
* it's a container of interest or just a
* data blob to pass through.
*/
if(strstr(containers_of_interest, atom->name) != 0) {
//If it's a container, mark the size in data_remaining so the main loop
//knows how much to process
atom->data = NULL;
atom->data_remaining = atom->data_size;
} else {
//Otherwise, just throw the data in a char blob
//to dump back out later
atom->data = (unsigned char*)malloc(atom->data_size);;
fread(atom->data, atom->data_size, 1, m4a_file);
atom->data_remaining = 0;
}
return atom;
}
// A little function to look for meta tags in a less structured way
// Just used for testing
// Could possibly result in a false positive if the "meta" tag appears
// in binary data by chance, although my hunch is that this is unlikely.
int find_meta(FILE *m4a_file) {
const char* target = "meta";
unsigned int tmp;
int i;
for(i = 0; i < strlen(target); i++) {
tmp <<= 8;
tmp |= (unsigned char)target[i];
}
const unsigned int target_checksum = tmp; //Sum of characters in "meta"
int checksum = 0;
unsigned char c = 0;
unsigned char buffer[8] = {0,0,0,0,0,0,0,0};
int index = 0;
bool found = false;
while(fread(&c, 1, 1, m4a_file) > 0) {
index++;
buffer[index & 7] = c;
checksum <<= 8;
checksum |= c;
if(checksum == target_checksum) {
found = true;
for(i = strlen(target)-1; i >=0; i--) {
if(target[i] != buffer[(index+5+i) & 7]) {
found = false;
break;
}
}
if(found == true) {
printf("Found 'meta' at position %lu\n", index - strlen(target));
return index;
}
}
}
printf("found no meta box in all %d positions\n",index);
return -1;
}
void print_tree_rec(atom_t* node, int level) {
int i;
for(i=0; i<level; i++) {
printf(".");
}
//skip root content, it's not *really* an atom
if(node->parent != NULL) {
printf("%llu %s\n", node->len.word, node->name);
}
for(i=0; i<node->children.size(); i++) {
print_tree_rec(node->children[i], level+1);
}
}
void print_tree(atom_t* node) {
print_tree_rec(node, 0);
}
void output_tree(atom_t* node, FILE *out_file) {
int i;
//skip root content, it's not *really* an atom
if(node->parent != NULL) {
for(i = 3; i >= 0; i--) {
fwrite(&node->len.bytes[i], 1, 1, out_file);
}
fwrite(node->name, 4, 1, out_file);
if(node->data_size > 0 && node->data != NULL) {
fwrite(node->data, node->data_size, 1, out_file);
}
}
for(i=0; i < node->children.size(); i++) {
output_tree(node->children[i], out_file);
}
}
void adjust_stco_offset(atom_t *stco, int offset_adjust) {
int i,j;
//Offset past the version byte
unsigned char* stco_data_ptr = (stco->data + 4);
int stco_entries = htonl(*((uint32_t*)(stco_data_ptr)));
//Ofset version bytes and length bytes
stco_data_ptr = stco->data + 8;
//Read the bytes in big-endian order,
//subtract offset,
//write back out.
for(i = 0; i < stco_entries; i++) {
uint32_t stco_offset = htonl(*((uint32_t*)(stco_data_ptr)));
stco_offset -= offset_adjust;
*((uint32_t*)stco_data_ptr) = htonl(stco_offset);
stco_data_ptr += 4;
}
}
atom_t* build_tree(FILE* m4a_file) {
bool visited_mdat = false;
//Place to hold the current working atom.
atom_t *atom;
//Create an abstract root node to hold the top-level
//atom list.
atom_t *root = (atom_t*)malloc(sizeof(atom_t));
root->parent == NULL;
root->data_remaining = -1;
atom_t *current_parent = root;
atom_t *stco = NULL;
uint64_t chunk_offset_adjust = 0;
int level = 0;
/* Loop through the rest of the atoms */
while((atom = get_next_box(m4a_file))->len.word > 0) {
int i;
//Set the parent of the newly created atom
atom->parent = current_parent;
//Note whether or not we've visited the mdat box
//So that we know if stco offsets must be
//adjusted later.
if(strncmp(atom->name, "mdat", 4) == 0) {
visited_mdat = true;
}
//If it's a meta box, don't add it to the
//current atom list, so it's removed from
//the internal tree structure. Also, iterate
//back up through the parent pointers adjusting
//box sizes to account for its removal.
if(strncmp(atom->name, "meta", 4) == 0) {
//reset the parent values
atom_t *cur = atom->parent;
while(cur != NULL) {
cur->len.word -= atom->len.word;
cur = cur->parent;
}
//update the chunk offset adjustment
//but only if this meta chunk is before
//the mdat box. If it's after,
//it won't change stco offsets relative
//to the file start.
if(visited_mdat == false) {
chunk_offset_adjust += atom->len.word;
}
} else {
current_parent->children.push_back(atom);
}
//If we have a chunk_offset_adjust and
//the current atom is stco,
//save it so we can adjust it at the end if necessary.
if(strncmp(atom->name, "stco", 4) == 0) {
stco = atom;
}
//Subtract size of current atom from
//the data_remaining of the parent
//before the next step, which might reset the
//parent pointer to a new level.
if(current_parent != root) {
current_parent->data_remaining -= atom->len.word;
}
//If the atom has data_remaining set, then must have some children
if(atom->data_remaining > 0) {
current_parent = atom;
level++;
}
//Check if we have data remaining in the parent.
//If not, if atom was the last one in the parent.
//So, move back up one level
//Make sure we haven't overrun any expected sizes in
//parents further up
if(current_parent != root) {
if(current_parent->data_remaining < 0) {
printf("Something wrong: child atom overruns the parent size.");
printf("Parent name is: %s\n",current_parent->name);
exit(0);
}
//We're done getting the children of this parent, move back up.
while (current_parent && current_parent->parent && current_parent->data_remaining == 0) {
current_parent = current_parent->parent;
level--;
}
}
}
if(stco != NULL) {
adjust_stco_offset(stco, chunk_offset_adjust);
}
return root;
}
int main(int argc, char** argv) {
FILE *m4a_file;
char test[5] = "ftyp";
uint32_t *test_convert = (uint32_t*)test;
if(argc < 3) {
printf("Usage: m4mudex <infilename> <outfilename>");
exit(1);
}
m4a_file = fopen(argv[1], "rb");
printf("\nChecking to see if source file has a meta box: \n");
find_meta(m4a_file);
rewind(m4a_file);
printf("\n");
if (m4a_file == NULL) {
printf("Provide the name of an existing m4a file to parse\n");
exit(1);
}
atom_t* m4a_tree = build_tree(m4a_file);
printf("printing modified tree:\n");
print_tree(m4a_tree);
printf("\n");
FILE *out_file;
out_file = fopen(argv[2], "wb");
output_tree(m4a_tree, out_file);
fclose(out_file);
printf("\nVerifying that output file has no meta box: \n");
out_file = fopen(argv[2], "rb");
find_meta(out_file);
}
<commit_msg>Updated and cleaned up<commit_after>/***
* Removes the meta boxes from the provided mpeg4 source file, writing the result
* out to a new file given the provided filename.
*
* This sample program only works for media files that stay within 32-bit box/file sizes.
* If the file is larger than the 32-bit maximum, the following additions could be made:
*
* TODO
* 1. Check for 64-bit boxes size encoding (atom size=1) and adjust accordingly.
* 2. Find the co64 table instead of stco table, and modify those table entries.
*/
#include "stdio.h"
#include "stdint.h"
#include "stdlib.h"
#include "stddef.h"
#include "string.h"
#include <vector>
/* M4A atoms can be either data holders, or containers of other
* atoms. Actually, it's slightly more complicated than that, since there
* are a few choice atoms that are containers that also have data inside of them.
* However, we don't need to worry about this in this utility, since the only
* container that has that property is the "meta" container, but we're just
* removing it, anyway; we don't need to recurse into it.
*
* According to the docs for the m4a file type, we can find meta in the following
* places in the hierarchy:
* meta
* moov.udta.meta
* moov.udta.trak.meta
*
* So, based on that information, we track make sure to check the
* substructure of the necessary containers.
*/
const char *const containers_of_interest = "moov|udta|trak|mdia|minf|stbl";
typedef struct atom_t {
atom_t* parent;
uint32_t len;
char name[5];
uint32_t data_size;
int32_t data_remaining;
unsigned char* data;
std::vector<atom_t*> children;
bool active;
} atom_t;
/***
* Find the next box (atom) starting from the current
* position of the provided m4a file.
*
* Allocates memory for the atom if necessary, and returns
* a new atom_t with information about the new atom.
*/
atom_t* get_next_box(FILE* m4a_file) {
atom_t *atom = (atom_t*)malloc(sizeof(atom_t));
/* Read size in big-endian order */
fread(&atom->len, 4, 1, m4a_file);
atom->active = true;
atom->len = htonl(atom->len);
fread(atom->name, 1, 4, m4a_file);
/* If the standard length word is 1, then we
* expect an 8-byte length immediately follow
* the name.
*
* Also the header is effectively 16 bytes now. */
//if(atom->len == 1) {
/* Read in big-endian order */
// for(i = 7; i >= 0; i--) {
// fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
// }
// atom->data_size = atom->len.word - 16;
//} else {
atom->data_size = atom->len - 8;
//}
/* Initialize the struct depending on whether
* it's a container of interest or just a
* data blob to pass through.
*/
if(strstr(containers_of_interest, atom->name) != 0) {
//If it's a container, mark the size in data_remaining so the main loop
//knows how much to process
atom->data = NULL;
atom->data_remaining = atom->data_size;
} else {
//Otherwise, just throw the data in a char blob
//to dump back out later
atom->data = (unsigned char*)malloc(atom->data_size);;
fread(atom->data, atom->data_size, 1, m4a_file);
atom->data_remaining = 0;
}
return atom;
}
// A little function to look for meta tags in a less structured way
// Just used for testing
// Could possibly result in a false positive if the "meta" tag appears
// in binary data by chance, although my hunch is that this is unlikely.
int find_meta(FILE *m4a_file) {
const char* target = "meta";
unsigned int tmp;
uint32_t i;
for(i = 0; i < strlen(target); i++) {
tmp <<= 8;
tmp |= (unsigned char)target[i];
}
const unsigned int target_checksum = tmp; //Sum of characters in "meta"
uint32_t checksum = 0;
unsigned char c = 0;
unsigned char buffer[8] = {0,0,0,0,0,0,0,0};
int index = 0;
while(fread(&c, 1, 1, m4a_file) > 0) {
index++;
buffer[index & 7] = c;
checksum <<= 8;
checksum |= c;
if(checksum == target_checksum) {
printf("Found 'meta' at position %lu\n", index - strlen(target));
return index;
}
}
printf("found no meta box in all %d positions\n",index);
return -1;
}
/* Print out the atom tree representation
* on stdout
*/
void print_tree_rec(atom_t* node, uint8_t level) {
uint8_t i;
for(i=0; i<level; i++) {
printf(".");
}
//skip root content, it's not *really* an atom
if(node->parent != NULL) {
printf("%u %s\n", node->len, node->name);
}
for(i=0; i<node->children.size(); i++) {
if(node->children[i]->active == true) {
print_tree_rec(node->children[i], level+1);
}
}
}
void print_tree(atom_t* node) {
print_tree_rec(node, 0);
}
//Write the atoms back out to file.
void output_tree(atom_t* node, FILE *out_file) {
uint32_t i;
//skip root content, it's not *really* an atom
if(node->parent != NULL) {
uint32_t out_len = htonl(node->len);
fwrite(&out_len, 4, 1, out_file);
fwrite(node->name, 4, 1, out_file);
if(node->data_size > 0 && node->data != NULL) {
fwrite(node->data, node->data_size, 1, out_file);
}
}
for(i=0; i < node->children.size(); i++) {
if(node->children[i]->active == true) {
output_tree(node->children[i], out_file);
}
}
}
//Given an atom that we expect to be a stco block,
//and an offset_adjustment, fix the data portion of the
//atom so that the offsets are reduced by the adjustment
//amount
void adjust_stco_offset(atom_t *stco, int offset_adjust) {
int i;
//Offset past the version byte
unsigned char* stco_data_ptr = (stco->data + 4);
int stco_entries = htonl(*((uint32_t*)(stco_data_ptr)));
//Ofset version bytes and length bytes
stco_data_ptr = stco->data + 8;
//Read the bytes in big-endian order,
//subtract offset,
//write back out.
for(i = 0; i < stco_entries; i++) {
uint32_t stco_offset = htonl(*((uint32_t*)(stco_data_ptr)));
stco_offset -= offset_adjust;
*((uint32_t*)stco_data_ptr) = htonl(stco_offset);
stco_data_ptr += 4;
}
}
//Strip meta boxes, returning the size of
//meta tags before mdat boxes for later
//adjustment.
void strip_meta_box_rec(atom_t *node, bool do_accumulate, uint32_t &accumulator, atom_t **stco) {
uint32_t i;
if(strncmp(node->name, "mdat", 4) == 0) {
do_accumulate = false;
} else if(strncmp(node->name, "stco", 4) == 0) {
*stco = node;
} else if(do_accumulate && strncmp(node->name, "meta", 4) == 0) {
accumulator += node->len;
node->active = false;
}
for(i = 0; i < node->children.size(); i++) {
strip_meta_box_rec(node->children[i], do_accumulate, accumulator, stco);
}
}
void strip_meta_box(atom_t *node) {
uint32_t offset_adjust = 0;
atom_t* stco;
strip_meta_box_rec(node, true, offset_adjust, &stco);
adjust_stco_offset(stco, offset_adjust);
}
//Create a representation of the tree structure of the atoms
//This function is called recursively. If an atom is marked as a
//container, move through the data section of the atom sub-atom
//at a time, otherwise just dump the whole data thing into a blob.
atom_t* build_tree(FILE* m4a_file) {
//Place to hold the current working atom.
atom_t *atom;
//Create an abstract root node to hold the top-level
//atom list.
atom_t *root = (atom_t*)calloc(sizeof(atom_t), 1);
atom_t *current_parent = root;
/* Loop through the rest of the atoms */
while((atom = get_next_box(m4a_file))->len > 0) {
//Set the parent of the newly created atom
atom->parent = current_parent;
//Add new atom to the current parent list.
current_parent->children.push_back(atom);
//Subtract size of current atom from
//the data_remaining of the parent
//Note: this must occur before the next step
//which might change the level. Don't try to
//include it in the following step.
if(current_parent != root) {
current_parent->data_remaining -= atom->len;
}
//If the atom has data_remaining set, then must have some children
if(atom->data_remaining > 0) {
current_parent = atom;
}
//Check if we have data remaining in the parent.
//If not, if atom was the last one in the parent.
//So, move back up one level
if(current_parent != root) {
//Make sure we haven't overrun any expected sizes in the parent
if(current_parent->data_remaining < 0) {
printf("Something wrong: child atom overruns the parent size.");
printf("Parent name is: %s\n",current_parent->name);
exit(0);
}
//We're done getting the children of this parent, move back up.
while (current_parent && current_parent->parent && current_parent->data_remaining == 0) {
current_parent = current_parent->parent;
}
}
}
return root;
}
int main(int argc, char** argv) {
FILE *m4a_file;
FILE *out_file;
//Check inputs, open file, check for success
if(argc < 3) {
printf("Usage: m4mudex <infilename> <outfilename>");
exit(1);
}
m4a_file = fopen(argv[1], "rb");
if (m4a_file == NULL) {
printf("Provide the name of an existing m4a file to parse\n");
exit(1);
}
//Quick sanity check on input file
printf("\nChecking to see if source file has a meta box: \n");
find_meta(m4a_file);
rewind(m4a_file);
//Build the tree
atom_t* m4a_tree = build_tree(m4a_file);
//Show the tree
printf("printing original tree:\n");
print_tree(m4a_tree);
printf("\n");
//Get rid of metas and adjust offsets
strip_meta_box(m4a_tree);
//Show the modified tree
printf("printing modifiedtree:\n");
print_tree(m4a_tree);
printf("\n");
//Write out the modified tree.
out_file = fopen(argv[2], "wb");
output_tree(m4a_tree, out_file);
fclose(out_file);
//Verify the output file
printf("\nVerifying that output file has no meta box: \n");
out_file = fopen(argv[2], "rb");
find_meta(out_file);
}
<|endoftext|> |
<commit_before>#include "./center_force.h"
#include <vector>
#include "./label_state.h"
namespace Forces
{
CenterForce::CenterForce() : Force("Center", 0.1f)
{
}
void CenterForce::beforeAll(std::vector<LabelState> &labels)
{
Eigen::Vector2f anchorPositionSum;
for (auto &labelState : labels)
anchorPositionSum += labelState.anchorPosition2D;
if (labels.size() > 0)
averageCenter = anchorPositionSum / labels.size();
else
averageCenter = Eigen::Vector2f(0, 0);
}
Eigen::Vector2f CenterForce::calculate(LabelState &label,
std::vector<LabelState> &labels)
{
return (label.anchorPosition2D - averageCenter).normalized();
}
} // namespace Forces
<commit_msg>Fix uninitialized local variable.<commit_after>#include "./center_force.h"
#include <vector>
#include "./label_state.h"
namespace Forces
{
CenterForce::CenterForce() : Force("Center", 0.1f)
{
}
void CenterForce::beforeAll(std::vector<LabelState> &labels)
{
Eigen::Vector2f anchorPositionSum(0, 0);
for (auto &labelState : labels)
anchorPositionSum += labelState.anchorPosition2D;
if (labels.size() > 0)
averageCenter = anchorPositionSum / labels.size();
else
averageCenter = Eigen::Vector2f(0, 0);
}
Eigen::Vector2f CenterForce::calculate(LabelState &label,
std::vector<LabelState> &labels)
{
return (label.anchorPosition2D - averageCenter).normalized();
}
} // namespace Forces
<|endoftext|> |
<commit_before>#include "geometry.hpp"
Segment::Segment()
{
p1=sf::Vector2f(0.f,0.f);
p2=sf::Vector2f(0.f,0.f);
}
Segment::Segment(sf::Vector2f pointA, sf::Vector2f pointB)
{
p1=pointA;
p2=pointB;
}
const sf::Vector2f Segment::intersection_time(const Segment &other) const
{
auto dir1 = p2 - p1;
auto dir2 = other.p2 - other.p1;
/*
Now we try to solve p1 + t1 * dir1 = other.p1 + t2 * dir2
This is a system of two linear equations
*/
float a = dir1.x;
float b = -dir2.x;
float c = dir1.y;
float d = -dir2.y;
float det = (a * d - b * c);
if (-epsilon <= det && det <= epsilon) {
return sf::Vector2f(-42, -42); // Segments are parallel
}
float e = other.p1.x - p1.x;
float f = other.p1.y - p1.x;
float t1 = (d * e - b * f) / det;
float t2 = (-c * e + a * f) / det;
return sf::Vector2f(t1, t2);
}
const sf::Vector2f Segment::intersection(const Segment &other) const {
sf::Vector2f it = intersection_time(other);
if (check(it.x) && check(it.y)) {
// Intersection
return interp(p1, p2, it.x);
}
return sf::Vector2f(-42, -42);
};
void Segment::intersection_triangle(const sf::Vector2f lumiere,
const Segment &tri, std::vector<Segment> &result) {
Segment tri1 = Segment(lumiere, tri.p1);
Segment tri2 = Segment(lumiere, tri.p2);
sf::Vector2f it1 = intersection_time(tri1);
sf::Vector2f it2 = intersection_time(tri2);
sf::Vector2f it3 = intersection_time(tri);
sf::Vector2f si1 = interp(lumiere, tri.p1, it1.y);
sf::Vector2f si2 = interp(lumiere, tri.p2, it2.y);
sf::Vector2f si3 = interp(tri.p1, tri.p2, it3.y);
if (!(check(it1.y) || check(it2.y) || check(it3.y))) {
// La droite du segment ne passe pas dans le triangle
result.push_back(tri);
return;
}
if (!check_strict(it3.y)) {
// La droite coupe les deux cotes principaux
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it2.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it1.x)) {
// On intersecte cote 1
result.push_back(Segment(si1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si2));
return;
}
}
if (!check_strict(it1.y)) {
// On coupe cote 2 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it3.x < it2.x) {
pp1 = p1; pp2 = p2; u = it3.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it3.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(Segment(tri.p1, si3));
result.push_back(Segment(si3, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si2));
return;
}
} else {
// On coupe cote 1 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it3.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it3.x;
} else {
pp1 = p2; pp2 = p1; u = it3.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si3));
result.push_back(Segment(si3, tri.p2));
return;
} else {
// On intersecte cote 1
result.push_back(Segment(si1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
}
};
<commit_msg>Triangle splitter should work<commit_after>#include "geometry.hpp"
Segment::Segment()
{
p1=sf::Vector2f(0.f,0.f);
p2=sf::Vector2f(0.f,0.f);
}
Segment::Segment(sf::Vector2f pointA, sf::Vector2f pointB)
{
p1=pointA;
p2=pointB;
}
const sf::Vector2f Segment::intersection_time(const Segment &other) const
{
auto dir1 = p2 - p1;
auto dir2 = other.p2 - other.p1;
/*
Now we try to solve p1 + t1 * dir1 = other.p1 + t2 * dir2
This is a system of two linear equations
*/
float a = dir1.x;
float b = -dir2.x;
float c = dir1.y;
float d = -dir2.y;
float det = (a * d - b * c);
if (-epsilon <= det && det <= epsilon) {
return sf::Vector2f(-42, -42); // Segments are parallel
}
float e = other.p1.x - p1.x;
float f = other.p1.y - p1.x;
float t1 = (d * e - b * f) / det;
float t2 = (-c * e + a * f) / det;
return sf::Vector2f(t1, t2);
}
const sf::Vector2f Segment::intersection(const Segment &other) const {
sf::Vector2f it = intersection_time(other);
if (check(it.x) && check(it.y)) {
// Intersection
return interp(p1, p2, it.x);
}
return sf::Vector2f(-42, -42);
};
void Segment::intersection_triangle(const sf::Vector2f lumiere,
const Segment &tri, std::vector<Segment> &result) {
Segment tri1 = Segment(lumiere, tri.p1);
Segment tri2 = Segment(lumiere, tri.p2);
sf::Vector2f it1 = intersection_time(tri1);
sf::Vector2f it2 = intersection_time(tri2);
sf::Vector2f it3 = intersection_time(tri);
sf::Vector2f si1 = interp(lumiere, tri.p1, it1.y);
sf::Vector2f si2 = interp(lumiere, tri.p2, it2.y);
sf::Vector2f si3 = interp(tri.p1, tri.p2, it3.y);
if (!(check(it1.y) || check(it2.y) || check(it3.y))) {
// La droite du segment ne passe pas dans le triangle
result.push_back(tri);
return;
}
if (!check_strict(it3.y)) {
// La droite coupe les deux cotes principaux
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it2.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it1.x)) {
// On intersecte cote 1
result.push_back(Segment(si1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si2));
return;
}
}
if (!check_strict(it1.y)) {
// On coupe cote 2 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it3.x < it2.x) {
pp1 = p1; pp2 = p2; u = it3.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it3.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(Segment(tri.p1, si3));
result.push_back(Segment(si3, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si2));
return;
}
} else {
// On coupe cote 1 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it3.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it3.x;
} else {
pp1 = p2; pp2 = p1; u = it3.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(Segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(Segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(Segment(tri.p1, inter1));
result.push_back(Segment(pp1, si3));
result.push_back(Segment(si3, tri.p2));
return;
} else {
// On intersecte cote 1
result.push_back(Segment(si1, pp2));
result.push_back(Segment(inter2, tri.p2));
return;
}
}
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imapdlg.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:56:14 $
*
* 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 _IMAPDLG_HXX_
#define _IMAPDLG_HXX_
#ifndef _SVTOOLS_INETTBC_HXX
#include <svtools/inettbc.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#ifndef _GOMISC_HXX
class ImageMap;
#endif
/*************************************************************************
|*
|* Ableitung vom SfxChildWindow als "Behaelter" fuer Float
|*
\************************************************************************/
class Graphic;
class TargetList;
class SVX_DLLPUBLIC SvxIMapDlgChildWindow : public SfxChildWindow
{
public:
SvxIMapDlgChildWindow( Window*, USHORT, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxIMapDlgChildWindow );
static void UpdateIMapDlg( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
};
#ifndef _REDUCED_IMAPDLG_HXX_
#define _REDUCED_IMAPDLG_HXX_
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxIMapDlg;
class SvxIMapDlgItem : public SfxControllerItem
{
SvxIMapDlg& rIMap;
protected:
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
public:
SvxIMapDlgItem( USHORT nId, SvxIMapDlg& rIMapDlg, SfxBindings& rBindings );
};
/*************************************************************************
|*
|*
|*
\************************************************************************/
class IMapOwnData;
class IMapWindow;
class SVX_DLLPUBLIC SvxIMapDlg : public SfxModelessDialog // SfxFloatingWindow
{
friend class IMapOwnData;
friend class IMapWindow;
ToolBox aTbxIMapDlg1;
FixedText aFtURL;
SvtURLBox maURLBox;
FixedText aFtText;
Edit aEdtText;
FixedText maFtTarget;
ComboBox maCbbTarget;
StatusBar aStbStatus;
ImageList maImageList;
ImageList maImageListH;
Size aLastSize;
IMapWindow* pIMapWnd;
IMapOwnData* pOwnData;
void* pCheckObj;
SvxIMapDlgItem aIMapItem;
virtual void Resize();
virtual BOOL Close();
#ifdef _IMAPDLG_PRIVATE
DECL_LINK( TbxClickHdl, ToolBox* );
DECL_LINK( InfoHdl, IMapWindow* );
DECL_LINK( MousePosHdl, IMapWindow* );
DECL_LINK( GraphSizeHdl, IMapWindow* );
DECL_LINK( URLModifyHdl, void* );
DECL_LINK( URLLoseFocusHdl, void* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( TbxUpdateHdl, Timer* );
DECL_LINK( StateHdl, IMapWindow* );
DECL_LINK( MiscHdl, void* );
void DoOpen();
BOOL DoSave();
#endif
public:
SvxIMapDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxIMapDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
void SetImageMap( const ImageMap& rImageMap );
const ImageMap& GetImageMap() const;
void SetTargetList( const TargetList& rTargetList );
const TargetList& GetTargetList() const;
void Update( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void ApplyImageList();
};
/*************************************************************************
|*
|* Defines
|*
\************************************************************************/
#define SVXIMAPDLG() ( (SvxIMapDlg*) ( SfxViewFrame::Current()->GetChildWindow( \
SvxIMapDlgChildWindow::GetChildWindowId() )-> \
GetWindow() ) )
#endif // _REDUCED_IMAPDLG_HXX_
#endif // _IMAPDLG_HXX_
<commit_msg>INTEGRATION: CWS sb59 (1.9.488); FILE MERGED 2006/08/03 13:47:04 cl 1.9.488.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imapdlg.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-10-12 11:45:06 $
*
* 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 _IMAPDLG_HXX_
#define _IMAPDLG_HXX_
#ifndef _SVTOOLS_INETTBC_HXX
#include <svtools/inettbc.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#ifndef _GOMISC_HXX
class ImageMap;
#endif
/*************************************************************************
|*
|* Ableitung vom SfxChildWindow als "Behaelter" fuer Float
|*
\************************************************************************/
class Graphic;
class TargetList;
class SVX_DLLPUBLIC SvxIMapDlgChildWindow : public SfxChildWindow
{
public:
SvxIMapDlgChildWindow( Window*, USHORT, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxIMapDlgChildWindow );
static void UpdateIMapDlg( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
};
#ifndef _REDUCED_IMAPDLG_HXX_
#define _REDUCED_IMAPDLG_HXX_
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxIMapDlg;
class SvxIMapDlgItem : public SfxControllerItem
{
SvxIMapDlg& rIMap;
protected:
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
public:
SvxIMapDlgItem( USHORT nId, SvxIMapDlg& rIMapDlg, SfxBindings& rBindings );
};
/*************************************************************************
|*
|*
|*
\************************************************************************/
class IMapOwnData;
class IMapWindow;
class SVX_DLLPUBLIC SvxIMapDlg : public SfxModelessDialog // SfxFloatingWindow
{
friend class IMapOwnData;
friend class IMapWindow;
using Window::Update;
ToolBox aTbxIMapDlg1;
FixedText aFtURL;
SvtURLBox maURLBox;
FixedText aFtText;
Edit aEdtText;
FixedText maFtTarget;
ComboBox maCbbTarget;
StatusBar aStbStatus;
ImageList maImageList;
ImageList maImageListH;
Size aLastSize;
IMapWindow* pIMapWnd;
IMapOwnData* pOwnData;
void* pCheckObj;
SvxIMapDlgItem aIMapItem;
virtual void Resize();
virtual BOOL Close();
#ifdef _IMAPDLG_PRIVATE
DECL_LINK( TbxClickHdl, ToolBox* );
DECL_LINK( InfoHdl, IMapWindow* );
DECL_LINK( MousePosHdl, IMapWindow* );
DECL_LINK( GraphSizeHdl, IMapWindow* );
DECL_LINK( URLModifyHdl, void* );
DECL_LINK( URLLoseFocusHdl, void* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( TbxUpdateHdl, Timer* );
DECL_LINK( StateHdl, IMapWindow* );
DECL_LINK( MiscHdl, void* );
void DoOpen();
BOOL DoSave();
#endif
public:
SvxIMapDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxIMapDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
void SetImageMap( const ImageMap& rImageMap );
const ImageMap& GetImageMap() const;
void SetTargetList( const TargetList& rTargetList );
const TargetList& GetTargetList() const;
void Update( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void ApplyImageList();
};
/*************************************************************************
|*
|* Defines
|*
\************************************************************************/
#define SVXIMAPDLG() ( (SvxIMapDlg*) ( SfxViewFrame::Current()->GetChildWindow( \
SvxIMapDlgChildWindow::GetChildWindowId() )-> \
GetWindow() ) )
#endif // _REDUCED_IMAPDLG_HXX_
#endif // _IMAPDLG_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbgoutsw.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-11-08 17:11:44 $
*
* 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 __DBGOUTSW_HXX
#define __DBGOUTSW_HXX
#ifdef DEBUG
#include <hash_map>
#include <tox.hxx>
class String;
class SwNode;
class SwTxtAttr;
class SwpHints;
class SfxPoolItem;
class SfxItemSet;
struct SwPosition;
class SwPaM;
class SwNodeNum;
class SwUndo;
class SwUndos;
class SwRect;
class SwFrmFmt;
class SwFrmFmts;
class SwNodes;
class SwRewriter;
class SwNumRuleTbl;
class SwNumRule;
class SwOutlineNodes;
class SwTxtFmtColl;
#define DBG_OUT_HERE printf("%s(%d):", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN printf("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT_HERE_LN printf("%s(%d)\n", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN_LN printf("%s(%d) %s\n", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT(x) printf("%s\n", dbg_out(x))
#define DBG_OUT_LN(x) printf("%s(%d): %s\n", __FILE__, __LINE__, dbg_out(x))
#define DBG_OUT_FN_LN(x) printf("%s: %s\n", __FUNCTION__, dbg_out(x))
extern bool bDbgOutStdErr;
extern bool bDbgOutPrintAttrSet;
const char * dbg_out(const void * pVoid);
const char * dbg_out(const String & aStr);
const char * dbg_out(const SwRect & rRect);
const char * dbg_out(const SwFrmFmt & rFrmFmt);
const char * dbg_out(const SwNode & rNode);
const char * dbg_out(const SwTxtAttr & rAttr);
const char * dbg_out(const SwpHints &rHints);
const char * dbg_out(const SfxPoolItem & rItem);
const char * dbg_out(const SfxPoolItem * pItem);
const char * dbg_out(const SfxItemSet & rSet);
const char * dbg_out(SwNodes & rNodes);
// const char * dbg_out(SwOutlineNodes & rNodes);
const char * dbg_out(const SwPosition & rPos);
const char * dbg_out(const SwPaM & rPam);
const char * dbg_out(const SwNodeNum & rNum);
const char * dbg_out(const SwUndo & rUndo);
const char * dbg_out(const SwUndos & rUndos);
const char * dbg_out(const SwRewriter & rRewriter);
const char * dbg_out(const SwNumRule & rRule);
const char * dbg_out(const SwTxtFmtColl & rFmt);
const char * dbg_out(const SwFrmFmts & rFrmFmts);
const char * dbg_out(const SwNumRuleTbl & rTbl);
template<typename tKey, typename tMember, typename fHashFunction>
String lcl_dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
String aResult("[", RTL_TEXTENCODING_ASCII_US);
typename std::hash_map<tKey, tMember, fHashFunction>::const_iterator aIt;
for (aIt = rMap.begin(); aIt != rMap.end(); aIt++)
{
if (aIt != rMap.begin())
aResult += String(", ", RTL_TEXTENCODING_ASCII_US);
aResult += aIt->first;
char sBuffer[256];
sprintf(sBuffer, "(%p)", aIt->second);
aResult += String(sBuffer, RTL_TEXTENCODING_ASCII_US);
}
aResult += String("]", RTL_TEXTENCODING_ASCII_US);
return aResult;
}
template<typename tKey, typename tMember, typename fHashFunction>
const char * dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
return dbg_out(lcl_dbg_out(rMap));
}
const char * dbg_out(const SwFormToken & rToken);
const char * dbg_out(const SwFormTokens & rTokens);
#endif // DEBUG
#endif // __DBGOUTSW_HXX
<commit_msg>INTEGRATION: CWS writercorehandoff (1.12.172); FILE MERGED 2005/12/20 15:00:15 tra 1.12.172.4: RESYNC: (1.14-1.15); FILE MERGED 2005/09/13 11:19:33 tra 1.12.172.3: RESYNC: (1.13-1.14); FILE MERGED 2005/07/11 06:08:27 tra 1.12.172.2: RESYNC: (1.12-1.13); FILE MERGED 2005/06/06 07:07:21 tra 1.12.172.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbgoutsw.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2006-08-14 15:19:01 $
*
* 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 __DBGOUTSW_HXX
#define __DBGOUTSW_HXX
#ifdef DEBUG
#include <hash_map>
#include <tox.hxx>
class String;
class SwNode;
class SwTxtAttr;
class SwpHints;
class SfxPoolItem;
class SfxItemSet;
struct SwPosition;
class SwPaM;
class SwNodeNum;
class SwUndo;
class SwUndos;
class SwRect;
class SwFrmFmt;
class SwFrmFmts;
class SwNodes;
class SwRewriter;
class SwNumRuleTbl;
class SwNumRule;
class SwOutlineNodes;
class SwTxtFmtColl;
#define DBG_OUT_HERE printf("%s(%d):", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN printf("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT_HERE_LN printf("%s(%d)\n", __FILE__, __LINE__)
#define DBG_OUT_HERE_FN_LN printf("%s(%d) %s\n", __FILE__, __LINE__, __FUNCTION__)
#define DBG_OUT(x) printf("%s\n", dbg_out(x))
#define DBG_OUT_LN(x) printf("%s(%d): %s\n", __FILE__, __LINE__, dbg_out(x))
#define DBG_OUT_FN_LN(x) printf("%s: %s\n", __FUNCTION__, dbg_out(x))
extern bool bDbgOutStdErr;
extern bool bDbgOutPrintAttrSet;
const char * dbg_out(const void * pVoid);
const char * dbg_out(const String & aStr);
const char * dbg_out(const SwRect & rRect);
const char * dbg_out(const SwFrmFmt & rFrmFmt);
const char * dbg_out(const SwNode & rNode);
const char * dbg_out(const SwTxtAttr & rAttr);
const char * dbg_out(const SwpHints &rHints);
const char * dbg_out(const SfxPoolItem & rItem);
const char * dbg_out(const SfxPoolItem * pItem);
const char * dbg_out(const SfxItemSet & rSet);
const char * dbg_out(SwNodes & rNodes);
// const char * dbg_out(SwOutlineNodes & rNodes);
const char * dbg_out(const SwPosition & rPos);
const char * dbg_out(const SwPaM & rPam);
const char * dbg_out(const SwNodeNum & rNum);
const char * dbg_out(const SwUndo & rUndo);
const char * dbg_out(const SwUndos & rUndos);
const char * dbg_out(const SwRewriter & rRewriter);
const char * dbg_out(const SwNumRule & rRule);
const char * dbg_out(const SwTxtFmtColl & rFmt);
const char * dbg_out(const SwFrmFmts & rFrmFmts);
const char * dbg_out(const SwNumRuleTbl & rTbl);
template<typename tKey, typename tMember, typename fHashFunction>
String lcl_dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
String aResult("[", RTL_TEXTENCODING_ASCII_US);
typename std::hash_map<tKey, tMember, fHashFunction>::const_iterator aIt;
for (aIt = rMap.begin(); aIt != rMap.end(); aIt++)
{
if (aIt != rMap.begin())
aResult += String(", ", RTL_TEXTENCODING_ASCII_US);
aResult += aIt->first;
char sBuffer[256];
sprintf(sBuffer, "(%p)", aIt->second);
aResult += String(sBuffer, RTL_TEXTENCODING_ASCII_US);
}
aResult += String("]", RTL_TEXTENCODING_ASCII_US);
return aResult;
}
template<typename tKey, typename tMember, typename fHashFunction>
const char * dbg_out(const std::hash_map<tKey, tMember, fHashFunction> & rMap)
{
return dbg_out(lcl_dbg_out(rMap));
}
const char * dbg_out(const SwFormToken & rToken);
const char * dbg_out(const SwFormTokens & rTokens);
#endif // DEBUG
#endif // __DBGOUTSW_HXX
<|endoftext|> |
<commit_before>/**
* A set of functions and method which assist the main function to set up
* the requested feature of the Intelligent Automation System.
*
* @date Jul 2, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <string>
#include <iostream>
#include <openssl/conf.h>
#include <openssl/engine.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
// Application dependencies.
#include <ias/application/constants.h>
#include <ias/application/client/client_application.h>
#include <ias/application/controller_application.h>
#include <ias/application/server_application.h>
#include <ias/main.h>
#include <ias/util/util.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
int main( const int argc , const char ** argv ) {
initializeSsl();
if( controllerRequested(argc,argv) )
startController(argc,argv);
else
if( serverRequested(argc,argv) )
startServer(argc,argv);
else
if( clientRequested(argc,argv) )
startClient(argc,argv);
else
usage();
cleanupSsl();
cleanupLogger();
return ( 0 );
}
void startController( const int argc , const char ** argv ) {
ControllerApplication application(argc,argv);
application.run();
}
void startClient( const int argc , const char ** argv ) {
ClientApplication application(argc,argv);
application.run();
}
void startServer( const int argc , const char ** argv ) {
ServerApplication application(argc,argv);
application.run();
}
bool serverRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagServer) );
}
bool clientRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagClient) );
}
bool controllerRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagController) );
}
void usage( void ) {
std::cout << kVersion << std::endl;
std::cout << "Basic usage: " << std::endl;
std::cout << "Run as server: ias --server --config <path>" << std::endl;
std::cout << "Run as controller: ias --controller --config <path>" << std::endl;
std::cout << "Run as client: ias --client [options]" << std::endl;
std::cout << "Run as eventstream: ias --eventstream --key <API key>" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " --address [hostname]" << std::endl;
}
void initializeSsl( void ) {
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
void cleanupSsl( void ) {
CONF_modules_free();
ERR_remove_state(0);
ENGINE_cleanup();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
}
void cleanupLogger( void ) {
Logger::cleanup();
}
<commit_msg>Modify options of usage function.<commit_after>/**
* A set of functions and method which assist the main function to set up
* the requested feature of the Intelligent Automation System.
*
* @date Jul 2, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <string>
#include <iostream>
#include <openssl/conf.h>
#include <openssl/engine.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
// Application dependencies.
#include <ias/application/constants.h>
#include <ias/application/client/client_application.h>
#include <ias/application/controller_application.h>
#include <ias/application/server_application.h>
#include <ias/main.h>
#include <ias/util/util.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
int main( const int argc , const char ** argv ) {
initializeSsl();
if( controllerRequested(argc,argv) )
startController(argc,argv);
else
if( serverRequested(argc,argv) )
startServer(argc,argv);
else
if( clientRequested(argc,argv) )
startClient(argc,argv);
else
usage();
cleanupSsl();
cleanupLogger();
return ( 0 );
}
void startController( const int argc , const char ** argv ) {
ControllerApplication application(argc,argv);
application.run();
}
void startClient( const int argc , const char ** argv ) {
ClientApplication application(argc,argv);
application.run();
}
void startServer( const int argc , const char ** argv ) {
ServerApplication application(argc,argv);
application.run();
}
bool serverRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagServer) );
}
bool clientRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagClient) );
}
bool controllerRequested( const int argc , const char ** argv ) {
return ( flagSpecified(argc,argv,kFlagController) );
}
void usage( void ) {
std::cout << kVersion << std::endl;
std::cout << "Basic usage: " << std::endl;
std::cout << "Run as server: ias --server --config <path>" << std::endl;
std::cout << "Run as controller: ias --controller --config <path>" << std::endl;
std::cout << "Run as client: ias --client [options]" << std::endl;
std::cout << "Run as eventstream: ias --eventstream --key <API key> [options]" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " --address [hostname]" << std::endl;
std::cout << " --ssl" << std::endl;
}
void initializeSsl( void ) {
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
void cleanupSsl( void ) {
CONF_modules_free();
ERR_remove_state(0);
ENGINE_cleanup();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
}
void cleanupLogger( void ) {
Logger::cleanup();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 tildearrow
*
* 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.
*/
#ifdef _WIN32
#define FONT "C:\\Windows\\Fonts\\segoeui.ttf"
#elif __APPLE__
#define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf"
#elif __linux__
#define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf"
#else
#warning "really? please tell me if you are compiling on this OS"
#endif
#include "includes.h"
#include "font.h"
#include "ui.h"
#include "gfxeditor.h"
SDL_Window* mainWindow;
SDL_Renderer* mainRenderer;
SDL_Event* event;
int mouseX;
int mouseY;
unsigned int mouseB;
unsigned int mouseBold;
SDL_Color color[16];
bool willquit;
uisystem* ui;
gfxeditor* geditor;
font* mainFont;
int curview;
int cureditid, curedittype;
const char* viewname[9]={"Graphics","Audio","Entity Types","Scenes","Functions","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear"};
struct graphic {
string name;
int id;
int width;
int height;
int originX, originY;
int subgraphics;
bool background;
unsigned char** data;
int colmode;
unsigned char** colmask;
};
struct audio {
string name;
int id;
int size;
float* data;
int finaltype;
};
struct etype {
string name;
int id;
int initialgraphic;
int initialsubgraphic;
int parent;
int category;
std::vector<string> eventcode;
string headercode;
};
struct viewport {
SDL_Rect view, port;
float viewangle, portangle;
};
struct scene {
string name;
int id;
int width;
int height;
bool freeze;
std::vector<viewport> viewports;
};
struct function {
string name;
int id;
string code;
};
std::vector<graphic> graphics;
std::vector<audio> sounds;
std::vector<etype> etypes;
std::vector<scene> scenes;
std::vector<function> functions;
void doNothing(){
printf("hello world!\n");
}
void drawScreen() {
SDL_RenderDrawLine(mainRenderer,0,32,1024,32);
if (curview<5) {
SDL_RenderDrawLine(mainRenderer,256,32,256,600);
SDL_RenderDrawLine(mainRenderer,0,53,256,53);
mainFont->drawf(128,41,color[0],1,1,"%s List",viewname[curview]);
switch (curview) {
case 0:
for (int i=0; i<graphics.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==0)?(color[1]):(color[0])),0,0,false,graphics[i].name);
}
// also draw graphic editor
geditor->draw();
break;
case 1:
for (int i=0; i<sounds.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==1)?(color[1]):(color[0])),0,0,false,sounds[i].name);
}
break;
case 2:
for (int i=0; i<etypes.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==2)?(color[1]):(color[0])),0,0,false,etypes[i].name);
}
break;
case 3:
for (int i=0; i<scenes.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==3)?(color[1]):(color[0])),0,0,false,scenes[i].name);
}
break;
case 4:
for (int i=0; i<functions.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==4)?(color[1]):(color[0])),0,0,false, functions[i].name);
}
break;
}
}
}
void goGraphicsView() {
curview=0;
}
void goAudioView() {
curview=1;
}
void goETypesView() {
curview=2;
}
void goScenesView() {
curview=3;
}
void goFunctionsView() {
curview=4;
}
void goProjectView() {
curview=5;
}
void goSettingsView() {
curview=6;
}
void goHelpView() {
curview=7;
}
void goAboutView() {
curview=8;
}
void handleMouse() {
if ((mouseB&1)>(mouseBold&1)) { // checks for mouse left pressed
if (mouseX<256 && mouseY>64) {
cureditid=(mouseY-64)/20;
curedittype=curview;
}
}
}
void makeNewResource() {
// make new resource
int formersize;
switch (curview) {
case 0:
formersize=graphics.size();
graphics.resize(formersize+1);
graphics[formersize].id=formersize;
graphics[formersize].name="graphic";
graphics[formersize].name+=std::to_string(formersize);
break;
case 1:
formersize=sounds.size();
sounds.resize(formersize+1);
sounds[formersize].id=formersize;
sounds[formersize].name="sound";
sounds[formersize].name+=std::to_string(formersize);
break;
case 2:
formersize=etypes.size();
etypes.resize(formersize+1);
etypes[formersize].id=formersize;
etypes[formersize].name="type";
etypes[formersize].name+=std::to_string(formersize);
break;
case 3:
formersize=scenes.size();
scenes.resize(formersize+1);
scenes[formersize].id=formersize;
scenes[formersize].name="scene";
scenes[formersize].name+=std::to_string(formersize);
break;
case 4:
formersize=functions.size();
functions.resize(formersize+1);
functions[formersize].id=formersize;
functions[formersize].name="func";
functions[formersize].name+=std::to_string(formersize);
break;
}
}
int main() {
willquit=false;
// init everything
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
ui=new uisystem;
event=new SDL_Event;
string title;
title="LowerTriad";
mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE);
if (!mainWindow) {
printf("i'm sorry, but window can't be created: %s\n",SDL_GetError());
return 1;
}
mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
// initialize UI
mainFont=new font;
mainFont->setrenderer(mainRenderer);
if (!mainFont->load(FONT,14)) {
printf("can't load font, which means this application is going to crash now...\n");
}
ui->setrenderer(mainRenderer);
color[0].r=192; color[0].g=192; color[0].b=192; color[0].a=255; // main
color[1].r=255; color[1].g=255; color[1].b=255; color[1].a=255; // alternate
color[2].r=0; color[2].g=255; color[2].b=0; color[2].a=255; // success
color[3].r=255; color[3].g=255; color[3].b=0; color[3].a=255; // ongoing
color[4].r=255; color[4].g=0; color[4].b=0; color[4].a=255; // failure
ui->setfont(mainFont);
ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color[0],color[0],doNothing);
ui->addbutton(48,0,40,22,"Build","Build game",color[0],color[0],doNothing);
ui->addbutton(100,0,32,22,"Run","Run compiled game",color[0],color[0],doNothing);
ui->addbutton(132,0,56,22,"Package","Create package",color[0],color[0],doNothing);
ui->addbutton(200,0,64,22,"Graphics","",color[0],color[0],goGraphicsView);
ui->addbutton(264,0,50,22,"Audio","Sound/Music",color[0],color[0],goAudioView);
ui->addbutton(314,0,80,22,"EntityTypes","",color[0],color[0],goETypesView);
ui->addbutton(394,0,50,22,"Scenes","",color[0],color[0],goScenesView);
ui->addbutton(444,0,72,22,"Functions","",color[0],color[0],goFunctionsView);
ui->addbutton(516,0,60,22,"Project","",color[0],color[0],goProjectView);
ui->addbutton(1024-160,0,60,22,"Settings","",color[0],color[0],goSettingsView);
ui->addbutton(1024-100,0,50,22,"Help","",color[0],color[0],goHelpView);
ui->addbutton(1024-50,0,50,22,"About","",color[0],color[0],goAboutView);
ui->addbutton(225,32,32,22,"Add","Add a new resource",color[0],color[0],makeNewResource);
ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold);
// initialize graphic editor
geditor=new gfxeditor;
geditor->setfont(mainFont);
// initialize IDE variables
cureditid=-1; curedittype=0; curview=0;
while (1) {
// check events
while (SDL_PollEvent(event)) {
if (event->type==SDL_QUIT) {
willquit=true;
}
}
SDL_SetRenderDrawColor(mainRenderer,0,0,0,0);
SDL_RenderClear(mainRenderer);
SDL_SetRenderDrawColor(mainRenderer,color[0].r,color[0].g,color[0].b,color[0].a);
mouseBold=mouseB;
mouseB=SDL_GetMouseState(&mouseX, &mouseY);
handleMouse();
drawScreen();
ui->drawall();
SDL_RenderPresent(mainRenderer);
if (willquit) {
break;
}
}
return 0;
}
<commit_msg>more graphic editor stuff<commit_after>/*
* Copyright (c) 2016 tildearrow
*
* 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.
*/
#ifdef _WIN32
#define FONT "C:\\Windows\\Fonts\\segoeui.ttf"
#elif __APPLE__
#define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf"
#elif __linux__
#define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf"
#else
#warning "really? please tell me if you are compiling on this OS"
#endif
#include "includes.h"
#include "font.h"
#include "ui.h"
#include "gfxeditor.h"
SDL_Window* mainWindow;
SDL_Renderer* mainRenderer;
SDL_Event* event;
int mouseX;
int mouseY;
unsigned int mouseB;
unsigned int mouseBold;
SDL_Color color[16];
bool willquit;
uisystem* ui;
gfxeditor* geditor;
font* mainFont;
int curview;
int cureditid, curedittype;
const char* viewname[9]={"Graphics","Audio","Entity Types","Scenes","Functions","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear"};
struct graphic {
string name;
int id;
int width;
int height;
int originX, originY;
int subgraphics;
bool background;
std::vector<unsigned char*> data;
int colmode;
unsigned char** colmask;
};
struct audio {
string name;
int id;
int size;
float* data;
int finaltype;
};
struct etype {
string name;
int id;
int initialgraphic;
int initialsubgraphic;
int parent;
int category;
std::vector<string> eventcode;
string headercode;
};
struct viewport {
SDL_Rect view, port;
float viewangle, portangle;
};
struct scene {
string name;
int id;
int width;
int height;
bool freeze;
std::vector<viewport> viewports;
};
struct function {
string name;
int id;
string code;
};
std::vector<graphic> graphics;
std::vector<audio> sounds;
std::vector<etype> etypes;
std::vector<scene> scenes;
std::vector<function> functions;
void doNothing(){
printf("hello world!\n");
}
void drawScreen() {
SDL_RenderDrawLine(mainRenderer,0,32,1024,32);
if (curview<5) {
SDL_RenderDrawLine(mainRenderer,256,32,256,600);
SDL_RenderDrawLine(mainRenderer,0,53,256,53);
mainFont->drawf(128,41,color[0],1,1,"%s List",viewname[curview]);
switch (curview) {
case 0:
for (int i=0; i<graphics.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==0)?(color[1]):(color[0])),0,0,false,graphics[i].name);
}
// also draw graphic editor
geditor->draw();
break;
case 1:
for (int i=0; i<sounds.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==1)?(color[1]):(color[0])),0,0,false,sounds[i].name);
}
break;
case 2:
for (int i=0; i<etypes.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==2)?(color[1]):(color[0])),0,0,false,etypes[i].name);
}
break;
case 3:
for (int i=0; i<scenes.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==3)?(color[1]):(color[0])),0,0,false,scenes[i].name);
}
break;
case 4:
for (int i=0; i<functions.size(); i++) {
mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==4)?(color[1]):(color[0])),0,0,false, functions[i].name);
}
break;
}
}
}
void goGraphicsView() {
curview=0;
}
void goAudioView() {
curview=1;
}
void goETypesView() {
curview=2;
}
void goScenesView() {
curview=3;
}
void goFunctionsView() {
curview=4;
}
void goProjectView() {
curview=5;
}
void goSettingsView() {
curview=6;
}
void goHelpView() {
curview=7;
}
void goAboutView() {
curview=8;
}
void handleMouse() {
if ((mouseB&1)>(mouseBold&1)) { // checks for mouse left pressed
if (mouseX<256 && mouseY>64) {
cureditid=(mouseY-64)/20;
curedittype=curview;
switch (curview) {
case 0: geditor->setdata(graphics[cureditid].data[0], graphics[cureditid].width, graphics[cureditid].height); break;
}
}
}
}
void makeNewResource() {
// make new resource
int formersize;
switch (curview) {
case 0:
formersize=graphics.size();
graphics.resize(formersize+1);
graphics[formersize].id=formersize;
graphics[formersize].name="graphic";
graphics[formersize].name+=std::to_string(formersize);
// create pre-defined graphic
graphics[formersize].subgraphics=1;
graphics[formersize].width=32;
graphics[formersize].height=32;
graphics[formersize].data.resize(1);
graphics[formersize].data[0]=new unsigned char[4096];
break;
case 1:
formersize=sounds.size();
sounds.resize(formersize+1);
sounds[formersize].id=formersize;
sounds[formersize].name="sound";
sounds[formersize].name+=std::to_string(formersize);
break;
case 2:
formersize=etypes.size();
etypes.resize(formersize+1);
etypes[formersize].id=formersize;
etypes[formersize].name="type";
etypes[formersize].name+=std::to_string(formersize);
break;
case 3:
formersize=scenes.size();
scenes.resize(formersize+1);
scenes[formersize].id=formersize;
scenes[formersize].name="scene";
scenes[formersize].name+=std::to_string(formersize);
break;
case 4:
formersize=functions.size();
functions.resize(formersize+1);
functions[formersize].id=formersize;
functions[formersize].name="func";
functions[formersize].name+=std::to_string(formersize);
break;
}
}
int main() {
willquit=false;
// init everything
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
ui=new uisystem;
event=new SDL_Event;
string title;
title="LowerTriad";
mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE);
if (!mainWindow) {
printf("i'm sorry, but window can't be created: %s\n",SDL_GetError());
return 1;
}
mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
// initialize UI
mainFont=new font;
mainFont->setrenderer(mainRenderer);
if (!mainFont->load(FONT,14)) {
printf("can't load font, which means this application is going to crash now...\n");
}
ui->setrenderer(mainRenderer);
color[0].r=192; color[0].g=192; color[0].b=192; color[0].a=255; // main
color[1].r=255; color[1].g=255; color[1].b=255; color[1].a=255; // alternate
color[2].r=0; color[2].g=255; color[2].b=0; color[2].a=255; // success
color[3].r=255; color[3].g=255; color[3].b=0; color[3].a=255; // ongoing
color[4].r=255; color[4].g=0; color[4].b=0; color[4].a=255; // failure
ui->setfont(mainFont);
ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color[0],color[0],doNothing);
ui->addbutton(48,0,40,22,"Build","Build game",color[0],color[0],doNothing);
ui->addbutton(100,0,32,22,"Run","Run compiled game",color[0],color[0],doNothing);
ui->addbutton(132,0,56,22,"Package","Create package",color[0],color[0],doNothing);
ui->addbutton(200,0,64,22,"Graphics","",color[0],color[0],goGraphicsView);
ui->addbutton(264,0,50,22,"Audio","Sound/Music",color[0],color[0],goAudioView);
ui->addbutton(314,0,80,22,"EntityTypes","",color[0],color[0],goETypesView);
ui->addbutton(394,0,50,22,"Scenes","",color[0],color[0],goScenesView);
ui->addbutton(444,0,72,22,"Functions","",color[0],color[0],goFunctionsView);
ui->addbutton(516,0,60,22,"Project","",color[0],color[0],goProjectView);
ui->addbutton(1024-160,0,60,22,"Settings","",color[0],color[0],goSettingsView);
ui->addbutton(1024-100,0,50,22,"Help","",color[0],color[0],goHelpView);
ui->addbutton(1024-50,0,50,22,"About","",color[0],color[0],goAboutView);
ui->addbutton(225,32,32,22,"Add","Add a new resource",color[0],color[0],makeNewResource);
ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold);
// initialize graphic editor
geditor=new gfxeditor;
geditor->setfont(mainFont);
// initialize IDE variables
cureditid=-1; curedittype=0; curview=0;
while (1) {
// check events
while (SDL_PollEvent(event)) {
if (event->type==SDL_QUIT) {
willquit=true;
}
}
SDL_SetRenderDrawColor(mainRenderer,0,0,0,0);
SDL_RenderClear(mainRenderer);
SDL_SetRenderDrawColor(mainRenderer,color[0].r,color[0].g,color[0].b,color[0].a);
mouseBold=mouseB;
mouseB=SDL_GetMouseState(&mouseX, &mouseY);
handleMouse();
drawScreen();
ui->drawall();
SDL_RenderPresent(mainRenderer);
if (willquit) {
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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 "Output.hxx"
#include "Error.hxx"
#include "event/SocketEvent.hxx"
#include "event/TimerEvent.hxx"
#include "direct.hxx"
#include "io/Splice.hxx"
#include "io/FileDescriptor.hxx"
#include "system/Error.hxx"
#include "istream/Bucket.hxx"
#include "istream/Handler.hxx"
#include "istream/Pointer.hxx"
#include "istream/UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/StaticArray.hxx"
#include <was/protocol.h>
#include <sys/uio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
static constexpr Event::Duration was_output_timeout = std::chrono::minutes(2);
class WasOutput final : IstreamHandler {
public:
FileDescriptor fd;
SocketEvent event;
TimerEvent timeout_event;
WasOutputHandler &handler;
IstreamPointer input;
uint64_t sent = 0;
bool known_length = false;
WasOutput(EventLoop &event_loop, FileDescriptor _fd,
UnusedIstreamPtr _input,
WasOutputHandler &_handler)
:fd(_fd),
event(event_loop, BIND_THIS_METHOD(WriteEventCallback),
SocketDescriptor::FromFileDescriptor(fd)),
timeout_event(event_loop, BIND_THIS_METHOD(OnTimeout)),
handler(_handler),
input(std::move(_input), *this, ISTREAM_TO_PIPE) {
ScheduleWrite();
}
void ScheduleWrite() {
event.ScheduleWrite();
timeout_event.Schedule(was_output_timeout);
}
void AbortError(std::exception_ptr ep) {
event.Cancel();
timeout_event.Cancel();
if (input.IsDefined())
input.ClearAndClose();
handler.WasOutputError(ep);
}
bool CheckLength();
void WriteEventCallback(unsigned events) noexcept;
void OnTimeout() noexcept {
AbortError(std::make_exception_ptr(WasError("send timeout")));
}
/* virtual methods from class IstreamHandler */
bool OnIstreamReady() noexcept override;
size_t OnData(const void *data, size_t length) noexcept override;
ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
};
bool
WasOutput::CheckLength()
{
if (known_length)
return true;
off_t available = input.GetAvailable(false);
if (available < 0)
return true;
known_length = true;
return handler.WasOutputLength(sent + available);
}
/*
* libevent callback
*
*/
inline void
WasOutput::WriteEventCallback(unsigned) noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
event.CancelWrite();
timeout_event.Cancel();
if (CheckLength())
input.Read();
}
/*
* istream handler for the request
*
*/
bool
WasOutput::OnIstreamReady() noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
/* collect buckets */
IstreamBucketList list;
try {
input.FillBucketList(list);
} catch (...) {
input.Clear();
AbortError(std::current_exception());
return false;
}
if (list.IsEmpty() && !list.HasMore()) {
/* our input has ended */
input.ClearAndClose();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return false;
handler.WasOutputEof();
return false;
}
/* convert buckets to struct iovec array */
StaticArray<struct iovec, 64> v;
bool more = list.HasMore(), result = false;
size_t total = 0;
for (const auto &i : list) {
if (i.GetType() != IstreamBucket::Type::BUFFER) {
result = true;
more = true;
break;
}
if (v.full()) {
more = true;
break;
}
const auto buffer = i.GetBuffer();
auto &w = v.append();
w.iov_base = const_cast<void *>(buffer.data);
w.iov_len = buffer.size;
total += buffer.size;
}
if (v.empty())
return true;
/* write this struct iovec array */
ssize_t nbytes = writev(fd.Get(), &v.front(), v.size());
if (nbytes < 0) {
int e = errno;
if (e == EAGAIN) {
ScheduleWrite();
return false;
}
AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed")));
return false;
}
input.ConsumeBucketList(nbytes);
if (!more && size_t(nbytes) == total) {
/* we've just reached end of our input */
input.ClearAndClose();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return false;
handler.WasOutputEof();
return false;
}
return result;
}
inline size_t
WasOutput::OnData(const void *p, size_t length) noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
ssize_t nbytes = fd.Write(p, length);
if (gcc_likely(nbytes > 0)) {
sent += nbytes;
ScheduleWrite();
} else if (nbytes < 0) {
if (errno == EAGAIN) {
ScheduleWrite();
return 0;
}
AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed")));
return 0;
}
return (size_t)nbytes;
}
inline ssize_t
WasOutput::OnDirect(gcc_unused FdType type, int source_fd, size_t max_length) noexcept
{
assert(fd.IsDefined());
ssize_t nbytes = SpliceToPipe(source_fd, fd.Get(), max_length);
if (gcc_likely(nbytes > 0)) {
sent += nbytes;
ScheduleWrite();
} else if (nbytes < 0 && errno == EAGAIN) {
if (!fd.IsReadyForWriting()) {
ScheduleWrite();
return ISTREAM_RESULT_BLOCKING;
}
/* try again, just in case fd has become ready between
the first istream_direct_to_pipe() call and
fd.IsReadyForWriting() */
nbytes = SpliceToPipe(source_fd, fd.Get(), max_length);
}
return nbytes;
}
void
WasOutput::OnEof() noexcept
{
assert(input.IsDefined());
input.Clear();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return;
handler.WasOutputEof();
}
void
WasOutput::OnError(std::exception_ptr ep) noexcept
{
assert(input.IsDefined());
input.Clear();
event.Cancel();
timeout_event.Cancel();
handler.WasOutputPremature(sent, ep);
}
/*
* constructor
*
*/
WasOutput *
was_output_new(struct pool &pool, EventLoop &event_loop,
FileDescriptor fd, UnusedIstreamPtr input,
WasOutputHandler &handler)
{
assert(fd.IsDefined());
return NewFromPool<WasOutput>(pool, event_loop, fd,
std::move(input), handler);
}
uint64_t
was_output_free(WasOutput *output)
{
assert(output != nullptr);
if (output->input.IsDefined())
output->input.ClearAndClose();
output->event.Cancel();
output->timeout_event.Cancel();
return output->sent;
}
bool
was_output_check_length(WasOutput &output)
{
return output.CheckLength();
}
<commit_msg>was/Output: call destructor<commit_after>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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 "Output.hxx"
#include "Error.hxx"
#include "event/SocketEvent.hxx"
#include "event/TimerEvent.hxx"
#include "direct.hxx"
#include "io/Splice.hxx"
#include "io/FileDescriptor.hxx"
#include "system/Error.hxx"
#include "istream/Bucket.hxx"
#include "istream/Handler.hxx"
#include "istream/Pointer.hxx"
#include "istream/UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/StaticArray.hxx"
#include <was/protocol.h>
#include <sys/uio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
static constexpr Event::Duration was_output_timeout = std::chrono::minutes(2);
class WasOutput final : IstreamHandler {
public:
FileDescriptor fd;
SocketEvent event;
TimerEvent timeout_event;
WasOutputHandler &handler;
IstreamPointer input;
uint64_t sent = 0;
bool known_length = false;
WasOutput(EventLoop &event_loop, FileDescriptor _fd,
UnusedIstreamPtr _input,
WasOutputHandler &_handler)
:fd(_fd),
event(event_loop, BIND_THIS_METHOD(WriteEventCallback),
SocketDescriptor::FromFileDescriptor(fd)),
timeout_event(event_loop, BIND_THIS_METHOD(OnTimeout)),
handler(_handler),
input(std::move(_input), *this, ISTREAM_TO_PIPE) {
ScheduleWrite();
}
void Destroy() noexcept {
this->~WasOutput();
}
void DestroyEof() noexcept {
auto &_handler = handler;
Destroy();
_handler.WasOutputEof();
}
void DestroyPremature(std::exception_ptr ep) noexcept {
const auto _sent = sent;
auto &_handler = handler;
Destroy();
_handler.WasOutputPremature(_sent, ep);
}
void DestroyError(std::exception_ptr ep) noexcept {
auto &_handler = handler;
Destroy();
_handler.WasOutputError(ep);
}
void ScheduleWrite() {
event.ScheduleWrite();
timeout_event.Schedule(was_output_timeout);
}
void AbortError(std::exception_ptr ep) {
if (input.IsDefined())
input.ClearAndClose();
DestroyError(ep);
}
bool CheckLength();
void WriteEventCallback(unsigned events) noexcept;
void OnTimeout() noexcept {
AbortError(std::make_exception_ptr(WasError("send timeout")));
}
/* virtual methods from class IstreamHandler */
bool OnIstreamReady() noexcept override;
size_t OnData(const void *data, size_t length) noexcept override;
ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
};
bool
WasOutput::CheckLength()
{
if (known_length)
return true;
off_t available = input.GetAvailable(false);
if (available < 0)
return true;
known_length = true;
return handler.WasOutputLength(sent + available);
}
/*
* libevent callback
*
*/
inline void
WasOutput::WriteEventCallback(unsigned) noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
event.CancelWrite();
timeout_event.Cancel();
if (CheckLength())
input.Read();
}
/*
* istream handler for the request
*
*/
bool
WasOutput::OnIstreamReady() noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
/* collect buckets */
IstreamBucketList list;
try {
input.FillBucketList(list);
} catch (...) {
input.Clear();
AbortError(std::current_exception());
return false;
}
if (list.IsEmpty() && !list.HasMore()) {
/* our input has ended */
input.ClearAndClose();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return false;
DestroyEof();
return false;
}
/* convert buckets to struct iovec array */
StaticArray<struct iovec, 64> v;
bool more = list.HasMore(), result = false;
size_t total = 0;
for (const auto &i : list) {
if (i.GetType() != IstreamBucket::Type::BUFFER) {
result = true;
more = true;
break;
}
if (v.full()) {
more = true;
break;
}
const auto buffer = i.GetBuffer();
auto &w = v.append();
w.iov_base = const_cast<void *>(buffer.data);
w.iov_len = buffer.size;
total += buffer.size;
}
if (v.empty())
return true;
/* write this struct iovec array */
ssize_t nbytes = writev(fd.Get(), &v.front(), v.size());
if (nbytes < 0) {
int e = errno;
if (e == EAGAIN) {
ScheduleWrite();
return false;
}
AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed")));
return false;
}
input.ConsumeBucketList(nbytes);
if (!more && size_t(nbytes) == total) {
/* we've just reached end of our input */
input.ClearAndClose();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return false;
DestroyEof();
return false;
}
return result;
}
inline size_t
WasOutput::OnData(const void *p, size_t length) noexcept
{
assert(fd.IsDefined());
assert(input.IsDefined());
ssize_t nbytes = fd.Write(p, length);
if (gcc_likely(nbytes > 0)) {
sent += nbytes;
ScheduleWrite();
} else if (nbytes < 0) {
if (errno == EAGAIN) {
ScheduleWrite();
return 0;
}
AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed")));
return 0;
}
return (size_t)nbytes;
}
inline ssize_t
WasOutput::OnDirect(gcc_unused FdType type, int source_fd, size_t max_length) noexcept
{
assert(fd.IsDefined());
ssize_t nbytes = SpliceToPipe(source_fd, fd.Get(), max_length);
if (gcc_likely(nbytes > 0)) {
sent += nbytes;
ScheduleWrite();
} else if (nbytes < 0 && errno == EAGAIN) {
if (!fd.IsReadyForWriting()) {
ScheduleWrite();
return ISTREAM_RESULT_BLOCKING;
}
/* try again, just in case fd has become ready between
the first istream_direct_to_pipe() call and
fd.IsReadyForWriting() */
nbytes = SpliceToPipe(source_fd, fd.Get(), max_length);
}
return nbytes;
}
void
WasOutput::OnEof() noexcept
{
assert(input.IsDefined());
input.Clear();
event.Cancel();
timeout_event.Cancel();
if (!known_length && !handler.WasOutputLength(sent))
return;
DestroyEof();
}
void
WasOutput::OnError(std::exception_ptr ep) noexcept
{
assert(input.IsDefined());
input.Clear();
DestroyPremature(ep);
}
/*
* constructor
*
*/
WasOutput *
was_output_new(struct pool &pool, EventLoop &event_loop,
FileDescriptor fd, UnusedIstreamPtr input,
WasOutputHandler &handler)
{
assert(fd.IsDefined());
return NewFromPool<WasOutput>(pool, event_loop, fd,
std::move(input), handler);
}
uint64_t
was_output_free(WasOutput *output)
{
assert(output != nullptr);
if (output->input.IsDefined())
output->input.ClearAndClose();
const auto sent = output->sent;
output->Destroy();
return sent;
}
bool
was_output_check_length(WasOutput &output)
{
return output.CheckLength();
}
<|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 "content/common/unix_domain_socket_posix.h"
#include <errno.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/pickle.h"
// static
bool UnixDomainSocket::SendMsg(int fd,
const void* buf,
size_t length,
const std::vector<int>& fds) {
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov = {const_cast<void*>(buf), length};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char* control_buffer = NULL;
if (fds.size()) {
const unsigned control_len = CMSG_SPACE(sizeof(int) * fds.size());
control_buffer = new char[control_len];
struct cmsghdr *cmsg;
msg.msg_control = control_buffer;
msg.msg_controllen = control_len;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fds.size());
memcpy(CMSG_DATA(cmsg), &fds[0], sizeof(int) * fds.size());
msg.msg_controllen = cmsg->cmsg_len;
}
const ssize_t r = HANDLE_EINTR(sendmsg(fd, &msg, 0));
const bool ret = static_cast<ssize_t>(length) == r;
delete[] control_buffer;
return ret;
}
// static
ssize_t UnixDomainSocket::RecvMsg(int fd,
void* buf,
size_t length,
std::vector<int>* fds) {
static const unsigned kMaxDescriptors = 16;
fds->clear();
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov = {buf, length};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char control_buffer[CMSG_SPACE(sizeof(int) * kMaxDescriptors)];
msg.msg_control = control_buffer;
msg.msg_controllen = sizeof(control_buffer);
const ssize_t r = HANDLE_EINTR(recvmsg(fd, &msg, 0));
if (r == -1)
return -1;
int* wire_fds = NULL;
unsigned wire_fds_len = 0;
if (msg.msg_controllen > 0) {
struct cmsghdr* cmsg;
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS) {
const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
DCHECK(payload_len % sizeof(int) == 0);
wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
wire_fds_len = payload_len / sizeof(int);
break;
}
}
}
if (msg.msg_flags & MSG_TRUNC || msg.msg_flags & MSG_CTRUNC) {
for (unsigned i = 0; i < wire_fds_len; ++i)
close(wire_fds[i]);
errno = EMSGSIZE;
return -1;
}
fds->resize(wire_fds_len);
memcpy(&(*fds)[0], wire_fds, sizeof(int) * wire_fds_len);
return r;
}
// static
ssize_t UnixDomainSocket::SendRecvMsg(int fd,
uint8_t* reply,
unsigned max_reply_len,
int* result_fd,
const Pickle& request) {
int fds[2];
// This socketpair is only used for the IPC and is cleaned up before
// returning.
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) == -1)
return false;
std::vector<int> fd_vector;
fd_vector.push_back(fds[1]);
if (!SendMsg(fd, request.data(), request.size(), fd_vector)) {
close(fds[0]);
close(fds[1]);
return -1;
}
close(fds[1]);
fd_vector.clear();
const ssize_t reply_len = RecvMsg(fds[0], reply, max_reply_len, &fd_vector);
close(fds[0]);
if (reply_len == -1)
return -1;
if ((!fd_vector.empty() && result_fd == NULL) || fd_vector.size() > 1) {
for (std::vector<int>::const_iterator
i = fd_vector.begin(); i != fd_vector.end(); ++i) {
close(*i);
}
NOTREACHED();
return -1;
}
if (result_fd)
*result_fd = fd_vector.empty() ? -1 : fd_vector[0];
return reply_len;
}
<commit_msg>Use vector_as_array() in unix_domain_socket_posix.cc<commit_after>// Copyright (c) 2011 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 "content/common/unix_domain_socket_posix.h"
#include <errno.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/pickle.h"
#include "base/stl_util-inl.h"
// static
bool UnixDomainSocket::SendMsg(int fd,
const void* buf,
size_t length,
const std::vector<int>& fds) {
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov = {const_cast<void*>(buf), length};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char* control_buffer = NULL;
if (fds.size()) {
const unsigned control_len = CMSG_SPACE(sizeof(int) * fds.size());
control_buffer = new char[control_len];
struct cmsghdr *cmsg;
msg.msg_control = control_buffer;
msg.msg_controllen = control_len;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fds.size());
memcpy(CMSG_DATA(cmsg), &fds[0], sizeof(int) * fds.size());
msg.msg_controllen = cmsg->cmsg_len;
}
const ssize_t r = HANDLE_EINTR(sendmsg(fd, &msg, 0));
const bool ret = static_cast<ssize_t>(length) == r;
delete[] control_buffer;
return ret;
}
// static
ssize_t UnixDomainSocket::RecvMsg(int fd,
void* buf,
size_t length,
std::vector<int>* fds) {
static const unsigned kMaxDescriptors = 16;
fds->clear();
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov = {buf, length};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char control_buffer[CMSG_SPACE(sizeof(int) * kMaxDescriptors)];
msg.msg_control = control_buffer;
msg.msg_controllen = sizeof(control_buffer);
const ssize_t r = HANDLE_EINTR(recvmsg(fd, &msg, 0));
if (r == -1)
return -1;
int* wire_fds = NULL;
unsigned wire_fds_len = 0;
if (msg.msg_controllen > 0) {
struct cmsghdr* cmsg;
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS) {
const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
DCHECK(payload_len % sizeof(int) == 0);
wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
wire_fds_len = payload_len / sizeof(int);
break;
}
}
}
if (msg.msg_flags & MSG_TRUNC || msg.msg_flags & MSG_CTRUNC) {
for (unsigned i = 0; i < wire_fds_len; ++i)
close(wire_fds[i]);
errno = EMSGSIZE;
return -1;
}
fds->resize(wire_fds_len);
memcpy(vector_as_array(fds), wire_fds, sizeof(int) * wire_fds_len);
return r;
}
// static
ssize_t UnixDomainSocket::SendRecvMsg(int fd,
uint8_t* reply,
unsigned max_reply_len,
int* result_fd,
const Pickle& request) {
int fds[2];
// This socketpair is only used for the IPC and is cleaned up before
// returning.
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) == -1)
return false;
std::vector<int> fd_vector;
fd_vector.push_back(fds[1]);
if (!SendMsg(fd, request.data(), request.size(), fd_vector)) {
close(fds[0]);
close(fds[1]);
return -1;
}
close(fds[1]);
fd_vector.clear();
const ssize_t reply_len = RecvMsg(fds[0], reply, max_reply_len, &fd_vector);
close(fds[0]);
if (reply_len == -1)
return -1;
if ((!fd_vector.empty() && result_fd == NULL) || fd_vector.size() > 1) {
for (std::vector<int>::const_iterator
i = fd_vector.begin(); i != fd_vector.end(); ++i) {
close(*i);
}
NOTREACHED();
return -1;
}
if (result_fd)
*result_fd = fd_vector.empty() ? -1 : fd_vector[0];
return reply_len;
}
<|endoftext|> |
<commit_before>#include "statistic.h"
#include <cassert>
using namespace dariadb::statistic;
using namespace dariadb::statistic::integral;
using namespace dariadb::statistic::average;
class StatisticReadClbk :public dariadb::storage::ReaderClb {
public:
StatisticReadClbk(BaseMethod*m):_method(m)
{
}
void call(const dariadb::Meas&m) {
assert(_method != nullptr);
_method->call(m);
}
BaseMethod*_method;
};
BaseMethod::BaseMethod() {
_is_first = true;
_result = 0;
}
void BaseMethod::call(const dariadb::Meas&m){
if(_is_first){
_last=m;
_is_first=false;
}else{
this->calc(_last,m);
_last=m;
}
}
dariadb::Value BaseMethod::result()const {
return _result;
}
void BaseMethod::fromReader(dariadb::storage::Reader_ptr&ptr, dariadb::Time from, dariadb::Time to, dariadb::Time step) {
std::unique_ptr<StatisticReadClbk> c{ new StatisticReadClbk{ this } };
ptr->readByStep(c.get(), from, to, step);
}
RectangleMethod::RectangleMethod(const RectangleMethod::Kind k):
BaseMethod(),
_kind(k)
{}
void RectangleMethod::calc(const dariadb::Meas&a, const dariadb::Meas&b){
switch (_kind)
{
case Kind::LEFT:
_result += a.value*(b.time - a.time);
break;
case Kind::RIGHT:
_result += b.value*(b.time - a.time);
break;
case Kind::MIDLE:
_result += ((a.value + b.value) / 2.0)*(b.time - a.time);
break;
default:
assert(false);
}
}
Average::Average():BaseMethod() {
_count = 0;
}
void Average::call(const dariadb::Meas&a){
_result += a.value;
_count++;
}
void Average::calc(const dariadb::Meas&, const dariadb::Meas&){
}
dariadb::Value Average::result()const {
assert(_count != 0);
return _result / _count;
}<commit_msg>todo.<commit_after>#include "statistic.h"
#include <cassert>
using namespace dariadb::statistic;
using namespace dariadb::statistic::integral;
using namespace dariadb::statistic::average;
class StatisticReadClbk :public dariadb::storage::ReaderClb {
public:
StatisticReadClbk(BaseMethod*m):_method(m)
{
}
void call(const dariadb::Meas&m) {
assert(_method != nullptr);
_method->call(m);
}
BaseMethod*_method;
};
BaseMethod::BaseMethod() {
_is_first = true;
_result = 0;
}
void BaseMethod::call(const dariadb::Meas&m){
//TODO add check to m.Id. id must be one.
if(_is_first){
_last=m;
_is_first=false;
}else{
this->calc(_last,m);
_last=m;
}
}
dariadb::Value BaseMethod::result()const {
return _result;
}
void BaseMethod::fromReader(dariadb::storage::Reader_ptr&ptr, dariadb::Time from, dariadb::Time to, dariadb::Time step) {
std::unique_ptr<StatisticReadClbk> c{ new StatisticReadClbk{ this } };
ptr->readByStep(c.get(), from, to, step);
}
RectangleMethod::RectangleMethod(const RectangleMethod::Kind k):
BaseMethod(),
_kind(k)
{}
void RectangleMethod::calc(const dariadb::Meas&a, const dariadb::Meas&b){
switch (_kind)
{
case Kind::LEFT:
_result += a.value*(b.time - a.time);
break;
case Kind::RIGHT:
_result += b.value*(b.time - a.time);
break;
case Kind::MIDLE:
_result += ((a.value + b.value) / 2.0)*(b.time - a.time);
break;
default:
assert(false);
}
}
Average::Average():BaseMethod() {
_count = 0;
}
void Average::call(const dariadb::Meas&a){
_result += a.value;
_count++;
}
void Average::calc(const dariadb::Meas&, const dariadb::Meas&){
}
dariadb::Value Average::result()const {
assert(_count != 0);
return _result / _count;
}<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <pandora/util/ReferenceList.hpp>
#include <pandora/PSize.hpp>
#include <pandora/Selection.hpp>
#include <pandora/DataSet.hpp>
using namespace std;
namespace pandora {
namespace util {
const PSize ReferenceList::MIN_CHUNK_SIZE = {1};
const PSize ReferenceList::MAX_SIZE_1D = {H5S_UNLIMITED};
ReferenceList::ReferenceList(const ReferenceList &other)
: group(other.group), ds_name(other.ds_name)
{}
ReferenceList::ReferenceList(const Group &group, const string &ds_name)
: group(group), ds_name(ds_name)
{}
bool ReferenceList::has(const string &id) const {
vector<string> ids = get();
return std::find(ids.begin(), ids.end(), id) != ids.end();
}
vector<string> ReferenceList::get() const {
vector<string> ids;
if (group.hasData(ds_name)) {
DataSet ds = group.openData(ds_name);
ds.read(ids, true);
}
return ids;
}
void ReferenceList::set(const vector<string> &ids) {
if (group.hasData(ds_name)) {
DataSet ds = group.openData(ds_name);
ds.extend({ids.size()});
ds.write(ids);
} else {
DataSet ds = DataSet::create(group.h5Group(), ds_name, ids,
&MAX_SIZE_1D, &MIN_CHUNK_SIZE);
ds.write(ids);
}
}
void ReferenceList::add(const string &id) {
vector<string> new_ids = {id};
if (group.hasData(ds_name)) {
DataSet ds = group.openData("sources");
PSize old_size = ds.size();
PSize new_size = old_size + 1;
ds.extend(new_size);
PSize count = {1};
Selection sel = ds.createSelection();
sel.select(count, old_size);
ds.write(new_ids, sel);
} else {
DataSet ds = DataSet::create(group.h5Group(), ds_name, new_ids,
&MAX_SIZE_1D, &MIN_CHUNK_SIZE);
ds.write(new_ids);
}
}
bool ReferenceList::remove(const string &id) {
bool removed = false;
if (group.hasData(ds_name)) {
vector<string> ids;
DataSet ds = group.openData(ds_name);
ds.read(ids, true);
for (size_t i = 0; i < ids.size(); i++) {
if (ids[i] == id) {
ids.erase(ids.begin() + i);
removed = true;
break;
}
}
if (removed) {
PSize new_size = ds.size();
ds.extend(--new_size);
ds.write(ids);
}
}
return removed;
}
bool ReferenceList::operator==(const ReferenceList &other) const {
return group == other.group && ds_name == other.ds_name;
}
bool ReferenceList::operator!=(const ReferenceList &other) const {
return !(*this == other);
}
ReferenceList& ReferenceList::operator=(const ReferenceList &other) {
if (*this != other) {
this->group = other.group;
this->ds_name = other.ds_name;
}
return *this;
}
ReferenceList::~ReferenceList() {}
} // namespace util
} // namespace pandora
<commit_msg>fixed bug in referenceList<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <pandora/util/ReferenceList.hpp>
#include <pandora/PSize.hpp>
#include <pandora/Selection.hpp>
#include <pandora/DataSet.hpp>
using namespace std;
namespace pandora {
namespace util {
const PSize ReferenceList::MIN_CHUNK_SIZE = {1};
const PSize ReferenceList::MAX_SIZE_1D = {H5S_UNLIMITED};
ReferenceList::ReferenceList(const ReferenceList &other)
: group(other.group), ds_name(other.ds_name)
{}
ReferenceList::ReferenceList(const Group &group, const string &ds_name)
: group(group), ds_name(ds_name)
{}
bool ReferenceList::has(const string &id) const {
vector<string> ids = get();
return std::find(ids.begin(), ids.end(), id) != ids.end();
}
vector<string> ReferenceList::get() const {
vector<string> ids;
if (group.hasData(ds_name)) {
DataSet ds = group.openData(ds_name);
ds.read(ids, true);
}
return ids;
}
void ReferenceList::set(const vector<string> &ids) {
if (group.hasData(ds_name)) {
DataSet ds = group.openData(ds_name);
ds.extend({ids.size()});
ds.write(ids);
} else {
DataSet ds = DataSet::create(group.h5Group(), ds_name, ids,
&MAX_SIZE_1D, &MIN_CHUNK_SIZE);
ds.write(ids);
}
}
void ReferenceList::add(const string &id) {
vector<string> new_ids = {id};
if (group.hasData(ds_name)) {
DataSet ds = group.openData(ds_name);
PSize old_size = ds.size();
PSize new_size = old_size + 1;
ds.extend(new_size);
PSize count = {1};
Selection sel = ds.createSelection();
sel.select(count, old_size);
ds.write(new_ids, sel);
} else {
DataSet ds = DataSet::create(group.h5Group(), ds_name, new_ids,
&MAX_SIZE_1D, &MIN_CHUNK_SIZE);
ds.write(new_ids);
}
}
bool ReferenceList::remove(const string &id) {
bool removed = false;
if (group.hasData(ds_name)) {
vector<string> ids;
DataSet ds = group.openData(ds_name);
ds.read(ids, true);
for (size_t i = 0; i < ids.size(); i++) {
if (ids[i] == id) {
ids.erase(ids.begin() + i);
removed = true;
break;
}
}
if (removed) {
PSize new_size = ds.size();
ds.extend(--new_size);
ds.write(ids);
}
}
return removed;
}
bool ReferenceList::operator==(const ReferenceList &other) const {
return group == other.group && ds_name == other.ds_name;
}
bool ReferenceList::operator!=(const ReferenceList &other) const {
return !(*this == other);
}
ReferenceList& ReferenceList::operator=(const ReferenceList &other) {
if (*this != other) {
this->group = other.group;
this->ds_name = other.ds_name;
}
return *this;
}
ReferenceList::~ReferenceList() {}
} // namespace util
} // namespace pandora
<|endoftext|> |
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2014 VoltDB Inc.
*
* This program 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, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef POOL_HPP_
#define POOL_HPP_
#include <vector>
#include <iostream>
#include <stdint.h>
#include <sys/mman.h>
#include <errno.h>
#include <climits>
#include <string.h>
#include "common/FatalException.hpp"
namespace voltdb {
#ifndef MEMCHECK
/**
* Description of a chunk of memory allocated on the heap
*/
class Chunk {
public:
Chunk()
: m_offset(0), m_size(0), m_chunkData(NULL)
{
}
inline Chunk(uint64_t size, void *chunkData)
: m_offset(0), m_size(size), m_chunkData(static_cast<char*>(chunkData))
{
}
int64_t getSize() const
{
return static_cast<int64_t>(m_size);
}
uint64_t m_offset;
uint64_t m_size;
char *m_chunkData;
};
/*
* Find next higher power of two
* From http://en.wikipedia.org/wiki/Power_of_two
*/
template <class T>
inline T nexthigher(T k) {
if (k == 0)
return 1;
k--;
for (int i=1; i<sizeof(T)*CHAR_BIT; i<<=1)
k = k | k >> i;
return k+1;
}
static const size_t TEMP_POOL_CHUNK_SIZE = 262144;
/**
* A memory pool that provides fast allocation and deallocation. The
* only way to release memory is to free all memory in the pool by
* calling purge.
*/
class Pool {
public:
Pool() :
m_allocationSize(TEMP_POOL_CHUNK_SIZE), m_maxChunkCount(0), m_currentChunkIndex(0)
{
}
Pool(uint64_t allocationSize, uint64_t maxChunkCount) :
#ifdef USE_MMAP
m_allocationSize(nexthigher(allocationSize)),
#else
m_allocationSize(allocationSize),
#endif
m_maxChunkCount(static_cast<std::size_t>(maxChunkCount)),
m_currentChunkIndex(0)
{
}
~Pool() {
for (std::size_t ii = 0; ii < m_chunks.size(); ii++) {
#ifdef USE_MMAP
if (::munmap( m_chunks[ii].m_chunkData, m_chunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_chunks[ii].m_chunkData;
#endif
}
for (std::size_t ii = 0; ii < m_oversizeChunks.size(); ii++) {
#ifdef USE_MMAP
if (::munmap( m_oversizeChunks[ii].m_chunkData, m_oversizeChunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_oversizeChunks[ii].m_chunkData;
#endif
}
}
/*
* Allocate a continous block of memory of the specified size.
*/
inline void* allocate(std::size_t size) {
if (m_chunks.empty()) {
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, m_allocationSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[m_allocationSize];
#endif
m_chunks.push_back(Chunk(m_allocationSize, storage));
}
/*
* See if there is space in the current chunk
*/
Chunk *currentChunk = &m_chunks[m_currentChunkIndex];
if (size > currentChunk->m_size - currentChunk->m_offset) {
/*
* Not enough space. Check if it is greater then our allocation size.
*/
if (size > m_allocationSize) {
/*
* Allocate an oversize chunk that will not be reused.
*/
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, nexthigher(size), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[size];
#endif
m_oversizeChunks.push_back(Chunk(nexthigher(size), storage));
Chunk &newChunk = m_oversizeChunks.back();
newChunk.m_offset = size;
return newChunk.m_chunkData;
}
/*
* Check if there is an already allocated chunk we can use.
*/
m_currentChunkIndex++;
if (m_currentChunkIndex < m_chunks.size()) {
currentChunk = &m_chunks[m_currentChunkIndex];
currentChunk->m_offset = size;
return currentChunk->m_chunkData;
} else {
/*
* Need to allocate a new chunk
*/
// std::cout << "Pool had to allocate a new chunk. Not a good thing "
// "from a performance perspective. If you see this we need to look "
// "into structuring our pool sizes and allocations so the this doesn't "
// "happen frequently" << std::endl;
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, m_allocationSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[m_allocationSize];
#endif
m_chunks.push_back(Chunk(m_allocationSize, storage));
Chunk &newChunk = m_chunks.back();
newChunk.m_offset = size;
return newChunk.m_chunkData;
}
}
/*
* Get the offset into the current chunk. Then increment the
* offset counter by the amount being allocated.
*/
void *retval = currentChunk->m_chunkData + currentChunk->m_offset;
currentChunk->m_offset += size;
//Ensure 8 byte alignment of future allocations
currentChunk->m_offset += (8 - (currentChunk->m_offset % 8));
if (currentChunk->m_offset > currentChunk->m_size) {
currentChunk->m_offset = currentChunk->m_size;
}
return retval;
}
/*
* Allocate a continous block of memory of the specified size conveniently initialized to 0s
*/
inline void* allocateZeroes(std::size_t size) { return ::memset(allocate(size), 0, size); }
inline void purge() {
/*
* Erase any oversize chunks that were allocated
*/
const std::size_t numOversizeChunks = m_oversizeChunks.size();
for (std::size_t ii = 0; ii < numOversizeChunks; ii++) {
#ifdef USE_MMAP
if (::munmap( m_oversizeChunks[ii].m_chunkData, m_oversizeChunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_oversizeChunks[ii].m_chunkData;
#endif
}
m_oversizeChunks.clear();
/*
* Set the current chunk to the first in the list
*/
m_currentChunkIndex = 0;
std::size_t numChunks = m_chunks.size();
/*
* If more then maxChunkCount chunks are allocated erase all extra chunks
*/
if (numChunks > m_maxChunkCount) {
for (std::size_t ii = m_maxChunkCount; ii < numChunks; ii++) {
#ifdef USE_MMAP
if (::munmap( m_chunks[ii].m_chunkData, m_chunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete []m_chunks[ii].m_chunkData;
#endif
}
m_chunks.resize(m_maxChunkCount);
}
numChunks = m_chunks.size();
for (std::size_t ii = 0; ii < numChunks; ii++) {
m_chunks[ii].m_offset = 0;
}
}
int64_t getAllocatedMemory()
{
int64_t total = 0;
total += m_chunks.size() * m_allocationSize;
for (int i = 0; i < m_oversizeChunks.size(); i++)
{
total += m_oversizeChunks[i].getSize();
}
return total;
}
private:
const uint64_t m_allocationSize;
std::size_t m_maxChunkCount;
std::size_t m_currentChunkIndex;
std::vector<Chunk> m_chunks;
/*
* Oversize chunks that will be freed and not reused.
*/
std::vector<Chunk> m_oversizeChunks;
// No implicit copies
Pool(const Pool&);
Pool& operator=(const Pool&);
};
#else
/**
* A debug version of the memory pool that does each allocation on the heap keeps a list for when purge is called
*/
class Pool {
public:
Pool()
{
}
Pool(uint64_t allocationSize, uint64_t maxChunkCount) :
m_memTotal(0)
{
}
~Pool() {
purge();
}
/*
* Allocate a continous block of memory of the specified size.
*/
inline void* allocate(std::size_t size) {
char *retval = new char[size];
m_allocations.push_back(retval);
m_memTotal += size;
return retval;
}
/*
* Allocate a continous block of memory of the specified size conveniently initialized to 0s
*/
inline void* allocateZeroes(std::size_t size) { return ::memset(allocate(size), 0, size); }
inline void purge() {
for (std::size_t ii = 0; ii < m_allocations.size(); ii++) {
delete [] m_allocations[ii];
}
m_allocations.clear();
m_memTotal = 0;
}
int64_t getAllocatedMemory()
{
return m_memTotal;
}
private:
std::vector<char*> m_allocations;
int64_t m_memTotal;
// No implicit copies
Pool(const Pool&);
Pool& operator=(const Pool&);
};
#endif
}
#endif /* POOL_HPP_ */
<commit_msg>move the constants to VoltDB scope for memcheck build<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2014 VoltDB Inc.
*
* This program 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, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef POOL_HPP_
#define POOL_HPP_
#include <vector>
#include <iostream>
#include <stdint.h>
#include <sys/mman.h>
#include <errno.h>
#include <climits>
#include <string.h>
#include "common/FatalException.hpp"
namespace voltdb {
static const size_t TEMP_POOL_CHUNK_SIZE = 262144;
#ifndef MEMCHECK
/**
* Description of a chunk of memory allocated on the heap
*/
class Chunk {
public:
Chunk()
: m_offset(0), m_size(0), m_chunkData(NULL)
{
}
inline Chunk(uint64_t size, void *chunkData)
: m_offset(0), m_size(size), m_chunkData(static_cast<char*>(chunkData))
{
}
int64_t getSize() const
{
return static_cast<int64_t>(m_size);
}
uint64_t m_offset;
uint64_t m_size;
char *m_chunkData;
};
/*
* Find next higher power of two
* From http://en.wikipedia.org/wiki/Power_of_two
*/
template <class T>
inline T nexthigher(T k) {
if (k == 0)
return 1;
k--;
for (int i=1; i<sizeof(T)*CHAR_BIT; i<<=1)
k = k | k >> i;
return k+1;
}
/**
* A memory pool that provides fast allocation and deallocation. The
* only way to release memory is to free all memory in the pool by
* calling purge.
*/
class Pool {
public:
Pool() :
m_allocationSize(TEMP_POOL_CHUNK_SIZE), m_maxChunkCount(0), m_currentChunkIndex(0)
{
}
Pool(uint64_t allocationSize, uint64_t maxChunkCount) :
#ifdef USE_MMAP
m_allocationSize(nexthigher(allocationSize)),
#else
m_allocationSize(allocationSize),
#endif
m_maxChunkCount(static_cast<std::size_t>(maxChunkCount)),
m_currentChunkIndex(0)
{
}
~Pool() {
for (std::size_t ii = 0; ii < m_chunks.size(); ii++) {
#ifdef USE_MMAP
if (::munmap( m_chunks[ii].m_chunkData, m_chunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_chunks[ii].m_chunkData;
#endif
}
for (std::size_t ii = 0; ii < m_oversizeChunks.size(); ii++) {
#ifdef USE_MMAP
if (::munmap( m_oversizeChunks[ii].m_chunkData, m_oversizeChunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_oversizeChunks[ii].m_chunkData;
#endif
}
}
/*
* Allocate a continous block of memory of the specified size.
*/
inline void* allocate(std::size_t size) {
if (m_chunks.empty()) {
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, m_allocationSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[m_allocationSize];
#endif
m_chunks.push_back(Chunk(m_allocationSize, storage));
}
/*
* See if there is space in the current chunk
*/
Chunk *currentChunk = &m_chunks[m_currentChunkIndex];
if (size > currentChunk->m_size - currentChunk->m_offset) {
/*
* Not enough space. Check if it is greater then our allocation size.
*/
if (size > m_allocationSize) {
/*
* Allocate an oversize chunk that will not be reused.
*/
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, nexthigher(size), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[size];
#endif
m_oversizeChunks.push_back(Chunk(nexthigher(size), storage));
Chunk &newChunk = m_oversizeChunks.back();
newChunk.m_offset = size;
return newChunk.m_chunkData;
}
/*
* Check if there is an already allocated chunk we can use.
*/
m_currentChunkIndex++;
if (m_currentChunkIndex < m_chunks.size()) {
currentChunk = &m_chunks[m_currentChunkIndex];
currentChunk->m_offset = size;
return currentChunk->m_chunkData;
} else {
/*
* Need to allocate a new chunk
*/
// std::cout << "Pool had to allocate a new chunk. Not a good thing "
// "from a performance perspective. If you see this we need to look "
// "into structuring our pool sizes and allocations so the this doesn't "
// "happen frequently" << std::endl;
#ifdef USE_MMAP
char *storage =
static_cast<char*>(::mmap( 0, m_allocationSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ));
if (storage == MAP_FAILED) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed mmap");
}
#else
char *storage = new char[m_allocationSize];
#endif
m_chunks.push_back(Chunk(m_allocationSize, storage));
Chunk &newChunk = m_chunks.back();
newChunk.m_offset = size;
return newChunk.m_chunkData;
}
}
/*
* Get the offset into the current chunk. Then increment the
* offset counter by the amount being allocated.
*/
void *retval = currentChunk->m_chunkData + currentChunk->m_offset;
currentChunk->m_offset += size;
//Ensure 8 byte alignment of future allocations
currentChunk->m_offset += (8 - (currentChunk->m_offset % 8));
if (currentChunk->m_offset > currentChunk->m_size) {
currentChunk->m_offset = currentChunk->m_size;
}
return retval;
}
/*
* Allocate a continous block of memory of the specified size conveniently initialized to 0s
*/
inline void* allocateZeroes(std::size_t size) { return ::memset(allocate(size), 0, size); }
inline void purge() {
/*
* Erase any oversize chunks that were allocated
*/
const std::size_t numOversizeChunks = m_oversizeChunks.size();
for (std::size_t ii = 0; ii < numOversizeChunks; ii++) {
#ifdef USE_MMAP
if (::munmap( m_oversizeChunks[ii].m_chunkData, m_oversizeChunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete [] m_oversizeChunks[ii].m_chunkData;
#endif
}
m_oversizeChunks.clear();
/*
* Set the current chunk to the first in the list
*/
m_currentChunkIndex = 0;
std::size_t numChunks = m_chunks.size();
/*
* If more then maxChunkCount chunks are allocated erase all extra chunks
*/
if (numChunks > m_maxChunkCount) {
for (std::size_t ii = m_maxChunkCount; ii < numChunks; ii++) {
#ifdef USE_MMAP
if (::munmap( m_chunks[ii].m_chunkData, m_chunks[ii].m_size) != 0) {
std::cout << strerror( errno ) << std::endl;
throwFatalException("Failed munmap");
}
#else
delete []m_chunks[ii].m_chunkData;
#endif
}
m_chunks.resize(m_maxChunkCount);
}
numChunks = m_chunks.size();
for (std::size_t ii = 0; ii < numChunks; ii++) {
m_chunks[ii].m_offset = 0;
}
}
int64_t getAllocatedMemory()
{
int64_t total = 0;
total += m_chunks.size() * m_allocationSize;
for (int i = 0; i < m_oversizeChunks.size(); i++)
{
total += m_oversizeChunks[i].getSize();
}
return total;
}
private:
const uint64_t m_allocationSize;
std::size_t m_maxChunkCount;
std::size_t m_currentChunkIndex;
std::vector<Chunk> m_chunks;
/*
* Oversize chunks that will be freed and not reused.
*/
std::vector<Chunk> m_oversizeChunks;
// No implicit copies
Pool(const Pool&);
Pool& operator=(const Pool&);
};
#else
/**
* A debug version of the memory pool that does each allocation on the heap keeps a list for when purge is called
*/
class Pool {
public:
Pool()
{
}
Pool(uint64_t allocationSize, uint64_t maxChunkCount) :
m_memTotal(0)
{
}
~Pool() {
purge();
}
/*
* Allocate a continous block of memory of the specified size.
*/
inline void* allocate(std::size_t size) {
char *retval = new char[size];
m_allocations.push_back(retval);
m_memTotal += size;
return retval;
}
/*
* Allocate a continous block of memory of the specified size conveniently initialized to 0s
*/
inline void* allocateZeroes(std::size_t size) { return ::memset(allocate(size), 0, size); }
inline void purge() {
for (std::size_t ii = 0; ii < m_allocations.size(); ii++) {
delete [] m_allocations[ii];
}
m_allocations.clear();
m_memTotal = 0;
}
int64_t getAllocatedMemory()
{
return m_memTotal;
}
private:
std::vector<char*> m_allocations;
int64_t m_memTotal;
// No implicit copies
Pool(const Pool&);
Pool& operator=(const Pool&);
};
#endif
}
#endif /* POOL_HPP_ */
<|endoftext|> |
<commit_before>int main() {
}
<commit_msg>argc, argV<commit_after>int main(int argc, char **argv) {
return 0;
}
<|endoftext|> |
<commit_before>#include "shared.h"
#include "job.h"
#include "image.h"
ImagePair Job::get_next_pair() {
std::unique_lock<std::mutex> ul{mutex};
while (index_major != images.size() && images[index_major] == nullptr) {
if (index_next_to_create < images.size()) {
// create image
auto i = index_next_to_create++;
ul.unlock();
auto image = std::make_shared<Image>(paths[i]);
ul.lock();
images[i] = image;
} else {
// no more images to create but allow other threads to finish creating images
ul.unlock();
ul.lock();
}
}
if (index_major == images.size())
return {nullptr, nullptr};
auto index_minor_old = index_minor;
auto index_major_old = index_major;
if (index_minor == index_major) {
index_major++;
index_minor = 0;
} else {
index_minor++;
}
return {images[index_minor_old], images[index_major_old]};
}
float Job::get_progress() const {
std::lock_guard<std::mutex> lg{mutex};
return static_cast<float>(progress_current()) / progress_total();
}
bool Job::is_completed() const {
std::lock_guard<std::mutex> lg{mutex};
return index_major == images.size();
}
std::size_t Job::progress_current() const {
return index_major * (1 + index_major) / 2 + index_minor;
}
std::size_t Job::progress_total() const {
return paths.size() * (1 + paths.size()) / 2;
}
<commit_msg>Style<commit_after>#include "shared.h"
#include "job.h"
#include "image.h"
ImagePair Job::get_next_pair() {
std::unique_lock<std::mutex> ul{mutex};
while (index_major != images.size() && images[index_major] == nullptr) {
if (index_next_to_create < images.size()) {
// create image
auto i = index_next_to_create++;
ul.unlock();
auto image = std::make_shared<Image>(paths[i]);
ul.lock();
images[i] = image;
} else {
// no more images to create but allow other threads to finish creating images
ul.unlock();
ul.lock();
}
}
if (index_major == images.size())
return {nullptr, nullptr};
auto result = ImagePair{images[index_minor], images[index_major]};
if (index_minor == index_major) {
index_major++;
index_minor = 0;
} else {
index_minor++;
}
return result;
}
float Job::get_progress() const {
std::lock_guard<std::mutex> lg{mutex};
return static_cast<float>(progress_current()) / progress_total();
}
bool Job::is_completed() const {
std::lock_guard<std::mutex> lg{mutex};
return index_major == images.size();
}
std::size_t Job::progress_current() const {
return index_major * (1 + index_major) / 2 + index_minor;
}
std::size_t Job::progress_total() const {
return paths.size() * (1 + paths.size()) / 2;
}
<|endoftext|> |
<commit_before>/* 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 "contents.hh"
#include "show_message.hh"
namespace vick {
namespace join {
struct join_c : public change {
const move_t y, x;
join_c(const contents& contents)
: y(contents.y)
, x(contents.cont[y].size()) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont.insert(contents.cont.begin() + y + 1,
contents.cont[y].substr(x));
contents.cont[y] = contents.cont[y].substr(0, x);
}
virtual void redo(contents& contents) override {
contents.cont[y] += contents.cont[y + 1];
contents.cont.erase(contents.cont.begin() + y + 1);
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<join_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
join_two_lines(contents& contents, boost::optional<int>) {
if (contents.y >= contents.cont.size() - 1) {
show_message("Can't join lines past end");
return boost::none;
}
std::shared_ptr<change> join = std::make_shared<join_c>(contents);
join->redo(contents);
return join;
}
}
}
<commit_msg>Make `change::is_overriding()` `const noexcept`<commit_after>/* 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 "contents.hh"
#include "show_message.hh"
namespace vick {
namespace join {
struct join_c : public change {
const move_t y, x;
join_c(const contents& contents)
: y(contents.y)
, x(contents.cont[y].size()) {}
virtual bool is_overriding() const noexcept override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont.insert(contents.cont.begin() + y + 1,
contents.cont[y].substr(x));
contents.cont[y] = contents.cont[y].substr(0, x);
}
virtual void redo(contents& contents) override {
contents.cont[y] += contents.cont[y + 1];
contents.cont.erase(contents.cont.begin() + y + 1);
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<join_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
join_two_lines(contents& contents, boost::optional<int>) {
if (contents.y >= contents.cont.size() - 1) {
show_message("Can't join lines past end");
return boost::none;
}
std::shared_ptr<change> join = std::make_shared<join_c>(contents);
join->redo(contents);
return join;
}
}
}
<|endoftext|> |
<commit_before>// win32find.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
void _check_invariant_conditions(int argc, char *argv[])
{
if (argc == 1 || argc > 3)
{
fprintf(stderr, "usage: %s [starting point...] [expression]\n", argv[0]);
exit(-1); // argument length
}
if (strlen(argv[1]) > MAX_PATH)
{
fprintf(stderr, "argument length: path cannot exceed %d characters\n", MAX_PATH);
exit(-1);
}
if (argc > 3 && strlen(argv[2]) > FILENAME_MAX)
{
fprintf(stderr, "argument length: expression cannot exceed %d characters\n", FILENAME_MAX);
exit(-1);
}
}
void _search(wchar_t base_path[], wchar_t filename[])
{
LPWIN32_FIND_DATA hFile = (LPWIN32_FIND_DATA) GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
HANDLE findResult = NULL;
wchar_t combined_filename[MAX_PATH] = TEXT("");
StringCchCat(combined_filename, MAX_PATH - FILENAME_MAX - 1, base_path);
StringCchCat(combined_filename, 1, TEXT("/"));
StringCchCat(combined_filename, FILENAME_MAX, filename);
findResult = FindFirstFile((LPCWSTR)combined_filename, hFile);
if (findResult == INVALID_HANDLE_VALUE)
{
DWORD dw_error_code = 0;
dw_error_code = GetLastError();
if (dw_error_code == ERROR_FILE_NOT_FOUND)
{
_tprintf(TEXT("No results to display.\n"));
}
else
{
_tprintf(TEXT("FindFirstFile failed %d\n"), dw_error_code);
}
}
do
{
_tprintf(TEXT("%s\n"), hFile->cFileName);
} while (FindNextFile(findResult, hFile));
FindClose(findResult);
}
int main(int argc, char *argv[])
{
_check_invariant_conditions(argc, argv);
wchar_t base_path[MAX_PATH] = L"";
wchar_t file_name[FILENAME_MAX] = L"";
if (argc == 2)
{
wchar_t fn[FILENAME_MAX];
mbstowcs_s(NULL, fn, argv[1], FILENAME_MAX);
StringCchCat(base_path, 4, L".\\");
StringCchCat(file_name, FILENAME_MAX * sizeof(wchar_t), fn);
}
else if (argc == 3)
{
wchar_t fn[FILENAME_MAX * sizeof(wchar_t)];
mbstowcs_s(NULL, fn, argv[2], FILENAME_MAX);
wchar_t bp[MAX_PATH * sizeof(wchar_t)];
mbstowcs_s(NULL, bp, argv[1], FILENAME_MAX);
StringCchCat(base_path, MAX_PATH * sizeof(wchar_t), bp);
StringCchCat(file_name, FILENAME_MAX * sizeof(wchar_t), fn);
}
_search(base_path, file_name);
return 0;
}<commit_msg>making find recursive<commit_after>// win32find.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
void _check_invariant_conditions(int argc, char *argv[])
{
if (argc == 1 || argc > 3)
{
fprintf(stderr, "usage: %s [starting point...] [expression]\n", argv[0]);
exit(-1); // argument length
}
if (strlen(argv[1]) > MAX_PATH)
{
fprintf(stderr, "argument length: path cannot exceed %d characters\n", MAX_PATH);
exit(-1);
}
if (argc > 3 && strlen(argv[2]) > FILENAME_MAX)
{
fprintf(stderr, "argument length: expression cannot exceed %d characters\n", FILENAME_MAX);
exit(-1);
}
}
void _search(wchar_t base_path[], wchar_t filename[])
{
LPWIN32_FIND_DATA hFile = (LPWIN32_FIND_DATA)GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
LPWIN32_FIND_DATA hDirectory = (LPWIN32_FIND_DATA) GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
HANDLE findFileResult = NULL;
HANDLE findDirectoryResult = NULL;
wchar_t wildcard[MAX_PATH] = L"";
size_t bp_sz = wcsnlen_s(base_path, MAX_PATH);
StringCchCat(wildcard, bp_sz + 1, base_path);
StringCchCat(wildcard, bp_sz + 2, L"*");
findDirectoryResult = FindFirstFile((LPCWSTR)wildcard, hDirectory);
if (findDirectoryResult == INVALID_HANDLE_VALUE)
{
DWORD dw_error_code = 0;
dw_error_code = GetLastError();
if (dw_error_code != ERROR_FILE_NOT_FOUND)
{
_tprintf(TEXT("FindFirstFile failed %d\n"), dw_error_code);
}
}
do
{
if (hDirectory->dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
&& wcscmp(hDirectory->cFileName, L".") != 0
&& wcscmp(hDirectory->cFileName, L"..") != 0)
{
wchar_t new_bp[MAX_PATH] = L"";
size_t fn_sz = wcsnlen_s(hDirectory->cFileName, FILENAME_MAX);
StringCchCat(new_bp, bp_sz + 1, base_path);
StringCchCat(new_bp, bp_sz + fn_sz + 1, hDirectory->cFileName);
StringCchCat(new_bp, bp_sz + fn_sz + 2, L"\\");
_search(new_bp, filename);
}
} while (FindNextFile(findDirectoryResult, hDirectory));
wchar_t combined_filename[MAX_PATH] = TEXT("");
StringCchCat(combined_filename, bp_sz + 1, base_path);
StringCchCat(combined_filename, bp_sz + 2, TEXT("\\"));
StringCchCat(combined_filename, bp_sz + wcsnlen_s(filename, FILENAME_MAX) + 2, filename);
findFileResult = FindFirstFile((LPCWSTR)combined_filename, hFile);
if (findFileResult == INVALID_HANDLE_VALUE)
{
DWORD dw_error_code = 0;
dw_error_code = GetLastError();
if (dw_error_code != ERROR_FILE_NOT_FOUND)
{
_tprintf(TEXT("FindFirstFile failed %d\n"), dw_error_code);
return;
}
return;
}
do
{
wchar_t fpn[MAX_PATH] = L"";
StringCchCat(fpn, bp_sz + 1, base_path);
StringCchCat(fpn, bp_sz + 2, L"\\");
StringCchCat(fpn, bp_sz + wcsnlen_s(hFile->cFileName, FILENAME_MAX) + 2, hFile->cFileName);
_tprintf(TEXT("%s\n"), fpn);
} while (FindNextFile(findFileResult, hFile));
FindClose(findFileResult);
}
int main(int argc, char *argv[])
{
_check_invariant_conditions(argc, argv);
wchar_t base_path[MAX_PATH] = L"";
wchar_t file_name[FILENAME_MAX] = L"";
if (argc == 2)
{
wchar_t fn[FILENAME_MAX];
mbstowcs_s(NULL, fn, argv[1], FILENAME_MAX);
StringCchCat(base_path, sizeof(wchar_t) * 3, L".\\");
StringCchCat(file_name, FILENAME_MAX * sizeof(wchar_t), fn);
}
else if (argc == 3)
{
wchar_t fn[FILENAME_MAX * sizeof(wchar_t)];
mbstowcs_s(NULL, fn, argv[2], FILENAME_MAX);
wchar_t bp[MAX_PATH * sizeof(wchar_t)];
mbstowcs_s(NULL, bp, argv[1], FILENAME_MAX);
StringCchCat(base_path, MAX_PATH * sizeof(wchar_t), bp);
StringCchCat(file_name, FILENAME_MAX * sizeof(wchar_t), fn);
}
_search(base_path, file_name);
return 0;
}<|endoftext|> |
<commit_before>#ifndef SILICIUM_SINK_HPP
#define SILICIUM_SINK_HPP
#include <silicium/override.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/filesystem/path.hpp>
#include <ostream>
#include <array>
#include <memory>
namespace Si
{
template <class Element>
struct sink
{
virtual ~sink()
{
}
virtual boost::iterator_range<Element *> make_append_space(std::size_t size) = 0;
virtual void flush_append_space() = 0;
virtual void append(boost::iterator_range<Element const *> data) = 0;
};
template <class Element>
struct flushable_sink : sink<Element>
{
virtual void flush() = 0;
};
template <class Element>
void commit(sink<Element> &destination, std::size_t count)
{
destination.make_append_space(count);
destination.flush_append_space();
}
template <class Element, class Buffer = std::array<Element, ((1U << 13U) / sizeof(Element))>>
struct buffering_sink : flushable_sink<Element>
{
explicit buffering_sink(sink<Element> &destination, Buffer buffer = Buffer())
: m_destination(destination)
, m_fallback_buffer(std::move(buffer))
, m_buffer_used(0)
{
}
boost::iterator_range<Element *> make_append_space(std::size_t size) SILICIUM_OVERRIDE
{
auto first_try = m_destination.make_append_space(size);
if (!first_try.empty())
{
auto const copied = (std::min)(static_cast<std::ptrdiff_t>(m_buffer_used), first_try.size());
std::copy(m_fallback_buffer.begin(), m_fallback_buffer.begin() + copied, first_try.begin());
m_buffer_used = 0;
return first_try;
}
m_buffer_used = (std::min)(size, m_fallback_buffer.size());
return boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used);
}
void flush_append_space() SILICIUM_OVERRIDE
{
if (m_buffer_used)
{
flush();
}
else
{
m_destination.flush_append_space();
}
}
void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE
{
if (data.size() <= (m_fallback_buffer.size() - m_buffer_used))
{
boost::range::copy(data, m_fallback_buffer.begin() + m_buffer_used);
m_buffer_used += data.size();
return;
}
flush();
m_destination.append(data);
}
void flush() SILICIUM_OVERRIDE
{
m_destination.append(boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used));
m_buffer_used = 0;
}
private:
sink<Element> &m_destination;
Buffer m_fallback_buffer;
std::size_t m_buffer_used;
};
template <class Element, class OutputIterator>
struct iterator_sink : sink<Element>
{
explicit iterator_sink(OutputIterator out)
: m_out(std::move(out))
{
}
virtual boost::iterator_range<Element *> make_append_space(std::size_t) SILICIUM_OVERRIDE
{
return {};
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
}
virtual void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE
{
boost::range::copy(data, m_out);
}
private:
OutputIterator m_out;
};
template <class Element, class OutputIterator>
auto make_iterator_sink(OutputIterator out)
-> iterator_sink<Element, typename std::decay<OutputIterator>::type>
{
return iterator_sink<Element, typename std::decay<OutputIterator>::type>(std::move(out));
}
template <class Container>
auto make_container_sink(Container &destination)
-> iterator_sink<typename Container::value_type, std::back_insert_iterator<Container>>
{
return make_iterator_sink<typename Container::value_type>(std::back_inserter(destination));
}
struct ostream_sink : flushable_sink<char>
{
//unique_ptr to make ostreams movable
explicit ostream_sink(std::unique_ptr<std::ostream> file)
: m_file(std::move(file))
{
m_file->exceptions(std::ios::failbit | std::ios::badbit);
}
virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE
{
return {};
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
}
virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
{
m_file->write(data.begin(), data.size());
}
virtual void flush() SILICIUM_OVERRIDE
{
m_file->flush();
}
private:
std::unique_ptr<std::ostream> m_file;
};
std::unique_ptr<flushable_sink<char>> make_file_sink(boost::filesystem::path const &name);
template <class Element>
struct auto_flush_sink : sink<Element>
{
auto_flush_sink()
: m_next(nullptr)
{
}
explicit auto_flush_sink(flushable_sink<Element> &next)
: m_next(&next)
{
}
virtual boost::iterator_range<char *> make_append_space(std::size_t size) SILICIUM_OVERRIDE
{
assert(m_next);
return m_next->make_append_space(size);
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
assert(m_next);
m_next->flush_append_space();
m_next->flush();
}
virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
{
assert(m_next);
m_next->append(data);
m_next->flush();
}
private:
flushable_sink<Element> *m_next;
};
template <class Element>
auto_flush_sink<Element> make_auto_flush_sink(flushable_sink<Element> &next)
{
return auto_flush_sink<Element>(next);
}
template <class Element>
void append(Si::sink<Element> &out, std::basic_string<Element> const &str)
{
out.append(boost::make_iterator_range(str.data(), str.data() + str.size()));
}
template <class Element>
void append(Si::sink<Element> &out, Element const *c_str)
{
out.append(boost::make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
}
template <class Element>
void append(Si::sink<Element> &out, Element const &single)
{
out.append(boost::make_iterator_range(&single, &single + 1));
}
}
#endif
<commit_msg>add sink that append to an std::ostream &<commit_after>#ifndef SILICIUM_SINK_HPP
#define SILICIUM_SINK_HPP
#include <silicium/override.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/filesystem/path.hpp>
#include <ostream>
#include <array>
#include <memory>
namespace Si
{
template <class Element>
struct sink
{
virtual ~sink()
{
}
virtual boost::iterator_range<Element *> make_append_space(std::size_t size) = 0;
virtual void flush_append_space() = 0;
virtual void append(boost::iterator_range<Element const *> data) = 0;
};
template <class Element>
struct flushable_sink : sink<Element>
{
virtual void flush() = 0;
};
template <class Element>
void commit(sink<Element> &destination, std::size_t count)
{
destination.make_append_space(count);
destination.flush_append_space();
}
template <class Element, class Buffer = std::array<Element, ((1U << 13U) / sizeof(Element))>>
struct buffering_sink : flushable_sink<Element>
{
explicit buffering_sink(sink<Element> &destination, Buffer buffer = Buffer())
: m_destination(destination)
, m_fallback_buffer(std::move(buffer))
, m_buffer_used(0)
{
}
boost::iterator_range<Element *> make_append_space(std::size_t size) SILICIUM_OVERRIDE
{
auto first_try = m_destination.make_append_space(size);
if (!first_try.empty())
{
auto const copied = (std::min)(static_cast<std::ptrdiff_t>(m_buffer_used), first_try.size());
std::copy(m_fallback_buffer.begin(), m_fallback_buffer.begin() + copied, first_try.begin());
m_buffer_used = 0;
return first_try;
}
m_buffer_used = (std::min)(size, m_fallback_buffer.size());
return boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used);
}
void flush_append_space() SILICIUM_OVERRIDE
{
if (m_buffer_used)
{
flush();
}
else
{
m_destination.flush_append_space();
}
}
void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE
{
if (data.size() <= (m_fallback_buffer.size() - m_buffer_used))
{
boost::range::copy(data, m_fallback_buffer.begin() + m_buffer_used);
m_buffer_used += data.size();
return;
}
flush();
m_destination.append(data);
}
void flush() SILICIUM_OVERRIDE
{
m_destination.append(boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used));
m_buffer_used = 0;
}
private:
sink<Element> &m_destination;
Buffer m_fallback_buffer;
std::size_t m_buffer_used;
};
template <class Element, class OutputIterator>
struct iterator_sink : sink<Element>
{
explicit iterator_sink(OutputIterator out)
: m_out(std::move(out))
{
}
virtual boost::iterator_range<Element *> make_append_space(std::size_t) SILICIUM_OVERRIDE
{
return {};
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
}
virtual void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE
{
boost::range::copy(data, m_out);
}
private:
OutputIterator m_out;
};
template <class Element, class OutputIterator>
auto make_iterator_sink(OutputIterator out)
-> iterator_sink<Element, typename std::decay<OutputIterator>::type>
{
return iterator_sink<Element, typename std::decay<OutputIterator>::type>(std::move(out));
}
template <class Container>
auto make_container_sink(Container &destination)
-> iterator_sink<typename Container::value_type, std::back_insert_iterator<Container>>
{
return make_iterator_sink<typename Container::value_type>(std::back_inserter(destination));
}
struct ostream_ref_sink : flushable_sink<char>
{
explicit ostream_ref_sink(std::ostream &file)
: m_file(file)
{
}
virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE
{
return {};
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
}
virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
{
m_file.write(data.begin(), data.size());
}
virtual void flush() SILICIUM_OVERRIDE
{
m_file.flush();
}
private:
std::ostream &m_file;
};
struct ostream_sink : flushable_sink<char>
{
//unique_ptr to make ostreams movable
explicit ostream_sink(std::unique_ptr<std::ostream> file)
: m_file(std::move(file))
{
m_file->exceptions(std::ios::failbit | std::ios::badbit);
}
virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE
{
return {};
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
}
virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
{
m_file->write(data.begin(), data.size());
}
virtual void flush() SILICIUM_OVERRIDE
{
m_file->flush();
}
private:
std::unique_ptr<std::ostream> m_file;
};
std::unique_ptr<flushable_sink<char>> make_file_sink(boost::filesystem::path const &name);
template <class Element>
struct auto_flush_sink : sink<Element>
{
auto_flush_sink()
: m_next(nullptr)
{
}
explicit auto_flush_sink(flushable_sink<Element> &next)
: m_next(&next)
{
}
virtual boost::iterator_range<char *> make_append_space(std::size_t size) SILICIUM_OVERRIDE
{
assert(m_next);
return m_next->make_append_space(size);
}
virtual void flush_append_space() SILICIUM_OVERRIDE
{
assert(m_next);
m_next->flush_append_space();
m_next->flush();
}
virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
{
assert(m_next);
m_next->append(data);
m_next->flush();
}
private:
flushable_sink<Element> *m_next;
};
template <class Element>
auto_flush_sink<Element> make_auto_flush_sink(flushable_sink<Element> &next)
{
return auto_flush_sink<Element>(next);
}
template <class Element>
void append(Si::sink<Element> &out, std::basic_string<Element> const &str)
{
out.append(boost::make_iterator_range(str.data(), str.data() + str.size()));
}
template <class Element>
void append(Si::sink<Element> &out, Element const *c_str)
{
out.append(boost::make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
}
template <class Element>
void append(Si::sink<Element> &out, Element const &single)
{
out.append(boost::make_iterator_range(&single, &single + 1));
}
}
#endif
<|endoftext|> |
<commit_before>/** @file ScenesManager.cpp
@author Philip Abbet
Implementation of the class 'Athena::Entities::ScenesManager'
*/
#include <Athena-Entities/ScenesManager.h>
#include <Athena-Entities/Scene.h>
#include <Athena-Core/Log/LogManager.h>
using namespace Athena::Entities;
using namespace Athena::Utils;
using namespace Athena::Log;
using namespace std;
/************************************** CONSTANTS ***************************************/
/// Context used for logging
static const char* __CONTEXT__ = "Scenes manager";
/********************************** STATIC ATTRIBUTES ***********************************/
/// The instance of the singleton
template<> ScenesManager* Singleton<ScenesManager>::ms_Singleton = 0;
/****************************** CONSTRUCTION / DESTRUCTION ******************************/
ScenesManager::ScenesManager()
: m_pCurrentScene(0)
{
ATHENA_LOG_EVENT("Creation");
}
//-----------------------------------------------------------------------
ScenesManager::~ScenesManager()
{
ATHENA_LOG_EVENT("Destruction");
destroyAll();
}
//-----------------------------------------------------------------------
ScenesManager& ScenesManager::getSingleton()
{
assert(ms_Singleton);
return *ms_Singleton;
}
//-----------------------------------------------------------------------
ScenesManager* ScenesManager::getSingletonPtr()
{
return ms_Singleton;
}
/******************************** MANAGEMENT OF THE SCENES ******************************/
Scene* ScenesManager::create(const std::string& strName)
{
// Assertions
assert(!strName.empty() && "Invalid entity name");
return new Scene(strName);
}
//-----------------------------------------------------------------------
Scene* ScenesManager::getScene(const std::string& strName)
{
assert(!strName.empty() && "The name is empty");
// Declarations
tScenesNativeIterator iter, iterEnd;
// Search the entity
for (iter = m_scenes.begin(), iterEnd = m_scenes.end(); iter != iterEnd; ++iter)
{
if ((*iter)->getName() == strName)
{
// Return it
return (*iter);
}
}
// Not found
return 0;
}
//-----------------------------------------------------------------------
void ScenesManager::destroy(const std::string& strName)
{
// Assertions
assert(!strName.empty() && "The name is empty");
// Declarations
Scene* pScene;
// Search the entity
pScene = getScene(strName);
if (pScene)
{
destroy(pScene);
}
else
{
ATHENA_LOG_ERROR("Failed to destroy the scene '" + strName + "'");
assert(false); // A scene not registered with this manager is not possible
}
}
//-----------------------------------------------------------------------
void ScenesManager::destroy(Scene* pScene)
{
// Assertions
assert(pScene && "Invalid scene");
delete pScene;
}
//-----------------------------------------------------------------------
void ScenesManager::destroyAll()
{
while (!m_scenes.empty())
destroy(m_scenes.front());
}
//-----------------------------------------------------------------------
void ScenesManager::_registerScene(Scene* pScene)
{
// Assertions
assert(pScene && "Invalid scene");
// Add the scene to the list
m_scenes.push_back(pScene);
}
//-----------------------------------------------------------------------
void ScenesManager::_destroyScene(Scene* pScene)
{
// CScenesManager
assert(pScene && "Invalid scene");
// Declarations
tScenesNativeIterator iter, iterEnd;
// Search the entity
for (iter = m_scenes.begin(), iterEnd = m_scenes.end(); iter != iterEnd; ++iter)
{
if (*iter == pScene)
{
// Remove it from the list
m_scenes.erase(iter);
break;
}
}
if (m_pCurrentScene == pScene)
m_pCurrentScene = 0;
}
//-----------------------------------------------------------------------
void ScenesManager::_onSceneShown(Scene* pScene)
{
// Assertions
assert(pScene);
assert(!pScene->isShown());
if (m_pCurrentScene)
m_pCurrentScene->hide();
m_pCurrentScene = pScene;
}
//-----------------------------------------------------------------------
void ScenesManager::_onSceneHidden(Scene* pScene)
{
// Assertions
assert(pScene);
assert(pScene->isShown());
m_pCurrentScene = 0;
}
<commit_msg>Fix a typo<commit_after>/** @file ScenesManager.cpp
@author Philip Abbet
Implementation of the class 'Athena::Entities::ScenesManager'
*/
#include <Athena-Entities/ScenesManager.h>
#include <Athena-Entities/Scene.h>
#include <Athena-Core/Log/LogManager.h>
using namespace Athena::Entities;
using namespace Athena::Utils;
using namespace Athena::Log;
using namespace std;
/************************************** CONSTANTS ***************************************/
/// Context used for logging
static const char* __CONTEXT__ = "Scenes manager";
/********************************** STATIC ATTRIBUTES ***********************************/
/// The instance of the singleton
template<> ScenesManager* Singleton<ScenesManager>::ms_Singleton = 0;
/****************************** CONSTRUCTION / DESTRUCTION ******************************/
ScenesManager::ScenesManager()
: m_pCurrentScene(0)
{
ATHENA_LOG_EVENT("Creation");
}
//-----------------------------------------------------------------------
ScenesManager::~ScenesManager()
{
ATHENA_LOG_EVENT("Destruction");
destroyAll();
}
//-----------------------------------------------------------------------
ScenesManager& ScenesManager::getSingleton()
{
assert(ms_Singleton);
return *ms_Singleton;
}
//-----------------------------------------------------------------------
ScenesManager* ScenesManager::getSingletonPtr()
{
return ms_Singleton;
}
/******************************** MANAGEMENT OF THE SCENES ******************************/
Scene* ScenesManager::create(const std::string& strName)
{
// Assertions
assert(!strName.empty() && "Invalid entity name");
return new Scene(strName);
}
//-----------------------------------------------------------------------
Scene* ScenesManager::getScene(const std::string& strName)
{
assert(!strName.empty() && "The name is empty");
// Declarations
tScenesNativeIterator iter, iterEnd;
// Search the entity
for (iter = m_scenes.begin(), iterEnd = m_scenes.end(); iter != iterEnd; ++iter)
{
if ((*iter)->getName() == strName)
{
// Return it
return (*iter);
}
}
// Not found
return 0;
}
//-----------------------------------------------------------------------
void ScenesManager::destroy(const std::string& strName)
{
// Assertions
assert(!strName.empty() && "The name is empty");
// Declarations
Scene* pScene;
// Search the entity
pScene = getScene(strName);
if (pScene)
{
destroy(pScene);
}
else
{
ATHENA_LOG_ERROR("Failed to destroy the scene '" + strName + "'");
assert(false); // A scene not registered with this manager is not possible
}
}
//-----------------------------------------------------------------------
void ScenesManager::destroy(Scene* pScene)
{
// Assertions
assert(pScene && "Invalid scene");
delete pScene;
}
//-----------------------------------------------------------------------
void ScenesManager::destroyAll()
{
while (!m_scenes.empty())
destroy(m_scenes.front());
}
//-----------------------------------------------------------------------
void ScenesManager::_registerScene(Scene* pScene)
{
// Assertions
assert(pScene && "Invalid scene");
// Add the scene to the list
m_scenes.push_back(pScene);
}
//-----------------------------------------------------------------------
void ScenesManager::_destroyScene(Scene* pScene)
{
// Assertions
assert(pScene && "Invalid scene");
// Declarations
tScenesNativeIterator iter, iterEnd;
// Search the scene
for (iter = m_scenes.begin(), iterEnd = m_scenes.end(); iter != iterEnd; ++iter)
{
if (*iter == pScene)
{
// Remove it from the list
m_scenes.erase(iter);
break;
}
}
if (m_pCurrentScene == pScene)
m_pCurrentScene = 0;
}
//-----------------------------------------------------------------------
void ScenesManager::_onSceneShown(Scene* pScene)
{
// Assertions
assert(pScene);
assert(!pScene->isShown());
if (m_pCurrentScene)
m_pCurrentScene->hide();
m_pCurrentScene = pScene;
}
//-----------------------------------------------------------------------
void ScenesManager::_onSceneHidden(Scene* pScene)
{
// Assertions
assert(pScene);
assert(pScene->isShown());
m_pCurrentScene = 0;
}
<|endoftext|> |
<commit_before>#include "common.h"
#include "World.h"
#include "PositionComponent.h"
#include "PlayerCameraComponent.h"
void World::Init() {
}
void World::Update(DeltaTicks &, std::vector<Object *> &) {
chunks.With([] (ChunksType &chunks) {
//INFO(chunks.size());
});
if(cameraObj == nullptr) { return; }
auto camera = cameraObj->Get<PlayerCameraComponent>();
if(camera != nullptr) {
auto pos = cameraObj->Get<PositionComponent>();
if(pos != nullptr) {
const unsigned char distance = 6;
auto chunkSizeF = glm::fvec3(chunkSize);
auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF);
auto jobM = engine->systems.Get<JobManager>();
/* clean up chunks outside distance */
chunks.With([this, distance, &keyBase] (ChunksType &chunks) {
for(auto it = chunks.begin(); it != chunks.end();) {
auto &keyTuple = it->first;
auto obj = std::get<1>(it->second);
if(abs(std::get<0>(keyTuple) -keyBase.x) > distance ||
abs(std::get<1>(keyTuple) -keyBase.y) > distance ||
abs(std::get<2>(keyTuple) -keyBase.z) > distance) {
auto &status = std::get<0>(it->second);
switch(status) {
case ChunkStatus::Generating:
status = ChunkStatus::Dying;
break;
case ChunkStatus::Alive:
case ChunkStatus::Dead:
if(obj != nullptr) {
engine->RemoveObject(obj, false);
obj->Pool();
}
chunks.erase(it++);
continue;
}
}
++it;
}
});
for(int d = 0; d <= distance; ++d) {
for(int x = -d; x <= d; ++x) {
for(int y = -d; y <= d; ++y) {
for(int z = -d; z <= d; ++z) {
auto key = keyBase + glm::ivec3(x, y, z);
auto keyTuple = std::make_tuple(key.x, key.y, key.z);
if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
return chunks.find(keyTuple) == chunks.end();
})) {
chunks.With([&keyTuple] (ChunksType &chunks) {
chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, nullptr));
});
jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () {
auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
auto &status = std::get<0>(chunks.at(keyTuple));
if(status == ChunkStatus::Dying) {
status = ChunkStatus::Dead;
return true;
} else { return false; }
});
if(dead) { return; }
auto data = Generate(keyTuple);
auto chunkObj = Chunk::New(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data));
auto pos = chunkObj->Get<PositionComponent>();
auto chunkPos = glm::fvec3(key) * chunkSizeF;
pos->position = Point(chunkPos.x, chunkPos.y, chunkPos.z + chunkSize.z, 1);
jobM->Do([this, keyTuple, key, chunkSizeF, chunkObj] () {
engine->AddObject(chunkObj);
chunks.With([&keyTuple, chunkObj] (ChunksType &chunks) {
chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, chunkObj);
});
}, JobPriority::High, JobThread::Main);
}, JobPriority::Normal, JobThread::Worker);
}
}
}
}
}
}
}
}
void World::Destroy() {
}
void World::ObjectAdded(Object *obj) {
auto camera = obj->Get<PlayerCameraComponent>();
if(camera != nullptr) {
cameraObj = obj;
}
}
std::vector<bool> World::Generate(const ChunkKeyType &keyTuple) const {
/*const float start = -0.5, end = -0;
static double factor = 1.0f;
factor /= 1.0001f;
auto r = factor * (start - end) + end;*/
const float scale = 0.5f;
const float scaleX = scale, scaleY = scale * 2, scaleZ = scale;
std::vector<bool> blocks;
blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z);
float xIncr = 1.0f / chunkSize.x, yIncr = 1.0f / chunkSize.y, zIncr = 1.0f / chunkSize.z;
int i = 0;
for(float z = 0; z < 1; z += zIncr) {
for(float x = 0; x < 1; x += xIncr) {
for(float y = 0; y < 1; y += yIncr) {
double random = noise.eval(
( std::get<0>(keyTuple) + x) * scaleX,
( std::get<1>(keyTuple) + y) * scaleY,
(-std::get<2>(keyTuple) + z) * scaleZ
);
blocks.at(i++) = random > 0.45f;
}
}
}
return blocks;
}
<commit_msg>World: Tidy up; separate block generation from chunk generation<commit_after>#include "common.h"
#include "World.h"
#include "PositionComponent.h"
#include "PlayerCameraComponent.h"
void World::Init() {
}
void World::Update(DeltaTicks &, std::vector<Object *> &) {
if(cameraObj == nullptr) { return; }
auto camera = cameraObj->Get<PlayerCameraComponent>();
if(camera != nullptr) {
auto pos = cameraObj->Get<PositionComponent>();
if(pos != nullptr) {
const unsigned char distance = 5;
auto chunkSizeF = glm::fvec3(chunkSize);
auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF);
auto jobM = engine->systems.Get<JobManager>();
/* clean up chunks outside distance */
chunks.With([this, distance, &keyBase] (ChunksType &chunks) {
for(auto it = chunks.begin(); it != chunks.end();) {
auto &keyTuple = it->first;
auto obj = std::get<1>(it->second);
if(abs(std::get<0>(keyTuple) -keyBase.x) > distance ||
abs(std::get<1>(keyTuple) -keyBase.y) > distance ||
abs(std::get<2>(keyTuple) -keyBase.z) > distance) {
auto &status = std::get<0>(it->second);
switch(status) {
case ChunkStatus::Generating:
status = ChunkStatus::Dying;
break;
case ChunkStatus::Alive:
case ChunkStatus::Dead:
if(obj != nullptr) {
engine->RemoveObject(obj, false);
obj->Pool();
}
chunks.erase(it++);
continue;
}
}
++it;
}
});
for(int d = 0; d <= distance; ++d) {
for(int x = -d; x <= d; ++x) {
for(int y = -d; y <= d; ++y) {
for(int z = -d; z <= d; ++z) {
auto key = keyBase + glm::ivec3(x, y, z);
auto keyTuple = std::make_tuple(key.x, key.y, key.z);
if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
return chunks.find(keyTuple) == chunks.end();
})) {
chunks.With([&keyTuple] (ChunksType &chunks) {
chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, nullptr));
});
jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () {
auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
auto &status = std::get<0>(chunks.at(keyTuple));
if(status == ChunkStatus::Dying) {
status = ChunkStatus::Dead;
return true;
} else { return false; }
});
if(dead) { return; }
auto data = Generate(keyTuple);
auto chunkObj = Chunk::New(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data));
auto pos = chunkObj->Get<PositionComponent>();
auto chunkPos = glm::fvec3(key) * chunkSizeF;
pos->position = Point(chunkPos.x, chunkPos.y, chunkPos.z + chunkSize.z, 1);
jobM->Do([this, keyTuple, key, chunkSizeF, chunkObj] () {
engine->AddObject(chunkObj);
chunks.With([&keyTuple, chunkObj] (ChunksType &chunks) {
chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, chunkObj);
});
}, JobPriority::High, JobThread::Main);
}, JobPriority::Normal, JobThread::Worker);
}
}
}
}
}
}
}
}
void World::Destroy() {
}
void World::ObjectAdded(Object *obj) {
auto camera = obj->Get<PlayerCameraComponent>();
if(camera != nullptr) {
cameraObj = obj;
}
}
std::vector<bool> World::Generate(const ChunkKeyType &keyTuple) const {
const float scale = 1.0f;
const float scaleX = scale, scaleY = scale, scaleZ = scale;
std::vector<bool> blocks;
blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z);
float xIncr = 1.0f / chunkSize.x, yIncr = 1.0f / chunkSize.y, zIncr = 1.0f / chunkSize.z;
int i = 0;
for(float z = 0; z < 1; z += zIncr) {
for(float x = 0; x < 1; x += xIncr) {
for(float y = 0; y < 1; y += yIncr) {
blocks.at(i++) = GenerateBlock(
( std::get<0>(keyTuple) + x) * scaleX,
( std::get<1>(keyTuple) + y) * scaleY,
(-std::get<2>(keyTuple) + z) * scaleZ
);
}
}
}
return blocks;
}
bool World::GenerateBlock(const float x, const float y, const float z) const {
return noise.eval(x, y, z) > 0.45f;
}
<|endoftext|> |
<commit_before>#include "common.h"
#include "World.h"
#include "JobManager.h"
#include "PositionComponent.h"
#include "PlayerCameraComponent.h"
void World::Init() {
}
void World::Update(DeltaTicks &) {
auto pair = engine->objects.right.equal_range(&typeid(PlayerCameraComponent));
for(auto it = pair.first; it != pair.second; ++it) {
auto object = it->get_left();
auto camera = static_cast<PlayerCameraComponent *>(it->info.get());
auto pos = engine->GetComponent<PositionComponent>(object);
if(pos != nullptr) {
const unsigned char distance = 5;
auto chunkSizeF = glm::fvec3(chunkSize);
auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF);
auto jobM = engine->systems.Get<JobManager>();
/* clean up chunks outside distance */
chunks.With([this, distance, &keyBase] (ChunksType &chunks) {
for(auto it = chunks.begin(); it != chunks.end();) {
auto &keyTuple = it->first;
auto obj = std::get<1>(it->second);
if(abs(std::get<0>(keyTuple) -keyBase.x) > distance ||
abs(std::get<1>(keyTuple) -keyBase.y) > distance ||
abs(std::get<2>(keyTuple) -keyBase.z) > distance) {
auto &status = std::get<0>(it->second);
switch(status) {
case ChunkStatus::Generating:
status = ChunkStatus::Dying;
break;
case ChunkStatus::Alive:
case ChunkStatus::Dead:
engine->RemoveObject(obj);
chunks.erase(it++);
continue;
}
}
++it;
}
});
for(int d = 0; d <= distance; ++d) {
for(int x = -d; x <= d; ++x) {
for(int y = -d; y <= d; ++y) {
for(int z = -d; z <= d; ++z) {
auto key = keyBase + glm::ivec3(x, y, z);
auto keyTuple = std::make_tuple(key.x, key.y, key.z);
if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
return chunks.find(keyTuple) == chunks.end();
})) {
chunks.With([&keyTuple] (ChunksType &chunks) {
chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, 0));
});
jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () {
auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
auto &status = std::get<0>(chunks.at(keyTuple));
if(status == ChunkStatus::Dying) {
status = ChunkStatus::Dead;
return true;
} else { return false; }
});
if(dead) { return; }
auto chunkPos = glm::fvec3(key) * chunkSizeF;
auto pos = Point3(chunkPos.x, chunkPos.y, chunkPos.z);
auto data = GenerateChunk(Point3(std::get<0>(keyTuple), std::get<1>(keyTuple), std::get<2>(keyTuple)));
auto chunk = new Chunk(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data));
jobM->Do([this, keyTuple, chunk, pos] () {
auto id = engine->AddObject();
engine->AddComponent<PositionComponent>(id, pos);
engine->InsertComponent<ModelComponent>(id, chunk);
chunks.With([&keyTuple, id] (ChunksType &chunks) {
chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, id);
});
}, JobPriority::High, JobThread::Main);
}, JobPriority::Normal, JobThread::Worker);
}
}
}
}
}
}
}
}
void World::Destroy() {
}
std::vector<bool> World::GenerateChunk(const Point3 &&p) const {
std::vector<bool> blocks;
blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z);
const Point3 blockSize(1, 1, 1);
Point3 actual = p * Point3(blockSize.x * chunkSize.x, blockSize.y * chunkSize.y, blockSize.z * chunkSize.z);
int i = 0;
for(float z = 0; z < blockSize.z * chunkSize.z; z += blockSize.z) {
for(float x = 0; x < blockSize.x * chunkSize.x; x += blockSize.x) {
for(float y = 0; y < blockSize.y * chunkSize.y; y += blockSize.y) {
blocks.at(i++) = GenerateBlock(actual + Point3(x, y, z));
}
}
}
return blocks;
}
bool World::GenerateBlock(const Point3 &&p) const {
/* periodic 'normal distribution' function */
auto fDensity = [] (const double x) {
return 1.0 - glm::abs(glm::sin(x));
};
const float scale = 17.0f;
auto result = noise.eval(p.x / scale, p.y * 1.6f / scale, p.z / scale);
return (
result > (fDensity(p.x / scale / 32.0f) - 1) * 1.5f + 0.1f ||
result > (fDensity(p.y / scale / 10.0f) - 1) * 1.5f + 0.1f ||
result > (fDensity(p.z / scale / 32.0f) - 1) * 1.5f + 0.1f
);
}
<commit_msg>Various World fixes<commit_after>#include "common.h"
#include "World.h"
#include "JobManager.h"
#include "PositionComponent.h"
#include "PlayerCameraComponent.h"
void World::Init() {
}
void World::Update(DeltaTicks &) {
auto pair = engine->objects.right.equal_range(&typeid(PlayerCameraComponent));
for(auto it = pair.first; it != pair.second; ++it) {
auto object = it->get_left();
auto camera = static_cast<PlayerCameraComponent *>(it->info.get());
auto pos = engine->GetComponent<PositionComponent>(object);
if(pos != nullptr) {
const unsigned char distance = 5;
auto chunkSizeF = Point3(chunkSize);
auto keyBase = glm::ivec3(glm::round(pos->position.Get()) / chunkSizeF);
auto jobM = engine->systems.Get<JobManager>();
/* clean up chunks outside distance */
chunks.With([this, jobM, distance, &keyBase] (ChunksType &chunks) {
for(auto it = chunks.begin(); it != chunks.end();) {
auto &keyTuple = it->first;
auto obj = std::get<1>(it->second);
if(abs(std::get<0>(keyTuple) -keyBase.x) > distance ||
abs(std::get<1>(keyTuple) -keyBase.y) > distance ||
abs(std::get<2>(keyTuple) -keyBase.z) > distance) {
auto &status = std::get<0>(it->second);
switch(status) {
case ChunkStatus::Generating:
status = ChunkStatus::Dying;
break;
case ChunkStatus::Alive:
case ChunkStatus::Dead:
jobM->Do([this, obj] () { engine->RemoveObject(obj); }, JobPriority::Low, JobThread::Main);
chunks.erase(it++);
continue;
}
}
++it;
}
});
for(int d = 0; d <= distance; ++d) {
for(int x = -d; x <= d; ++x) {
for(int y = -d; y <= d; ++y) {
for(int z = -d; z <= d; ++z) {
auto key = keyBase + glm::ivec3(x, y, z);
auto keyTuple = std::make_tuple(key.x, key.y, key.z);
if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
return chunks.find(keyTuple) == chunks.end();
})) {
chunks.With([&keyTuple] (ChunksType &chunks) {
chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, 0));
});
jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () {
auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) {
auto &status = std::get<0>(chunks.at(keyTuple));
if(status == ChunkStatus::Dying) {
status = ChunkStatus::Dead;
return true;
} else { return false; }
});
if(dead) { return; }
auto pos = new PositionComponent(Point3(key) * chunkSizeF);
auto data = GenerateChunk(Point3(std::get<0>(keyTuple), std::get<1>(keyTuple), std::get<2>(keyTuple)));
auto chunk = new Chunk(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data));
jobM->Do([this, keyTuple, chunk, pos] () {
auto id = engine->AddObject();
engine->InsertComponent<PositionComponent>(id, pos);
engine->InsertComponent<ModelComponent>(id, chunk);
chunks.With([&keyTuple, id] (ChunksType &chunks) {
chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, id);
});
}, JobPriority::High, JobThread::Main);
}, JobPriority::Normal, JobThread::Worker);
}
}
}
}
}
}
}
}
void World::Destroy() {
}
std::vector<bool> World::GenerateChunk(const Point3 &&p) const {
std::vector<bool> blocks;
blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z);
const Point3 blockSize(1, 1, 1);
Point3 actual = p * Point3(blockSize.x * chunkSize.x, blockSize.y * chunkSize.y, blockSize.z * chunkSize.z);
int i = 0;
for(float z = 0; z < blockSize.z * chunkSize.z; z += blockSize.z) {
for(float x = 0; x < blockSize.x * chunkSize.x; x += blockSize.x) {
for(float y = 0; y < blockSize.y * chunkSize.y; y += blockSize.y) {
blocks.at(i++) = GenerateBlock(actual + Point3(x, y, z));
}
}
}
return blocks;
}
bool World::GenerateBlock(const Point3 &&p) const {
/* periodic 'normal distribution' function */
auto fDensity = [] (const double x) {
return 1.0 - glm::abs(glm::sin(x));
};
const float scale = 17.0f;
auto result = noise.eval(p.x / scale, p.y * 1.6f / scale, p.z / scale);
return (
result > (fDensity(p.x / scale / 32.0f) - 1) * 1.5f + 0.1f ||
result > (fDensity(p.y / scale / 10.0f) - 1) * 1.5f + 0.1f ||
result > (fDensity(p.z / scale / 32.0f) - 1) * 1.5f + 0.1f
);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <[email protected]>
* Changed: $Id: main.cpp 203 2012-09-25 08:47:55Z martinsiggel $
*
* Version: $Revision: 203 $
*
* 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 <iostream>
#include <fstream>
#include <clocale>
#include <QString>
#include <QMessageBox>
#include "TIGLViewerWindow.h"
#include "CommandLineParameters.h"
using namespace std;
int parseArguments(QStringList);
void showHelp(QString);
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#ifdef __APPLE__
app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
#endif
#if defined __linux__
// we need to set us locale as we use "." for decimal point
putenv("LC_NUMERIC=C");
setlocale(LC_NUMERIC, "C");
#elif defined __APPLE__
setlocale(LC_NUMERIC, "C");
#endif
// set shader file location
QString shaderDir = QCoreApplication::applicationDirPath();
#ifdef __APPLE__
shaderDir += "/../Resources";
#else
shaderDir += "/../share/tigl/shaders";
#endif
if (qgetenv("CSF_ShadersDirectory").isNull()) {
qputenv("CSF_ShadersDirectory", shaderDir.toUtf8());
}
int retval = parseArguments(app.arguments());
if (retval != 0) {
showHelp(app.arguments().at(0));
return retval;
}
TIGLViewerWindow window;
window.show();
if (!PARAMS.controlFile.isEmpty()){
window.setInitialControlFile(PARAMS.controlFile);
}
// if a filename is given, open the configuration
if (!PARAMS.initialFilename.isEmpty()) {
window.openFile(PARAMS.initialFilename);
}
// if a script is given
if (!PARAMS.initialScript.isEmpty()) {
window.openScript(PARAMS.initialScript);
}
retval = app.exec();
return retval;
}
/**
* Show a dialog with command line information.
*/
void showHelp(QString appName)
{
QString helpText = appName + " [--help] [--filename <filename>]\n\n";
helpText += " --help This help page\n";
helpText += " --filename <filename> Initial CPACS file to open and display.\n";
helpText += " --modelUID <uid> Initial model uid open and display.\n";
helpText += " --script <filename> Script to execute.\n";
helpText += " --windowtitle <title> The titel of the TIGLViewer window.\n";
helpText += " --controlFile <filename> Name of the control file.\n";
helpText += " --JediMode <on|off> Makes you some kind of superhero like CPACS-Ninja.\n";
QMessageBox::information(0, "TIGLViewer Argument Error",
helpText,
QMessageBox::Ok );
}
/**
* Parsing the command line arguments. The values will be saved
* in a global structure "PARAMS".
*/
int parseArguments(QStringList argList)
{
for (int i = 1; i < argList.size(); i++) {
QString arg = argList.at(i);
if (arg.compare("--help") == 0) {
return -1;
}
else if (arg.compare("--filename") == 0) {
if (i+1 >= argList.size()) {
cout << "missing filename" << endl;
return -1;
}
else {
PARAMS.initialFilename = argList.at(++i);
}
}
else if (arg.compare("--script") == 0) {
if (i+1 >= argList.size()) {
cout << "missing script filename" << endl;
return -1;
}
else {
PARAMS.initialScript = argList.at(++i);
}
}
else if (arg.compare("--windowtitle") == 0) {
if (i+1 >= argList.size()) {
cout << "missing windowtitle" << endl;
PARAMS.windowTitle = "TIGLViewer";
}
else {
PARAMS.windowTitle = argList.at(++i);
}
}
else if (arg.compare("--modelUID") == 0) {
if (i+1 >= argList.size()) {
cout << "missing modelUID" << endl;
PARAMS.modelUID = "";
}
else {
PARAMS.modelUID = argList.at(++i);
}
}
else if (arg.compare("--controlFile") == 0) {
if (i+1 >= argList.size()) {
cout << "missing controlFile" << endl;
PARAMS.controlFile = "";
}
else {
PARAMS.controlFile = argList.at(++i);
}
}
/* when there is a string behind the executable, we assume its the filename */
else {
PARAMS.initialFilename = arg;
}
}
return 0;
}
<commit_msg>Implemented check for shaders directory<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <[email protected]>
* Changed: $Id: main.cpp 203 2012-09-25 08:47:55Z martinsiggel $
*
* Version: $Revision: 203 $
*
* 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 <iostream>
#include <fstream>
#include <clocale>
#include <QString>
#include <QMessageBox>
#include "TIGLViewerWindow.h"
#include "CommandLineParameters.h"
using namespace std;
int parseArguments(QStringList);
void showHelp(QString);
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#ifdef __APPLE__
app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
#endif
#if defined __linux__
// we need to set us locale as we use "." for decimal point
putenv("LC_NUMERIC=C");
setlocale(LC_NUMERIC, "C");
#elif defined __APPLE__
setlocale(LC_NUMERIC, "C");
#endif
// set shader file location
QString shaderDir = QCoreApplication::applicationDirPath();
#ifdef __APPLE__
shaderDir += "/../Resources";
#else
shaderDir += "/../share/tigl/shaders";
#endif
QByteArray envVar = qgetenv("CSF_ShadersDirectory");
if (envVar.isNull()) {
qputenv("CSF_ShadersDirectory", shaderDir.toUtf8());
}
else {
shaderDir = envVar;
}
// check existance of shader dir
if (!QFile(shaderDir+"/PhongShading.fs").exists()) {
std::stringstream str;
str << "Illegal or non existing shader directory "
<< "<p><b>" << shaderDir.toStdString() << "</b></p>"
<< "Set the enviroment variable <b>CSF_ShadersDirectory</b> to provide a path for the OpenCASCADE shaders.";
QMessageBox::critical(0, "Startup error...",
str.str().c_str(),
QMessageBox::Ok );
return 1;
}
int retval = parseArguments(app.arguments());
if (retval != 0) {
showHelp(app.arguments().at(0));
return retval;
}
TIGLViewerWindow window;
window.show();
if (!PARAMS.controlFile.isEmpty()){
window.setInitialControlFile(PARAMS.controlFile);
}
// if a filename is given, open the configuration
if (!PARAMS.initialFilename.isEmpty()) {
window.openFile(PARAMS.initialFilename);
}
// if a script is given
if (!PARAMS.initialScript.isEmpty()) {
window.openScript(PARAMS.initialScript);
}
retval = app.exec();
return retval;
}
/**
* Show a dialog with command line information.
*/
void showHelp(QString appName)
{
QString helpText = appName + " [--help] [--filename <filename>]\n\n";
helpText += " --help This help page\n";
helpText += " --filename <filename> Initial CPACS file to open and display.\n";
helpText += " --modelUID <uid> Initial model uid open and display.\n";
helpText += " --script <filename> Script to execute.\n";
helpText += " --windowtitle <title> The titel of the TIGLViewer window.\n";
helpText += " --controlFile <filename> Name of the control file.\n";
helpText += " --JediMode <on|off> Makes you some kind of superhero like CPACS-Ninja.\n";
QMessageBox::information(0, "TIGLViewer Argument Error",
helpText,
QMessageBox::Ok );
}
/**
* Parsing the command line arguments. The values will be saved
* in a global structure "PARAMS".
*/
int parseArguments(QStringList argList)
{
for (int i = 1; i < argList.size(); i++) {
QString arg = argList.at(i);
if (arg.compare("--help") == 0) {
return -1;
}
else if (arg.compare("--filename") == 0) {
if (i+1 >= argList.size()) {
cout << "missing filename" << endl;
return -1;
}
else {
PARAMS.initialFilename = argList.at(++i);
}
}
else if (arg.compare("--script") == 0) {
if (i+1 >= argList.size()) {
cout << "missing script filename" << endl;
return -1;
}
else {
PARAMS.initialScript = argList.at(++i);
}
}
else if (arg.compare("--windowtitle") == 0) {
if (i+1 >= argList.size()) {
cout << "missing windowtitle" << endl;
PARAMS.windowTitle = "TIGLViewer";
}
else {
PARAMS.windowTitle = argList.at(++i);
}
}
else if (arg.compare("--modelUID") == 0) {
if (i+1 >= argList.size()) {
cout << "missing modelUID" << endl;
PARAMS.modelUID = "";
}
else {
PARAMS.modelUID = argList.at(++i);
}
}
else if (arg.compare("--controlFile") == 0) {
if (i+1 >= argList.size()) {
cout << "missing controlFile" << endl;
PARAMS.controlFile = "";
}
else {
PARAMS.controlFile = argList.at(++i);
}
}
/* when there is a string behind the executable, we assume its the filename */
else {
PARAMS.initialFilename = arg;
}
}
return 0;
}
<|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. *
**************************************************************************/
////////////////////////////////////////////////
// //
// Manager class for TRD hits //
// //
////////////////////////////////////////////////
#include "AliTRDtrackHits.h"
#include "TClonesArray.h"
#include "AliTRDhit.h"
#include <iostream.h>
ClassImp(AliTRDtrackHits)
void AliTRDtrackHits::AddHitTRD(Int_t volumeID, Int_t trackID, Double_t x,
Double_t y, Double_t z,Int_t q, Bool_t inDrift)
{
//
// Add one TRD hit
//
if (inDrift) q=2*q+1;
else q=2*q;
AddHitKartez(volumeID, trackID,x,y,z,q);
}
Bool_t AliTRDtrackHits::First()
{
//
//set Current hit for the first hit
//
AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(0);
if (!fHit)
fHit = new AliTRDhit;
if (!(param) ) {
fCurrentHit->fStatus = kFALSE;
return kFALSE;
}
//
fCurrentHit->fParamIndex = 0;
fCurrentHit->fStackIndex = 0;
//
//
((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
((AliTRDhit*)fHit)->SetX(param->fR*TMath::Cos(param->fFi));
((AliTRDhit*)fHit)->SetY(param->fR*TMath::Sin(param->fFi));
((AliTRDhit*)fHit)->SetZ(param->fZ);
((AliTRDhit*)fHit)->SetQ(param->fCharge[0]/2);
if (param->fCharge[0]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
else ((AliTRDhit*)fHit)->SetDrift();
fCurrentHit->fR = param->fR;
return fCurrentHit->fStatus = kTRUE;
}
Bool_t AliTRDtrackHits::Next()
{
//
//
if (!(fCurrentHit->fStatus))
return kFALSE;
fCurrentHit->fStackIndex++;
AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
if (fCurrentHit->fStackIndex>=((UInt_t) param->fNHits)){
fCurrentHit->fParamIndex++;
if (fCurrentHit->fParamIndex>=((UInt_t) fArray->GetEntriesFast())){
fCurrentHit->fStatus=kFALSE;
return kFALSE;
}
param = (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
fCurrentHit->fStackIndex=0;
fCurrentHit->fR = param->fR;
}
Double_t ratio;
// Double_t dfi2 = param->fAn+2*param->fAd*(fCurrentHit->fR-param->fR);
Double_t dfi2 = param->fAn;
dfi2*=dfi2*fCurrentHit->fR*fCurrentHit->fR;
// Double_t ddz2 = param->fTheta+2*param->fThetaD*(fCurrentHit->fR-param->fR);
Double_t ddz2 = param->fTheta;
ddz2*=ddz2;
ratio = TMath::Sqrt(1.+ dfi2+ ddz2);
fCurrentHit->fR += fStep*param->fHitDistance[fCurrentHit->fStackIndex]/ratio;
Double_t dR = fCurrentHit->fR - param->fR;
Double_t fi = param->fFi + (param->fAn*dR+param->fAd*dR*dR);
Double_t z = param->fZ + (param->fTheta*dR+param->fThetaD*dR*dR);
((AliTRDhit*)fHit)->SetQ(param->fCharge[fCurrentHit->fStackIndex]/2);
if ( param->fCharge[fCurrentHit->fStackIndex]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
else ((AliTRDhit*)fHit)->SetDrift();
((AliTRDhit*)fHit)->SetX(fCurrentHit->fR*TMath::Cos(fi));
((AliTRDhit*)fHit)->SetY(fCurrentHit->fR*TMath::Sin(fi));
((AliTRDhit*)fHit)->SetZ(z);
((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
return kTRUE;
}
<commit_msg>The size of the array is checked in First() (M.Ivanov)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
////////////////////////////////////////////////
// //
// Manager class for TRD hits //
// //
////////////////////////////////////////////////
#include "AliTRDtrackHits.h"
#include "TClonesArray.h"
#include "AliTRDhit.h"
#include <iostream.h>
ClassImp(AliTRDtrackHits)
void AliTRDtrackHits::AddHitTRD(Int_t volumeID, Int_t trackID, Double_t x,
Double_t y, Double_t z,Int_t q, Bool_t inDrift)
{
//
// Add one TRD hit
//
if (inDrift) q=2*q+1;
else q=2*q;
AddHitKartez(volumeID, trackID,x,y,z,q);
}
Bool_t AliTRDtrackHits::First()
{
//
//set Current hit for the first hit
//
if (fArray->GetSize()<=0) {
fCurrentHit->fStatus = kFALSE;
return kFALSE;
}
AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(0);
if (!fHit)
fHit = new AliTRDhit;
if (!(param) ) {
fCurrentHit->fStatus = kFALSE;
return kFALSE;
}
//
fCurrentHit->fParamIndex = 0;
fCurrentHit->fStackIndex = 0;
//
//
((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
((AliTRDhit*)fHit)->SetX(param->fR*TMath::Cos(param->fFi));
((AliTRDhit*)fHit)->SetY(param->fR*TMath::Sin(param->fFi));
((AliTRDhit*)fHit)->SetZ(param->fZ);
((AliTRDhit*)fHit)->SetQ(param->fCharge[0]/2);
if (param->fCharge[0]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
else ((AliTRDhit*)fHit)->SetDrift();
fCurrentHit->fR = param->fR;
return fCurrentHit->fStatus = kTRUE;
}
Bool_t AliTRDtrackHits::Next()
{
//
//
if (!(fCurrentHit->fStatus))
return kFALSE;
fCurrentHit->fStackIndex++;
AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
if (fCurrentHit->fStackIndex>=((UInt_t) param->fNHits)){
fCurrentHit->fParamIndex++;
if (fCurrentHit->fParamIndex>=((UInt_t) fArray->GetEntriesFast())){
fCurrentHit->fStatus=kFALSE;
return kFALSE;
}
param = (AliTrackHitsParamV2 *)fArray->At(fCurrentHit->fParamIndex);
fCurrentHit->fStackIndex=0;
fCurrentHit->fR = param->fR;
}
Double_t ratio;
// Double_t dfi2 = param->fAn+2*param->fAd*(fCurrentHit->fR-param->fR);
Double_t dfi2 = param->fAn;
dfi2*=dfi2*fCurrentHit->fR*fCurrentHit->fR;
// Double_t ddz2 = param->fTheta+2*param->fThetaD*(fCurrentHit->fR-param->fR);
Double_t ddz2 = param->fTheta;
ddz2*=ddz2;
ratio = TMath::Sqrt(1.+ dfi2+ ddz2);
fCurrentHit->fR += fStep*param->fHitDistance[fCurrentHit->fStackIndex]/ratio;
Double_t dR = fCurrentHit->fR - param->fR;
Double_t fi = param->fFi + (param->fAn*dR+param->fAd*dR*dR);
Double_t z = param->fZ + (param->fTheta*dR+param->fThetaD*dR*dR);
((AliTRDhit*)fHit)->SetQ(param->fCharge[fCurrentHit->fStackIndex]/2);
if ( param->fCharge[fCurrentHit->fStackIndex]%2==0) ((AliTRDhit*)fHit)->SetAmplification();
else ((AliTRDhit*)fHit)->SetDrift();
((AliTRDhit*)fHit)->SetX(fCurrentHit->fR*TMath::Cos(fi));
((AliTRDhit*)fHit)->SetY(fCurrentHit->fR*TMath::Sin(fi));
((AliTRDhit*)fHit)->SetZ(z);
((AliTRDhit*)fHit)->SetDetector(param->fVolumeID);
((AliTRDhit*)fHit)->SetTrack(param->fTrackID);
return kTRUE;
}
<|endoftext|> |
<commit_before>/* <x0/request.hpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <[email protected]>
*/
#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)
#include <x0/io/fileinfo.hpp>
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/strutils.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>
namespace x0 {
class plugin;
//! \addtogroup core
//@{
/**
* \brief a client HTTP reuqest object, holding the parsed x0 request data.
*
* \see header, response, connection, server
*/
struct X0_API request
{
public:
explicit request(x0::connection& connection);
x0::connection& connection; ///< the TCP/IP connection this request has been sent through
// request properties
buffer_ref method; ///< HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
buffer_ref uri; ///< parsed request uri
buffer_ref path; ///< decoded path-part
fileinfo_ptr fileinfo; ///< the final entity to be served, for example the full path to the file on disk.
buffer_ref query; ///< decoded query-part
int http_version_major; ///< HTTP protocol version major part that this request was formed in
int http_version_minor; ///< HTTP protocol version minor part that this request was formed in
std::vector<x0::request_header> headers; ///< request headers
std::string body; ///< body
/** retrieve value of a given request header */
buffer_ref header(const std::string& name) const;
// accumulated request data
buffer_ref username; ///< username this client has authenticated with.
std::string document_root; ///< the document root directory for this request.
// std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified.
// std::shared_ptr<range_def> range; //!< parsed "Range" request header
// custom data bindings
std::map<plugin *, custom_data_ptr> custom_data;
// utility methods
bool supports_protocol(int major, int minor) const;
std::string hostid() const;
void set_hostid(const std::string& custom);
private:
mutable std::string hostid_;
};
// {{{ request impl
inline request::request(x0::connection& conn) :
connection(conn)
{
}
inline bool request::supports_protocol(int major, int minor) const
{
if (major == http_version_major && minor <= http_version_minor)
return true;
if (major < http_version_major)
return true;
return false;
}
// }}}
//@}
} // namespace x0
#endif
<commit_msg>core: properly initialize request object variables<commit_after>/* <x0/request.hpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <[email protected]>
*/
#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)
#include <x0/io/fileinfo.hpp>
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/strutils.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>
namespace x0 {
class plugin;
//! \addtogroup core
//@{
/**
* \brief a client HTTP reuqest object, holding the parsed x0 request data.
*
* \see header, response, connection, server
*/
struct X0_API request
{
public:
explicit request(x0::connection& connection);
x0::connection& connection; ///< the TCP/IP connection this request has been sent through
// request properties
buffer_ref method; ///< HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
buffer_ref uri; ///< parsed request uri
buffer_ref path; ///< decoded path-part
fileinfo_ptr fileinfo; ///< the final entity to be served, for example the full path to the file on disk.
buffer_ref query; ///< decoded query-part
int http_version_major; ///< HTTP protocol version major part that this request was formed in
int http_version_minor; ///< HTTP protocol version minor part that this request was formed in
std::vector<x0::request_header> headers; ///< request headers
std::string body; ///< body
/** retrieve value of a given request header */
buffer_ref header(const std::string& name) const;
// accumulated request data
buffer_ref username; ///< username this client has authenticated with.
std::string document_root; ///< the document root directory for this request.
// std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified.
// std::shared_ptr<range_def> range; //!< parsed "Range" request header
// custom data bindings
std::map<plugin *, custom_data_ptr> custom_data;
// utility methods
bool supports_protocol(int major, int minor) const;
std::string hostid() const;
void set_hostid(const std::string& custom);
private:
mutable std::string hostid_;
};
// {{{ request impl
inline request::request(x0::connection& conn) :
connection(conn),
method(),
uri(),
path(),
fileinfo(),
query(),
http_version_major(0),
http_version_minor(0),
headers(),
body(),
username(),
document_root(),
custom_data(),
hostid_()
{
}
inline bool request::supports_protocol(int major, int minor) const
{
if (major == http_version_major && minor <= http_version_minor)
return true;
if (major < http_version_major)
return true;
return false;
}
// }}}
//@}
} // namespace x0
#endif
<|endoftext|> |
<commit_before>#include "Galaxy.h"
extern "C"
{
#include <png.h>
#include <pngconf.h>
}
#include <fstream>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <direct.h>
Galaxy::Galaxy()
{
mWidth = 2000;
mHeight = 2000;
mAverageStellarDensity = 0.1;
mAverageStellarTemperature = 0.5;
mAverageStellarRadius = 4.0;
mBaseSeed = time(0);
mLayerScale = 4;
mLayerCount = 3;
mTwister = new std::mt19937();
mTwister->seed(mBaseSeed);
mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}
Galaxy::~Galaxy()
{
delete mRandomDistribution;
delete mTwister;
}
void Galaxy::ParseSettings(int argc, char* arguments[])
{
int iter = 0;
while (iter < argc)
{
if (strcmp(arguments[iter], "-w") == 0)
{
mWidth = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-h") == 0) {
mHeight = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-s") == 0) {
mBaseSeed = atol(arguments[++iter]);
delete mRandomDistribution;
delete mTwister;
mTwister = new std::mt19937;
mTwister->seed(mBaseSeed);
mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}
else if (strcmp(arguments[iter], "-l") == 0) {
mLayerCount = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-c") == 0) {
mLayerCount = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-r") == 0) {
mAverageStellarRadius = atof(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-d") == 0) {
mAverageStellarDensity = atof(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-t") == 0) {
mAverageStellarTemperature = atof(arguments[++iter]);
}
++iter;
}
}
bool Galaxy::CreateDirectoryTree()
{
char dir[128];
for (int i = 0; i < mLayerCount; ++i)
{
sprintf_s(dir, "layer_%03d", i);
if (_mkdir(dir) == ENOENT)
{
return false;
}
}
return true;
}
void Galaxy::ExportPng(unsigned int* data, int z, int slice)
{
char slice_name[128];
sprintf_s(slice_name, "slice%06d", slice);
char path[256];
sprintf_s(path, "layer_%03d/slice_%s.png", z, slice_name);
fprintf(stdout, "Exported to %s\n", path);
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
png_bytep row;
fopen_s(&fp, path, "wb");
if (fp == NULL)
{
fprintf(stderr, "Could not open %s for writing\n", path);
return;
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
fprintf(stderr, "Could not allocate write struct\n");
return;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
fprintf(stderr, "Could not allocate info struct\n");
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr,
info_ptr,
mWidth, mHeight,
8,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
row = (png_bytep) malloc(4 * mWidth * sizeof(png_byte));
for (int y = 0; y < mHeight; y++)
{
for (int x = 0; x < mWidth; x++)
{
memcpy(&(row[x*4]), &(data[(mWidth * mHeight * slice)+(y*mWidth) + x]), 4);
}
png_write_row(png_ptr, row);
}
png_write_end(png_ptr, NULL);
fclose(fp);
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
free(row);
}
void Galaxy::Generate()
{
CreateDirectoryTree();
for (int z = 0; z < mLayerCount; ++z)
{
GenerateLayer(z);
}
}
void Galaxy::DrawStar(unsigned int* buffer, unsigned long cx, unsigned long cy, unsigned long w, unsigned long h, double radius, double temperature)
{
unsigned long interior = floor(radius * 0.6);
long length = ceil(radius);
unsigned long hyp = pow(radius, 2);
unsigned long distance = 0;
unsigned long x = 0;
unsigned long y = 0;
unsigned int color = 0x00000000;
for (long y = -length; y < length; ++y)
{
for (long x = -length; x < length; ++x)
{
distance = pow(y,2) + pow(x, 2);
if (((distance < interior) && (distance < hyp)) || ((x == 0) && (y == 0)))
{
color = CoreTemperatureToColor(temperature).values.intValue;
}
else
{
double magnitude = pow((double)x/(double)length,2.0) + pow((double)y/(double)length,2.0);
if (magnitude > 1)
{
color = 0x00000000;
}
else
{
Color corona = CoreTemperatureToColor(temperature);
corona.values.argbValues.a = 255.0 * (1.0 - magnitude);
color = corona.values.intValue;
}
}
if (((cy + y) < h) && ((cy + y) > 0) && ((cx + x) < w) && ((cx + x) > 0) && (color != 0x00000000))
{
buffer[((cy + y) * w) + (cx + x)] = color;
}
}
}
}
Color Galaxy::CoreTemperatureToColor(double temperature)
{
int index = floor(COLOR_COUNT * temperature);
return ScaleColor(coreColors[index], GetTemperatureBrightness(temperature));
}
Color Galaxy::CoronaTemperatureToColor(double temperature)
{
int index = floor(COLOR_COUNT * temperature);
return ScaleColor(coronaColors[index], GetTemperatureBrightness(temperature));
}
Color Galaxy::ScaleColor(Color color, double amount)
{
color.values.argbValues.r *= amount;
color.values.argbValues.g *= amount;
color.values.argbValues.b *= amount;
return color;
}
double Galaxy::GetTemperatureBrightness(double temperature)
{
double fraction = 1.0 / COLOR_COUNT;
while (temperature > fraction)
{
temperature -= fraction;
}
return temperature/fraction;
}
double Galaxy::Random()
{
return (*mRandomDistribution)(*mTwister);
}
void Galaxy::GenerateLayer(int z)
{
int length = sqrt((pow(4, z))); //1, 4, 16, 64
unsigned long layerW = mWidth * length;
unsigned long layerH = mHeight * length;
unsigned int* buffer = new unsigned int[layerW * layerH];
for (unsigned long k = 0; k < (layerW * layerH); ++k)
{
buffer[k] = 0x00000000;
}
double density = 0;
double starCount = 0;
unsigned long x = 0;
unsigned long y = 0;
double radius = 0.0;
double temperature = 0.0;
while (density < mAverageStellarDensity)
{
x = layerW * Random();
y = layerH * Random();
radius = 2 * mAverageStellarRadius * Random();
temperature = 2 * mAverageStellarTemperature * Random();
DrawStar(buffer, x, y, layerW, layerH, radius, temperature);
starCount += 1.0;
density = starCount / (layerW * layerH);
}
for (int y = 0; y < length; ++y)
{
for (int x = 0; x < length; ++x)
{
unsigned long index = (y * length) + x;
ExportPng(buffer, z, index);
}
}
delete [] buffer;
}<commit_msg>MoarShapes<commit_after>#include "Galaxy.h"
extern "C"
{
#include <png.h>
#include <pngconf.h>
}
#include <fstream>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <direct.h>
Galaxy::Galaxy()
{
mWidth = 2000;
mHeight = 2000;
mAverageStellarDensity = 0.1;
mAverageStellarTemperature = 0.5;
mAverageStellarRadius = 4.0;
mBaseSeed = time(0);
mLayerScale = 4;
mLayerCount = 3;
mTwister = new std::mt19937();
mTwister->seed(mBaseSeed);
mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}
Galaxy::~Galaxy()
{
delete mRandomDistribution;
delete mTwister;
}
void Galaxy::ParseSettings(int argc, char* arguments[])
{
int iter = 0;
while (iter < argc)
{
if (strcmp(arguments[iter], "-w") == 0)
{
mWidth = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-h") == 0) {
mHeight = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-s") == 0) {
mBaseSeed = atol(arguments[++iter]);
delete mRandomDistribution;
delete mTwister;
mTwister = new std::mt19937;
mTwister->seed(mBaseSeed);
mRandomDistribution = new std::uniform_real_distribution<double>(0, std::nextafter(1, DBL_MAX));
}
else if (strcmp(arguments[iter], "-l") == 0) {
mLayerCount = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-c") == 0) {
mLayerCount = atol(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-r") == 0) {
mAverageStellarRadius = atof(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-d") == 0) {
mAverageStellarDensity = atof(arguments[++iter]);
}
else if (strcmp(arguments[iter], "-t") == 0) {
mAverageStellarTemperature = atof(arguments[++iter]);
}
++iter;
}
}
bool Galaxy::CreateDirectoryTree()
{
char dir[128];
for (int i = 0; i < mLayerCount; ++i)
{
sprintf_s(dir, "layer_%03d", i);
if (_mkdir(dir) == ENOENT)
{
return false;
}
}
return true;
}
void Galaxy::ExportPng(unsigned int* data, int z, int slice)
{
char slice_name[128];
sprintf_s(slice_name, "slice%06d", slice);
char path[256];
sprintf_s(path, "layer_%03d/slice_%s.png", z, slice_name);
fprintf(stdout, "Exported to %s\n", path);
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
png_bytep row;
fopen_s(&fp, path, "wb");
if (fp == NULL)
{
fprintf(stderr, "Could not open %s for writing\n", path);
return;
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
fprintf(stderr, "Could not allocate write struct\n");
return;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
fprintf(stderr, "Could not allocate info struct\n");
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr,
info_ptr,
mWidth, mHeight,
8,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
row = (png_bytep) malloc(4 * mWidth * sizeof(png_byte));
for (int y = 0; y < mHeight; y++)
{
for (int x = 0; x < mWidth; x++)
{
memcpy(&(row[x*4]), &(data[(mWidth * mHeight * slice)+(y*mWidth) + x]), 4);
}
png_write_row(png_ptr, row);
}
png_write_end(png_ptr, NULL);
fclose(fp);
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
free(row);
}
void Galaxy::Generate()
{
CreateDirectoryTree();
for (int z = 0; z < mLayerCount; ++z)
{
GenerateLayer(z);
}
}
void Galaxy::DrawStar(unsigned int* buffer, unsigned long cx, unsigned long cy, unsigned long w, unsigned long h, double radius, double temperature)
{
unsigned long interior = floor(radius * 0.6);
long length = ceil(radius);
unsigned long hyp = pow(radius, 2);
unsigned long distance = 0;
unsigned long x = 0;
unsigned long y = 0;
unsigned int color = 0x00000000;
for (long y = -length; y < length; ++y)
{
for (long x = -length; x < length; ++x)
{
//Determine radial distance from any corner
double corner_dist = pow((length/2) - abs(x),2) + pow((length/2) - abs(y), 2);
distance = pow(x, 2) + pow(y, 2);
if ((distance < interior) || ((x == 0) && (y == 0)))
{
color = CoreTemperatureToColor(temperature).values.intValue;
}
else
{
double magnitude = pow((double)x/(double)length,2.0) + pow((double)y/(double)length,2.0);
if (magnitude > 1)
{
color = 0x00000000;
}
else
{
Color corona = CoreTemperatureToColor(temperature);
corona.values.argbValues.a = 255.0 * (1.0 - magnitude);
color = corona.values.intValue;
}
}
if (((cy + y) < h) && ((cy + y) > 0) && ((cx + x) < w) && ((cx + x) > 0) && (color != 0x00000000))
{
buffer[((cy + y) * w) + (cx + x)] = color;
}
}
}
}
Color Galaxy::CoreTemperatureToColor(double temperature)
{
int index = floor(COLOR_COUNT * temperature);
return ScaleColor(coreColors[index], GetTemperatureBrightness(temperature));
}
Color Galaxy::CoronaTemperatureToColor(double temperature)
{
int index = floor(COLOR_COUNT * temperature);
return ScaleColor(coronaColors[index], GetTemperatureBrightness(temperature));
}
Color Galaxy::ScaleColor(Color color, double amount)
{
color.values.argbValues.r *= amount;
color.values.argbValues.g *= amount;
color.values.argbValues.b *= amount;
return color;
}
double Galaxy::GetTemperatureBrightness(double temperature)
{
double fraction = 1.0 / COLOR_COUNT;
while (temperature > fraction)
{
temperature -= fraction;
}
return temperature/fraction;
}
double Galaxy::Random()
{
return (*mRandomDistribution)(*mTwister);
}
void Galaxy::GenerateLayer(int z)
{
int length = sqrt((pow(4, z))); //1, 4, 16, 64
unsigned long layerW = mWidth * length;
unsigned long layerH = mHeight * length;
unsigned int* buffer = new unsigned int[layerW * layerH];
for (unsigned long k = 0; k < (layerW * layerH); ++k)
{
buffer[k] = 0x00000000;
}
double density = 0;
double starCount = 0;
unsigned long x = 0;
unsigned long y = 0;
double radius = 0.0;
double temperature = 0.0;
while (density < mAverageStellarDensity)
{
x = layerW * Random();
y = layerH * Random();
radius = 2 * mAverageStellarRadius * Random();
temperature = 2 * mAverageStellarTemperature * Random();
DrawStar(buffer, x, y, layerW, layerH, radius, temperature);
starCount += 1.0;
density = starCount / (layerW * layerH);
}
for (int y = 0; y < length; ++y)
{
for (int x = 0; x < length; ++x)
{
unsigned long index = (y * length) + x;
ExportPng(buffer, z, index);
}
}
delete [] buffer;
}<|endoftext|> |
<commit_before>// Copyright (c) 2009-2019 The libsfz Authors
//
// This file is part of libsfz, a free software project. You can redistribute it and/or modify it
// under the terms of the MIT License.
#include <sfz/string-utils.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <pn/string>
#include <sfz/encoding.hpp>
using testing::Eq;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Test;
namespace sfz {
namespace {
template <typename T>
struct ValueOrMessage {
template <typename U>
ValueOrMessage(U u) : value(u), message(NULL) {}
ValueOrMessage(const char* m) : value(0), message(m) {}
T value;
const char* message;
};
template <>
struct ValueOrMessage<const char*> {
ValueOrMessage(const char* m) : value(m), message(m) {}
const char* value;
const char* message;
};
using StringUtilitiesTest = ::testing::Test;
TEST_F(StringUtilitiesTest, Upper) {
std::pair<pn::string_view, pn::string_view> inputs[] = {
{"", ""}, {"a", "A"}, {"Na", "NA"}, {"WTF", "WTF"},
{"w00t", "W00T"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
};
for (const auto& input : inputs) {
pn::string actual = upper(input.first);
pn::string_view expected = input.second;
EXPECT_THAT(actual, Eq(expected))
<< "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
}
}
TEST_F(StringUtilitiesTest, Lower) {
std::pair<pn::string_view, pn::string_view> inputs[] = {
{"", ""}, {"A", "a"}, {"Na", "na"}, {"ill", "ill"},
{"HNO2", "hno2"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
};
for (const auto& input : inputs) {
pn::string actual = lower(input.first);
pn::string_view expected = input.second;
EXPECT_THAT(actual, Eq(expected))
<< "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
}
}
} // namespace
} // namespace sfz
<commit_msg>Remove test for Greek upper/lowercase<commit_after>// Copyright (c) 2009-2019 The libsfz Authors
//
// This file is part of libsfz, a free software project. You can redistribute it and/or modify it
// under the terms of the MIT License.
#include <sfz/string-utils.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <pn/string>
#include <sfz/encoding.hpp>
using testing::Eq;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Test;
namespace sfz {
namespace {
template <typename T>
struct ValueOrMessage {
template <typename U>
ValueOrMessage(U u) : value(u), message(NULL) {}
ValueOrMessage(const char* m) : value(0), message(m) {}
T value;
const char* message;
};
template <>
struct ValueOrMessage<const char*> {
ValueOrMessage(const char* m) : value(m), message(m) {}
const char* value;
const char* message;
};
using StringUtilitiesTest = ::testing::Test;
TEST_F(StringUtilitiesTest, Upper) {
std::pair<pn::string_view, pn::string_view> inputs[] = {
{"", ""}, {"a", "A"}, {"Na", "NA"},
{"WTF", "WTF"}, {"w00t", "W00T"}, {"林さん", "林さん"},
};
for (const auto& input : inputs) {
pn::string actual = upper(input.first);
pn::string_view expected = input.second;
EXPECT_THAT(actual, Eq(expected))
<< "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
}
}
TEST_F(StringUtilitiesTest, Lower) {
std::pair<pn::string_view, pn::string_view> inputs[] = {
{"", ""}, {"A", "a"}, {"Na", "na"},
{"ill", "ill"}, {"HNO2", "hno2"}, {"林さん", "林さん"},
};
for (const auto& input : inputs) {
pn::string actual = lower(input.first);
pn::string_view expected = input.second;
EXPECT_THAT(actual, Eq(expected))
<< "input: " << input.first.copy().c_str() << "; actual: " << actual.c_str();
}
}
} // namespace
} // namespace sfz
<|endoftext|> |
<commit_before>/*
* Memory Mapping Allocator
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/mmap_mem.h>
#include <cstring>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef MAP_FAILED
#define MAP_FAILED -1
#endif
namespace Botan {
namespace {
/*
* MemoryMapping_Allocator Exception
*/
class BOTAN_DLL MemoryMapping_Failed : public Exception
{
public:
MemoryMapping_Failed(const std::string& msg) :
Exception("MemoryMapping_Allocator: " + msg) {}
};
}
/*
* Memory Map a File into Memory
*/
void* MemoryMapping_Allocator::alloc_block(u32bit n)
{
class TemporaryFile
{
public:
int get_fd() const { return fd; }
const std::string path() const { return filepath; }
TemporaryFile(const std::string& base)
{
const std::string path = base + "XXXXXX";
filepath = new char[path.length() + 1];
std::strcpy(filepath, path.c_str());
mode_t old_umask = ::umask(077);
fd = ::mkstemp(filepath);
::umask(old_umask);
}
~TemporaryFile()
{
delete[] filepath;
if(fd != -1 && ::close(fd) == -1)
throw MemoryMapping_Failed("Could not close file");
}
private:
int fd;
char* filepath;
};
TemporaryFile file("/tmp/botan_");
if(file.get_fd() == -1)
throw MemoryMapping_Failed("Could not create file");
if(::unlink(file.path().c_str()))
throw MemoryMapping_Failed("Could not unlink file '" + file.path() + "'");
if(::lseek(file.get_fd(), n-1, SEEK_SET) < 0)
throw MemoryMapping_Failed("Could not seek file");
if(::write(file.get_fd(), "\0", 1) != 1)
throw MemoryMapping_Failed("Could not write to file");
#ifndef MAP_NOSYNC
#define MAP_NOSYNC 0
#endif
void* ptr = ::mmap(0, n,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_NOSYNC,
file.get_fd(), 0);
if(ptr == static_cast<void*>(MAP_FAILED))
throw MemoryMapping_Failed("Could not map file");
return ptr;
}
/*
* Remove a Memory Mapping
*/
void MemoryMapping_Allocator::dealloc_block(void* ptr, u32bit n)
{
if(ptr == 0)
return;
const byte PATTERNS[] = { 0x00, 0xFF, 0xAA, 0x55, 0x73, 0x8C, 0x5F, 0xA0,
0x6E, 0x91, 0x30, 0xCF, 0xD3, 0x2C, 0xAC, 0x00 };
for(u32bit j = 0; j != sizeof(PATTERNS); j++)
{
std::memset(ptr, PATTERNS[j], n);
if(::msync(ptr, n, MS_SYNC))
throw MemoryMapping_Failed("Sync operation failed");
}
if(::munmap(ptr, n))
throw MemoryMapping_Failed("Could not unmap file");
}
}
<commit_msg>Change how alloc_mmap's TemporaryFile class works. Don't expose the name at all; instead unlink it at the end of the constructor, so by the time it is fully constructed it is purely an anonymous file descriptor.<commit_after>/*
* Memory Mapping Allocator
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/mmap_mem.h>
#include <vector>
#include <cstring>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef MAP_FAILED
#define MAP_FAILED -1
#endif
namespace Botan {
namespace {
/*
* MemoryMapping_Allocator Exception
*/
class BOTAN_DLL MemoryMapping_Failed : public Exception
{
public:
MemoryMapping_Failed(const std::string& msg) :
Exception("MemoryMapping_Allocator: " + msg) {}
};
}
/*
* Memory Map a File into Memory
*/
void* MemoryMapping_Allocator::alloc_block(u32bit n)
{
class TemporaryFile
{
public:
int get_fd() const { return fd; }
TemporaryFile(const std::string& base)
{
const std::string mkstemp_template = base + "XXXXXX";
std::vector<char> filepath(mkstemp_template.begin(),
mkstemp_template.end());
filepath.push_back(0); // add terminating NULL
mode_t old_umask = ::umask(077);
fd = ::mkstemp(&filepath[0]);
::umask(old_umask);
if(fd == -1)
throw MemoryMapping_Failed("Temporary file allocation failed");
if(::unlink(&filepath[0]) != 0)
throw MemoryMapping_Failed("Could not unlink temporary file");
}
~TemporaryFile()
{
/*
* We can safely close here, because post-mmap the file
* will continue to exist until the mmap is unmapped from
* our address space upon deallocation.
*/
if(fd != -1 && ::close(fd) == -1)
throw MemoryMapping_Failed("Could not close file");
}
private:
int fd;
};
TemporaryFile file("/tmp/botan_");
if(file.get_fd() == -1)
throw MemoryMapping_Failed("Could not create file");
if(::lseek(file.get_fd(), n-1, SEEK_SET) < 0)
throw MemoryMapping_Failed("Could not seek file");
if(::write(file.get_fd(), "\0", 1) != 1)
throw MemoryMapping_Failed("Could not write to file");
#ifndef MAP_NOSYNC
#define MAP_NOSYNC 0
#endif
void* ptr = ::mmap(0, n,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_NOSYNC,
file.get_fd(), 0);
if(ptr == static_cast<void*>(MAP_FAILED))
throw MemoryMapping_Failed("Could not map file");
return ptr;
}
/*
* Remove a Memory Mapping
*/
void MemoryMapping_Allocator::dealloc_block(void* ptr, u32bit n)
{
if(ptr == 0)
return;
const byte PATTERNS[] = { 0x00, 0xFF, 0xAA, 0x55, 0x73, 0x8C, 0x5F, 0xA0,
0x6E, 0x91, 0x30, 0xCF, 0xD3, 0x2C, 0xAC, 0x00 };
for(u32bit j = 0; j != sizeof(PATTERNS); j++)
{
std::memset(ptr, PATTERNS[j], n);
if(::msync(ptr, n, MS_SYNC))
throw MemoryMapping_Failed("Sync operation failed");
}
if(::munmap(ptr, n))
throw MemoryMapping_Failed("Could not unmap file");
}
}
<|endoftext|> |
<commit_before>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"
#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"
int
GenerateConfigFile::operator() () {
dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );
std::map< std::string, std::string > mapping;
mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";
// FIXME: Do something clever for versioning.
// (Should these be in the param table?)
scratchpad->Assign( "odiDefaultInstanceType", "m4.large" );
mapping[ "odiDefaultInstanceType" ] = "ANNEX_DEFAULT_ODI_INSTANCE_TYPE";
scratchpad->Assign( "odiDefaultImageID", "ami-83269195" );
mapping[ "odiDefaultImageID" ] = "ANNEX_DEFAULT_ODI_IMAGE_ID";
// Append the annex configuration to the user config file.
FILE * configFile = NULL;
// Consider using createUserConfigDir() from CreateKeyPair.cpp.
std::string userConfigName;
MyString userConfigSource;
param( userConfigName, "USER_CONFIG_FILE" );
if(! userConfigName.empty()) {
find_user_file( userConfigSource, userConfigName.c_str(), false );
if(! userConfigSource.empty()) {
// Create the containing directory if necessary, and only the
// containing directory -- don't do anything stupid if the
// user configuration directory is misconfigured.
std::string dir, file;
filename_split( userConfigSource.c_str(), dir, file );
if(! IsDirectory( dir.c_str() )) {
mkdir( dir.c_str(), 0755 );
}
configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
"a", 0644 );
if( configFile == NULL ) {
fprintf( stderr, "Failed to open user configuration file '%s': %s (%d). Printing configuration...\n",
userConfigSource.c_str(), strerror( errno ), errno );
configFile = stdout;
}
} else {
fprintf( stderr, "Unable to locate your user configuration file. Printing configuration...\n" );
configFile = stdout;
}
} else {
fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files. Contact your system administrator. Printing configuration...\n" );
configFile = stdout;
}
fprintf( configFile, "\n" );
fprintf( configFile, "# Generated by condor_annex -setup.\n" );
std::string value;
for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
value.clear();
scratchpad->LookupString( i->first.c_str(), value );
if(! value.empty()) {
fprintf( configFile, "%s = %s\n", i->second.c_str(), value.c_str() );
}
}
std::string keyPath;
scratchpad->LookupString( "KeyPath", keyPath );
if(! keyPath.empty()) {
fprintf( configFile, "# For debugging:\n" );
fprintf( configFile, "# ssh -i %s +ec2-user@<address>\n", keyPath.c_str() );
}
fprintf( configFile, "\n" );
daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
return PASS_STREAM;
}
int
GenerateConfigFile::rollback() {
dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );
// This functor does nothing (to the service), so don't undo anything.
daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
return PASS_STREAM;
}
<commit_msg>(#6216) Update the default AMI.<commit_after>#include "condor_common.h"
#include "classad_collection.h"
#include "gahp-client.h"
#include "Functor.h"
#include "GenerateConfigFile.h"
#include "condor_config.h"
#include "filename_tools.h"
#include "directory.h"
#include "safe_fopen.h"
int
GenerateConfigFile::operator() () {
dprintf( D_FULLDEBUG, "GenerateConfigFile::operator()\n" );
std::map< std::string, std::string > mapping;
mapping[ "S3BucketName" ] = "ANNEX_DEFAULT_S3_BUCKET";
mapping[ "odiLeaseFunctionARN" ] = "ANNEX_DEFAULT_ODI_LEASE_FUNCTION_ARN";
mapping[ "sfrLeaseFunctionARN" ] = "ANNEX_DEFAULT_SFR_LEASE_FUNCTION_ARN";
mapping[ "InstanceProfileARN" ] = "ANNEX_DEFAULT_ODI_INSTANCE_PROFILE_ARN";
mapping[ "SecurityGroupID" ] = "ANNEX_DEFAULT_ODI_SECURITY_GROUP_IDS";
mapping[ "KeyName" ] = "ANNEX_DEFAULT_ODI_KEY_NAME";
mapping[ "AccessKeyFile" ] = "ANNEX_DEFAULT_ACCESS_KEY_FILE";
mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";
// FIXME: Do something clever for versioning.
scratchpad->Assign( "odiDefaultInstanceType", "m4.large" );
mapping[ "odiDefaultInstanceType" ] = "ANNEX_DEFAULT_ODI_INSTANCE_TYPE";
scratchpad->Assign( "odiDefaultImageID", "ami-35b13223" );
mapping[ "odiDefaultImageID" ] = "ANNEX_DEFAULT_ODI_IMAGE_ID";
// Append the annex configuration to the user config file.
FILE * configFile = NULL;
// Consider using createUserConfigDir() from CreateKeyPair.cpp.
std::string userConfigName;
MyString userConfigSource;
param( userConfigName, "USER_CONFIG_FILE" );
if(! userConfigName.empty()) {
find_user_file( userConfigSource, userConfigName.c_str(), false );
if(! userConfigSource.empty()) {
// Create the containing directory if necessary, and only the
// containing directory -- don't do anything stupid if the
// user configuration directory is misconfigured.
std::string dir, file;
filename_split( userConfigSource.c_str(), dir, file );
if(! IsDirectory( dir.c_str() )) {
mkdir( dir.c_str(), 0755 );
}
configFile = safe_fcreate_keep_if_exists_follow( userConfigSource.c_str(),
"a", 0644 );
if( configFile == NULL ) {
fprintf( stderr, "Failed to open user configuration file '%s': %s (%d). Printing configuration...\n",
userConfigSource.c_str(), strerror( errno ), errno );
configFile = stdout;
}
} else {
fprintf( stderr, "Unable to locate your user configuration file. Printing configuration...\n" );
configFile = stdout;
}
} else {
fprintf( stderr, "Your HTCondor installation is configured to ignore user configuration files. Contact your system administrator. Printing configuration...\n" );
configFile = stdout;
}
fprintf( configFile, "\n" );
fprintf( configFile, "# Generated by condor_annex -setup.\n" );
std::string value;
for( auto i = mapping.begin(); i != mapping.end(); ++i ) {
value.clear();
scratchpad->LookupString( i->first.c_str(), value );
if(! value.empty()) {
fprintf( configFile, "%s = %s\n", i->second.c_str(), value.c_str() );
}
}
std::string keyPath;
scratchpad->LookupString( "KeyPath", keyPath );
if(! keyPath.empty()) {
fprintf( configFile, "# For debugging:\n" );
fprintf( configFile, "# ssh -i %s +ec2-user@<address>\n", keyPath.c_str() );
}
fprintf( configFile, "\n" );
daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
return PASS_STREAM;
}
int
GenerateConfigFile::rollback() {
dprintf( D_FULLDEBUG, "GenerateConfigFile::rollback()\n" );
// This functor does nothing (to the service), so don't undo anything.
daemonCore->Reset_Timer( gahp->getNotificationTimerId(), 0, TIMER_NEVER );
return PASS_STREAM;
}
<|endoftext|> |
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* cliAppInit.c --
*
*
* This file initiliazes the application by calling all
* the new commands and thier respective arguments
*
*
*
* Dated : 12/13/2000.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Not sure if we need to worry about old gcc compilers any more, but ... /leif
#if (__GNUC__ >= 3)
#include <iostream>
#else
#include <iostream.h>
#endif
//#include "tclExtend.h"
#include "tcl.h"
#include <unistd.h>
#include <sys/types.h>
#include "CliMgmtUtils.h"
#include "createCommand.h"
#include "hashtable.h"
#include "createArgument.h"
#include "definitions.h"
#include "ShowCmd.h"
#include "ConfigCmd.h"
#include "CliCreateCommands.h"
#if HAVE_EDITLINE_READLINE_H
#include <editline/readline.h>
#elif HAVE_READLINE_READLINE_H
#include <readline/readline.h>
#if HAVE_READLINE_HISTORY_H
#include <readline/history.h>
#endif
#endif
Tcl_Interp *interp;
extern Tcl_HashTable CommandHashtable;
int
Tcl_AppInit(Tcl_Interp * app_interp)
{
/*
* Intialize the Tcl interpreter.
*/
if (Tcl_Init(app_interp) == TCL_ERROR)
return TCL_ERROR;
interp = app_interp;
#ifdef TCL_MEM_DEBUG
Tcl_InitMemory(interp);
#endif
cliCreateCommandHashtable();
// root users are automatically enabled
if (getuid() == 0) {
enable_restricted_commands = TRUE;
}
if (CliCreateCommands() != CLI_OK)
return CMD_ERROR;
Tcl_SetVar(interp, "tcl_rcFileName", "~/.tshellstartup", TCL_GLOBAL_ONLY);
/* Evaluating a application specific tcl script After creating
all the commands and sourcing the statup file */
/* Always this should be at the end of this function. */
/*
* Parse command-line arguments. A leading "-file" argument is
* ignored (a historical relic from the distant past). If the
* next argument doesn't start with a "-" then strip it off and
* use it as the name of a script file to process.
*/
const char *fileName = Tcl_GetVar(interp, "argv", TCL_LEAVE_ERR_MSG);
/*
* Invoke the script specified on the command line, if any.
*/
if (fileName[0] != '\0') {
int listArgc;
const char **listArgv;
if (Tcl_SplitList(interp, fileName, &listArgc, &listArgv) != TCL_OK) {
return TCL_ERROR;
}
int length = strlen(listArgv[0]);
if ((length >= 2) && (strncmp(listArgv[0], "-file", length) == 0)) {
for (int index = 1; index < listArgc; index++) {
Tcl_ResetResult(interp);
if (Tcl_EvalFile(interp, listArgv[index]) != TCL_OK) {
Tcl_AddErrorInfo(interp, "");
Tcl_DeleteInterp(interp);
Tcl_Exit(1);
}
}
}
ckfree((char *) listArgv);
}
Tcl_ResetResult(interp);
return TCL_OK;
}
#if HAVE_LIBREADLINE
// TCL main read, eval, print loop. We don't use Tcl_Main because we want to
// use readline to get line editing and command history.
void Tcl_ReadlineMain(void)
{
char * line;
for (;;) {
line = readline("trafficserver> ");
if (line == NULL) {
// Received EOF. Bound this into a TCL exit command just like Tcl_Main
// does.
Tcl_Eval(interp, "exit;");
}
if (*line) {
add_history(line);
Tcl_Eval(interp, line);
}
free(line);
}
exit(0);
}
#endif // HAVE_LIBREADLINE
// vim: set ts=2 sw=2 et :
<commit_msg>TS-1251 Adding ink_port.h include since this relies on it.<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* cliAppInit.c --
*
*
* This file initiliazes the application by calling all
* the new commands and thier respective arguments
*
*
*
* Dated : 12/13/2000.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Not sure if we need to worry about old gcc compilers any more, but ... /leif
#if (__GNUC__ >= 3)
#include <iostream>
#else
#include <iostream.h>
#endif
//#include "tclExtend.h"
#include "tcl.h"
#include <unistd.h>
#include <sys/types.h>
#include "CliMgmtUtils.h"
#include "createCommand.h"
#include "hashtable.h"
#include "createArgument.h"
#include "definitions.h"
#include "ShowCmd.h"
#include "ConfigCmd.h"
#include "CliCreateCommands.h"
#include "ink_port.h"
#if HAVE_EDITLINE_READLINE_H
#include <editline/readline.h>
#elif HAVE_READLINE_READLINE_H
#include <readline/readline.h>
#if HAVE_READLINE_HISTORY_H
#include <readline/history.h>
#endif
#endif
Tcl_Interp *interp;
extern Tcl_HashTable CommandHashtable;
int
Tcl_AppInit(Tcl_Interp * app_interp)
{
/*
* Intialize the Tcl interpreter.
*/
if (Tcl_Init(app_interp) == TCL_ERROR)
return TCL_ERROR;
interp = app_interp;
#ifdef TCL_MEM_DEBUG
Tcl_InitMemory(interp);
#endif
cliCreateCommandHashtable();
// root users are automatically enabled
if (getuid() == 0) {
enable_restricted_commands = TRUE;
}
if (CliCreateCommands() != CLI_OK)
return CMD_ERROR;
Tcl_SetVar(interp, "tcl_rcFileName", "~/.tshellstartup", TCL_GLOBAL_ONLY);
/* Evaluating a application specific tcl script After creating
all the commands and sourcing the statup file */
/* Always this should be at the end of this function. */
/*
* Parse command-line arguments. A leading "-file" argument is
* ignored (a historical relic from the distant past). If the
* next argument doesn't start with a "-" then strip it off and
* use it as the name of a script file to process.
*/
const char *fileName = Tcl_GetVar(interp, "argv", TCL_LEAVE_ERR_MSG);
/*
* Invoke the script specified on the command line, if any.
*/
if (fileName[0] != '\0') {
int listArgc;
const char **listArgv;
if (Tcl_SplitList(interp, fileName, &listArgc, &listArgv) != TCL_OK) {
return TCL_ERROR;
}
int length = strlen(listArgv[0]);
if ((length >= 2) && (strncmp(listArgv[0], "-file", length) == 0)) {
for (int index = 1; index < listArgc; index++) {
Tcl_ResetResult(interp);
if (Tcl_EvalFile(interp, listArgv[index]) != TCL_OK) {
Tcl_AddErrorInfo(interp, "");
Tcl_DeleteInterp(interp);
Tcl_Exit(1);
}
}
}
ckfree((char *) listArgv);
}
Tcl_ResetResult(interp);
return TCL_OK;
}
#if HAVE_LIBREADLINE
// TCL main read, eval, print loop. We don't use Tcl_Main because we want to
// use readline to get line editing and command history.
void Tcl_ReadlineMain(void)
{
char * line;
for (;;) {
line = readline("trafficserver> ");
if (line == NULL) {
// Received EOF. Bound this into a TCL exit command just like Tcl_Main
// does.
Tcl_Eval(interp, "exit;");
}
if (*line) {
add_history(line);
Tcl_Eval(interp, line);
}
free(line);
}
exit(0);
}
#endif // HAVE_LIBREADLINE
// vim: set ts=2 sw=2 et :
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private slots:
void initTestCase();
void listKeys();
void listPlugins();
void listKeysForPlugin();
void typeForKey();
void docForKey();
void pluginForKey();
void keyExists();
void constructionStringForKey();
void keyProvided();
};
void InfoCdbBackendUnitTest::initTestCase()
{
// FIXME: LOCAL_DIR
CDBWriter writer("cache.cdb");
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
writer.add("Battery.Charging:KEYTYPE", "TRUTH");
writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
writer.close();
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoCdbBackendUnitTest::listKeysForPlugin()
{
QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
QCOMPARE(keys1.count(), 2);
QVERIFY(keys1.contains("Battery.Charging"));
QVERIFY(keys1.contains("Internet.BytesOut"));
QStringList keys2 = backend->listKeysForPlugin("non-existant");
QCOMPARE(keys2.count(), 0);
}
void InfoCdbBackendUnitTest::typeForKey()
{
QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::docForKey()
{
QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::pluginForKey()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));
QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyExists()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->keyExists(key), true);
QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
QCOMPARE(backend->keyExists("Battery.Charging"), true);
}
void InfoCdbBackendUnitTest::constructionStringForKey()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->constructionStringForKey(key) != QString());
QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyProvided()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->keyProvided(key) == true);
QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>databaseExists.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private slots:
void initTestCase();
void databaseExists();
void listKeys();
void listPlugins();
void listKeysForPlugin();
void typeForKey();
void docForKey();
void pluginForKey();
void keyExists();
void constructionStringForKey();
void keyProvided();
};
void InfoCdbBackendUnitTest::initTestCase()
{
// FIXME: LOCAL_DIR
CDBWriter writer("cache.cdb");
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
writer.add("Battery.Charging:KEYTYPE", "TRUTH");
writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
writer.close();
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::databaseExists()
{
QCOMPARE(backend->databaseExists(), true);
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoCdbBackendUnitTest::listKeysForPlugin()
{
QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
QCOMPARE(keys1.count(), 2);
QVERIFY(keys1.contains("Battery.Charging"));
QVERIFY(keys1.contains("Internet.BytesOut"));
QStringList keys2 = backend->listKeysForPlugin("non-existant");
QCOMPARE(keys2.count(), 0);
}
void InfoCdbBackendUnitTest::typeForKey()
{
QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::docForKey()
{
QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::pluginForKey()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));
QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyExists()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->keyExists(key), true);
QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
QCOMPARE(backend->keyExists("Battery.Charging"), true);
}
void InfoCdbBackendUnitTest::constructionStringForKey()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->constructionStringForKey(key) != QString());
QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyProvided()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->keyProvided(key) == true);
QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|> |
<commit_before>#include "libdialog.h"
#include <qfiledialog.h>
libraryDialog::libraryDialog(ssmp *parent, Qt::WFlags flags)
: QDialog(parent, flags)
{
myparent = parent;
ui.setupUi(this);
connect(ui.browseBtn,SIGNAL(clicked()),this,SLOT(getDir()));
if(parent->settings->value("libdir") != QVariant())
ui.libDirTxt->setText(parent->settings->value("libdir").toString());
}
void libraryDialog::getDir()
{
libdir = QFileDialog::getExistingDirectory(this, "Select Libdir",ui.libDirTxt->text(),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
ui.libDirTxt->setText(libdir);
}
void libraryDialog::accept()
{
myparent->settings->setValue("libdir", ui.libDirTxt->text());
ui.buttonBox->setDisabled(true);
addDir2Lib(ui.libDirTxt->text());
this->close();
}
//Adds dir & its contents to the library
void libraryDialog::addDir2Lib(QDir dir)
{
dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QDirIterator di(dir, QDirIterator::Subdirectories);
while(di.hasNext())
{
di.next();
QString fpath = di.filePath();
QFileInfo f = di.fileInfo();
if(isAudioFile(f))//Add this song to the database
{
TagLib::FileName fname = fpath.toStdString().c_str();
QMap<QString, QString> stmap;
QMap<QString, int> itmap;
TagLib::FileRef file = TagLib::FileRef(fname);
if(file.isNull())
continue; //TODO: Error out here
//MP3 Means we can check for additional info in ID3v2 tags
if(f.suffix() == "mp3")
{
TagLib::MPEG::File* fr = new TagLib::MPEG::File(fname);
if(fr->ID3v2Tag())
{
//Somehow this means album artist / band. http://www.id3.org/id3v2.4.0-frames
TagLib::ID3v2::FrameList l = fr->ID3v2Tag()->frameList("TPE2");
if(!l.isEmpty())
stmap["albumartist"] = l.front()->toString().toCString();
}
delete fr;
}
TagLib::Tag* genTag = file.tag();
stmap["name"] = genTag->title().toCString();
stmap["genre"] = genTag->genre().toCString();
itmap["year"] = genTag->year();
itmap["tracknum"] = genTag->track();
stmap["album"] = genTag->album().toCString();
stmap["artist"] = genTag->artist().toCString();
itmap["length"] = file.audioProperties()->length();
stmap["path"] = fpath;
//Add collected info to db
DBItem s;
s.strVals = stmap;
s.intVals = itmap;
myparent->dbi->addSong(s);
}
else if(f.isDir())
ui.curDirLbl->setText(fpath);
//if(top) //If we're the top level of recursion update prog bar
// ui.progressBar->setValue(di./siz * 100);
qApp->processEvents();
}
}
bool libraryDialog::isAudioFile(QFileInfo f)
{
QString type = f.suffix();
return std::accumulate(myparent->supportedFileFormats.begin(), myparent->supportedFileFormats.end(), false,
[type](bool a, std::string b) {return (a || b == type.toStdString());});
}
libraryDialog::~libraryDialog()
{
}
<commit_msg>Unicode was easy, turns out. Next: m4as break on file not null check<commit_after>#include "libdialog.h"
#include <qfiledialog.h>
libraryDialog::libraryDialog(ssmp *parent, Qt::WFlags flags)
: QDialog(parent, flags)
{
myparent = parent;
ui.setupUi(this);
connect(ui.browseBtn,SIGNAL(clicked()),this,SLOT(getDir()));
if(parent->settings->value("libdir") != QVariant())
ui.libDirTxt->setText(parent->settings->value("libdir").toString());
}
void libraryDialog::getDir()
{
libdir = QFileDialog::getExistingDirectory(this, "Select Libdir",ui.libDirTxt->text(),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
ui.libDirTxt->setText(libdir);
}
void libraryDialog::accept()
{
myparent->settings->setValue("libdir", ui.libDirTxt->text());
ui.buttonBox->setDisabled(true);
addDir2Lib(ui.libDirTxt->text());
this->close();
}
//Adds dir & its contents to the library
void libraryDialog::addDir2Lib(QDir dir)
{
dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QDirIterator di(dir, QDirIterator::Subdirectories);
while(di.hasNext())
{
di.next();
QString fpath = di.filePath();
QFileInfo f = di.fileInfo();
if(isAudioFile(f))//Add this song to the database
{
wchar_t wname[200]; //TODO: Better way than static?
wname[fpath.toWCharArray(wname)] = 0;
TagLib::FileName fname(wname);
QMap<QString, QString> stmap;
QMap<QString, int> itmap;
TagLib::FileRef file = TagLib::FileRef(fname);
if(file.isNull())
continue; //TODO: Error out here
//MP3 Means we can check for additional info in ID3v2 tags
if(f.suffix() == "mp3")
{
TagLib::MPEG::File* fr = new TagLib::MPEG::File(fname);
if(fr->ID3v2Tag())
{
//Somehow this means album artist / band. http://www.id3.org/id3v2.4.0-frames
TagLib::ID3v2::FrameList l = fr->ID3v2Tag()->frameList("TPE2");
if(!l.isEmpty())
stmap["albumartist"] = l.front()->toString().toCString();
}
delete fr;
}
TagLib::Tag* genTag = file.tag();
stmap["name"] = genTag->title().toCString();
stmap["genre"] = genTag->genre().toCString();
itmap["year"] = genTag->year();
itmap["tracknum"] = genTag->track();
stmap["album"] = genTag->album().toCString();
stmap["artist"] = genTag->artist().toCString();
itmap["length"] = file.audioProperties()->length();
stmap["path"] = fpath;
//Add collected info to db
DBItem s;
s.strVals = stmap;
s.intVals = itmap;
myparent->dbi->addSong(s);
}
else if(f.isDir())
ui.curDirLbl->setText(fpath);
//if(top) //If we're the top level of recursion update prog bar
// ui.progressBar->setValue(di./siz * 100);
qApp->processEvents();
}
}
bool libraryDialog::isAudioFile(QFileInfo f)
{
QString type = f.suffix();
return std::accumulate(myparent->supportedFileFormats.begin(), myparent->supportedFileFormats.end(), false,
[type](bool a, std::string b) {return (a || b == type.toStdString());});
}
libraryDialog::~libraryDialog()
{
}
<|endoftext|> |
<commit_before>#include "StaticLibrary.h"
#include <fstream>
#include <stdio.h>
#include "Error.h"
namespace Halide {
namespace Internal {
namespace {
std::string pad_right(std::string s, size_t max) {
internal_assert(s.size() <= max) << s.size() << " " << s;
while (s.size() < max) {
s += " ";
}
return s;
}
std::string decimal_string(int value, size_t pad) {
return pad_right(std::to_string(value), pad);
}
std::string octal_string(int value, size_t pad) {
char buf[256];
#ifdef _MSC_VER
_snprintf(buf, sizeof(buf), "%o", value);
#else
snprintf(buf, sizeof(buf), "%o", value);
#endif
return pad_right(buf, pad);
}
} // namespace
void create_ar_file(const std::vector<std::string> &src_files,
const std::string &dst_file, bool deterministic) {
std::ofstream ar(dst_file, std::ofstream::out | std::ofstream::binary);
user_assert(ar.good());
ar << "!<arch>\x0A";
for (const std::string &src_path : src_files) {
FileStat stat = file_stat(src_path);
// Each member must begin on an even byte boundary; insert LF as needed
if (ar.tellp() & 1) {
ar << "\x0A";
}
// Need to embed just the leaf name
std::string src_name = base_name(src_path, '/');
uint64_t filesize = stat.file_size;
if (src_name.size() > 16) {
ar << "#1/" << decimal_string(src_name.size(), 13);
filesize += src_name.size();
} else {
ar << pad_right(src_name, 16);
}
ar << decimal_string(deterministic ? 0 : stat.mod_time, 12); // mod time
ar << decimal_string(deterministic ? 0 : stat.uid, 6); // user id
ar << decimal_string(deterministic ? 0 : stat.gid, 6); // group id
ar << octal_string(deterministic ? 0644 : stat.mode, 8); // mode
ar << decimal_string(filesize, 10); // filesize
ar << "\x60\x0A"; // magic
if (src_name.size() > 16) {
ar << src_name;
}
{
std::ifstream src(src_path, std::ifstream::in | std::ifstream::binary);
ar << src.rdbuf();
}
}
}
void static_library_test() {
{
std::ofstream a("a.tmp", std::ofstream::out);
a << "a123b";
user_assert(a.good());
}
{
std::ofstream b("b_long_name_is_long.tmp", std::ofstream::out);
b << "c456d";
user_assert(b.good());
}
{
std::ofstream c("./c_path.tmp", std::ofstream::out);
c << "e789f";
user_assert(c.good());
}
create_ar_file({"a.tmp", "b_long_name_is_long.tmp", "./c_path.tmp"}, "arfile.a");
{
std::ifstream ar("arfile.a", std::ifstream::in);
std::ostringstream actual;
actual << ar.rdbuf();
const std::string expected = R"literal(!<arch>
a.tmp 0 0 0 644 5 `
a123b
#1/23 0 0 0 644 28 `
b_long_name_is_long.tmpc456dc_path.tmp 0 0 0 644 5 `
e789f)literal";
internal_assert(actual.str() == expected)
<< "File contents wrong, expected:(" << expected << ")\nactual:(" << actual.str() << ")\n";
}
file_unlink("a.tmp");
file_unlink("b_long_name_is_long.tmp");
file_unlink("./c_path.tmp");
file_unlink("arfile.a");
debug(0) << "static_library_test passed\n";
}
} // namespace Internal
} // namespace Halide
<commit_msg>Move assert to end<commit_after>#include "StaticLibrary.h"
#include <fstream>
#include <stdio.h>
#include "Error.h"
namespace Halide {
namespace Internal {
namespace {
std::string pad_right(std::string s, size_t max) {
internal_assert(s.size() <= max) << s.size() << " " << s;
while (s.size() < max) {
s += " ";
}
return s;
}
std::string decimal_string(int value, size_t pad) {
return pad_right(std::to_string(value), pad);
}
std::string octal_string(int value, size_t pad) {
char buf[256];
#ifdef _MSC_VER
_snprintf(buf, sizeof(buf), "%o", value);
#else
snprintf(buf, sizeof(buf), "%o", value);
#endif
return pad_right(buf, pad);
}
} // namespace
void create_ar_file(const std::vector<std::string> &src_files,
const std::string &dst_file, bool deterministic) {
std::ofstream ar(dst_file, std::ofstream::out | std::ofstream::binary);
ar << "!<arch>\x0A";
for (const std::string &src_path : src_files) {
FileStat stat = file_stat(src_path);
// Each member must begin on an even byte boundary; insert LF as needed
if (ar.tellp() & 1) {
ar << "\x0A";
}
// Need to embed just the leaf name
std::string src_name = base_name(src_path, '/');
uint64_t filesize = stat.file_size;
if (src_name.size() > 16) {
ar << "#1/" << decimal_string(src_name.size(), 13);
filesize += src_name.size();
} else {
ar << pad_right(src_name, 16);
}
ar << decimal_string(deterministic ? 0 : stat.mod_time, 12); // mod time
ar << decimal_string(deterministic ? 0 : stat.uid, 6); // user id
ar << decimal_string(deterministic ? 0 : stat.gid, 6); // group id
ar << octal_string(deterministic ? 0644 : stat.mode, 8); // mode
ar << decimal_string(filesize, 10); // filesize
ar << "\x60\x0A"; // magic
if (src_name.size() > 16) {
ar << src_name;
}
{
std::ifstream src(src_path, std::ifstream::in | std::ifstream::binary);
ar << src.rdbuf();
}
}
user_assert(ar.good());
}
void static_library_test() {
{
std::ofstream a("a.tmp", std::ofstream::out);
a << "a123b";
user_assert(a.good());
}
{
std::ofstream b("b_long_name_is_long.tmp", std::ofstream::out);
b << "c456d";
user_assert(b.good());
}
{
std::ofstream c("./c_path.tmp", std::ofstream::out);
c << "e789f";
user_assert(c.good());
}
create_ar_file({"a.tmp", "b_long_name_is_long.tmp", "./c_path.tmp"}, "arfile.a");
{
std::ifstream ar("arfile.a", std::ifstream::in);
std::ostringstream actual;
actual << ar.rdbuf();
const std::string expected = R"literal(!<arch>
a.tmp 0 0 0 644 5 `
a123b
#1/23 0 0 0 644 28 `
b_long_name_is_long.tmpc456dc_path.tmp 0 0 0 644 5 `
e789f)literal";
internal_assert(actual.str() == expected)
<< "File contents wrong, expected:(" << expected << ")\nactual:(" << actual.str() << ")\n";
}
file_unlink("a.tmp");
file_unlink("b_long_name_is_long.tmp");
file_unlink("./c_path.tmp");
file_unlink("arfile.a");
debug(0) << "static_library_test passed\n";
}
} // namespace Internal
} // namespace Halide
<|endoftext|> |
<commit_before>// SciTE - Scintilla based Text Editor
/** @file StringHelpers.cxx
** Implementation of widely useful string functions.
**/
// Copyright 2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include <string>
#include <vector>
#include "Scintilla.h"
#include "GUI.h"
//~ #include "SString.h"
#include "StringHelpers.h"
bool StartsWith(GUI::gui_string const &s, GUI::gui_string const &start) {
return (s.size() >= start.size()) &&
(std::equal(s.begin(), s.begin() + start.size(), start.begin()));
}
bool EndsWith(GUI::gui_string const &s, GUI::gui_string const &end) {
return (s.size() >= end.size()) &&
(std::equal(s.begin() + s.size() - end.size(), s.end(), end.begin()));
}
int Substitute(GUI::gui_string &s, const GUI::gui_string &sFind, const GUI::gui_string &sReplace) {
int c = 0;
size_t lenFind = sFind.size();
size_t lenReplace = sReplace.size();
size_t posFound = s.find(sFind);
while (posFound != GUI::gui_string::npos) {
s.replace(posFound, lenFind, sReplace);
posFound = s.find(sFind, posFound + lenReplace);
c++;
}
return c;
}
/**
* Convert a string into C string literal form using \a, \b, \f, \n, \r, \t, \v, and \ooo.
* The return value is a newly allocated character array containing the result.
* 4 bytes are allocated for each byte of the input because that is the maximum
* expansion needed when all of the input needs to be output using the octal form.
* The return value should be deleted with delete[].
*/
char *Slash(const char *s, bool quoteQuotes) {
char *oRet = new char[strlen(s) * 4 + 1];
char *o = oRet;
while (*s) {
if (*s == '\a') {
*o++ = '\\';
*o++ = 'a';
} else if (*s == '\b') {
*o++ = '\\';
*o++ = 'b';
} else if (*s == '\f') {
*o++ = '\\';
*o++ = 'f';
} else if (*s == '\n') {
*o++ = '\\';
*o++ = 'n';
} else if (*s == '\r') {
*o++ = '\\';
*o++ = 'r';
} else if (*s == '\t') {
*o++ = '\\';
*o++ = 't';
} else if (*s == '\v') {
*o++ = '\\';
*o++ = 'v';
} else if (*s == '\\') {
*o++ = '\\';
*o++ = '\\';
} else if (quoteQuotes && (*s == '\'')) {
*o++ = '\\';
*o++ = '\'';
} else if (quoteQuotes && (*s == '\"')) {
*o++ = '\\';
*o++ = '\"';
} else if (isascii(*s) && (*s < ' ')) {
*o++ = '\\';
*o++ = static_cast<char>((*s >> 6) + '0');
*o++ = static_cast<char>((*s >> 3) + '0');
*o++ = static_cast<char>((*s & 0x7) + '0');
} else {
*o++ = *s;
}
s++;
}
*o = '\0';
return oRet;
}
/**
* Is the character an octal digit?
*/
static bool IsOctalDigit(char ch) {
return ch >= '0' && ch <= '7';
}
/**
* If the character is an hexa digit, get its value.
*/
static int GetHexaDigit(char ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
}
return -1;
}
/**
* Convert C style \a, \b, \f, \n, \r, \t, \v, \ooo and \xhh into their indicated characters.
*/
unsigned int UnSlash(char *s) {
char *sStart = s;
char *o = s;
while (*s) {
if (*s == '\\') {
s++;
if (*s == 'a') {
*o = '\a';
} else if (*s == 'b') {
*o = '\b';
} else if (*s == 'f') {
*o = '\f';
} else if (*s == 'n') {
*o = '\n';
} else if (*s == 'r') {
*o = '\r';
} else if (*s == 't') {
*o = '\t';
} else if (*s == 'v') {
*o = '\v';
} else if (IsOctalDigit(*s)) {
int val = *s - '0';
if (IsOctalDigit(*(s + 1))) {
s++;
val *= 8;
val += *s - '0';
if (IsOctalDigit(*(s + 1))) {
s++;
val *= 8;
val += *s - '0';
}
}
*o = static_cast<char>(val);
} else if (*s == 'x') {
s++;
int val = 0;
int ghd = GetHexaDigit(*s);
if (ghd >= 0) {
s++;
val = ghd;
ghd = GetHexaDigit(*s);
if (ghd >= 0) {
s++;
val *= 16;
val += ghd;
}
}
*o = static_cast<char>(val);
} else {
*o = *s;
}
} else {
*o = *s;
}
o++;
if (*s) {
s++;
}
}
*o = '\0';
return o - sStart;
}
/**
* Convert C style \0oo into their indicated characters.
* This is used to get control characters into the regular expresion engine.
*/
unsigned int UnSlashLowOctal(char *s) {
char *sStart = s;
char *o = s;
while (*s) {
if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigit(s[2]) && IsOctalDigit(s[3])) {
*o = static_cast<char>(8 * (s[2] - '0') + (s[3] - '0'));
s += 3;
} else {
*o = *s;
}
o++;
if (*s)
s++;
}
*o = '\0';
return o - sStart;
}
<commit_msg>Removed dead code.<commit_after>// SciTE - Scintilla based Text Editor
/** @file StringHelpers.cxx
** Implementation of widely useful string functions.
**/
// Copyright 2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include <string>
#include <vector>
#include "Scintilla.h"
#include "GUI.h"
#include "StringHelpers.h"
bool StartsWith(GUI::gui_string const &s, GUI::gui_string const &start) {
return (s.size() >= start.size()) &&
(std::equal(s.begin(), s.begin() + start.size(), start.begin()));
}
bool EndsWith(GUI::gui_string const &s, GUI::gui_string const &end) {
return (s.size() >= end.size()) &&
(std::equal(s.begin() + s.size() - end.size(), s.end(), end.begin()));
}
int Substitute(GUI::gui_string &s, const GUI::gui_string &sFind, const GUI::gui_string &sReplace) {
int c = 0;
size_t lenFind = sFind.size();
size_t lenReplace = sReplace.size();
size_t posFound = s.find(sFind);
while (posFound != GUI::gui_string::npos) {
s.replace(posFound, lenFind, sReplace);
posFound = s.find(sFind, posFound + lenReplace);
c++;
}
return c;
}
/**
* Convert a string into C string literal form using \a, \b, \f, \n, \r, \t, \v, and \ooo.
* The return value is a newly allocated character array containing the result.
* 4 bytes are allocated for each byte of the input because that is the maximum
* expansion needed when all of the input needs to be output using the octal form.
* The return value should be deleted with delete[].
*/
char *Slash(const char *s, bool quoteQuotes) {
char *oRet = new char[strlen(s) * 4 + 1];
char *o = oRet;
while (*s) {
if (*s == '\a') {
*o++ = '\\';
*o++ = 'a';
} else if (*s == '\b') {
*o++ = '\\';
*o++ = 'b';
} else if (*s == '\f') {
*o++ = '\\';
*o++ = 'f';
} else if (*s == '\n') {
*o++ = '\\';
*o++ = 'n';
} else if (*s == '\r') {
*o++ = '\\';
*o++ = 'r';
} else if (*s == '\t') {
*o++ = '\\';
*o++ = 't';
} else if (*s == '\v') {
*o++ = '\\';
*o++ = 'v';
} else if (*s == '\\') {
*o++ = '\\';
*o++ = '\\';
} else if (quoteQuotes && (*s == '\'')) {
*o++ = '\\';
*o++ = '\'';
} else if (quoteQuotes && (*s == '\"')) {
*o++ = '\\';
*o++ = '\"';
} else if (isascii(*s) && (*s < ' ')) {
*o++ = '\\';
*o++ = static_cast<char>((*s >> 6) + '0');
*o++ = static_cast<char>((*s >> 3) + '0');
*o++ = static_cast<char>((*s & 0x7) + '0');
} else {
*o++ = *s;
}
s++;
}
*o = '\0';
return oRet;
}
/**
* Is the character an octal digit?
*/
static bool IsOctalDigit(char ch) {
return ch >= '0' && ch <= '7';
}
/**
* If the character is an hexa digit, get its value.
*/
static int GetHexaDigit(char ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
}
return -1;
}
/**
* Convert C style \a, \b, \f, \n, \r, \t, \v, \ooo and \xhh into their indicated characters.
*/
unsigned int UnSlash(char *s) {
char *sStart = s;
char *o = s;
while (*s) {
if (*s == '\\') {
s++;
if (*s == 'a') {
*o = '\a';
} else if (*s == 'b') {
*o = '\b';
} else if (*s == 'f') {
*o = '\f';
} else if (*s == 'n') {
*o = '\n';
} else if (*s == 'r') {
*o = '\r';
} else if (*s == 't') {
*o = '\t';
} else if (*s == 'v') {
*o = '\v';
} else if (IsOctalDigit(*s)) {
int val = *s - '0';
if (IsOctalDigit(*(s + 1))) {
s++;
val *= 8;
val += *s - '0';
if (IsOctalDigit(*(s + 1))) {
s++;
val *= 8;
val += *s - '0';
}
}
*o = static_cast<char>(val);
} else if (*s == 'x') {
s++;
int val = 0;
int ghd = GetHexaDigit(*s);
if (ghd >= 0) {
s++;
val = ghd;
ghd = GetHexaDigit(*s);
if (ghd >= 0) {
s++;
val *= 16;
val += ghd;
}
}
*o = static_cast<char>(val);
} else {
*o = *s;
}
} else {
*o = *s;
}
o++;
if (*s) {
s++;
}
}
*o = '\0';
return o - sStart;
}
/**
* Convert C style \0oo into their indicated characters.
* This is used to get control characters into the regular expresion engine.
*/
unsigned int UnSlashLowOctal(char *s) {
char *sStart = s;
char *o = s;
while (*s) {
if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigit(s[2]) && IsOctalDigit(s[3])) {
*o = static_cast<char>(8 * (s[2] - '0') + (s[3] - '0'));
s += 3;
} else {
*o = *s;
}
o++;
if (*s)
s++;
}
*o = '\0';
return o - sStart;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 author 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 "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/xml_parse.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
using boost::bind;
using namespace libtorrent;
address_v4 lsd::lsd_multicast_address;
udp::endpoint lsd::lsd_multicast_endpoint;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios)
, m_broadcast_timer(ios)
, m_disabled(false)
{
// Bittorrent Local discovery multicast address and port
lsd_multicast_address = address_v4::from_string("239.192.152.143");
lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771);
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
assert(lsd_multicast_address.is_multicast());
rebind(listen_interface);
}
lsd::~lsd() {}
void lsd::rebind(address const& listen_interface)
{
address_v4 local_ip;
if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0"))
{
local_ip = listen_interface.to_v4();
}
else
{
// make a best guess of the interface we're using and its IP
udp::resolver r(m_socket.io_service());
udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0"));
for (;i != udp::resolver_iterator(); ++i)
{
if (i->endpoint().address().is_v4()) break;
}
if (i == udp::resolver_iterator())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "local host name did not resolve to an IPv4 address. "
"disabling local service discovery" << std::endl;
#endif
m_disabled = true;
return;
}
local_ip = i->endpoint().address().to_v4();
}
try
{
// the local interface hasn't changed
if (m_socket.is_open()
&& m_socket.local_endpoint().address() == local_ip)
return;
m_socket.close();
using namespace asio::ip::multicast;
m_socket.open(udp::v4());
m_socket.set_option(datagram_socket::reuse_address(true));
m_socket.bind(udp::endpoint(local_ip, 6771));
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "local ip: " << local_ip << std::endl;
#endif
m_socket.set_option(join_group(lsd_multicast_address));
m_socket.set_option(outbound_interface(address_v4()));
m_socket.set_option(enable_loopback(false));
m_socket.set_option(hops(255));
}
catch (std::exception& e)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "socket multicast error " << e.what()
<< ". disabling local service discovery" << std::endl;
#endif
m_disabled = true;
return;
}
m_disabled = false;
setup_receive();
}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << listen_port << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 0;
asio::error_code ec;
m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1)
, lsd_multicast_endpoint, ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
m_socket.send_to(asio::buffer(msg, msg.size() - 1)
, lsd_multicast_endpoint);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(asio::error_code const& e
, std::size_t bytes_transferred)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== on_announce" << std::endl;
#endif
using namespace libtorrent::detail;
if (e) return;
char* p = m_receive_buffer;
char* end = m_receive_buffer + bytes_transferred;
char* line = std::find(p, end, '\n');
for (char* i = p; i < line; ++i) *i = std::tolower(*i);
if (line == end || std::strcmp("bt-search", p))
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== Got incorrect method in announce" << std::string(p, line) << std::endl;
#endif
setup_receive();
return;
}
p = line + 1;
int port = 0;
sha1_hash ih(0);
while (p != end)
{
line = std::find(p, end, '\n');
if (line == end) break;
*line = 0;
for (char* i = p; i < line; ++i) *i = std::tolower(*i);
if (!strcmp(p, "port:"))
{
port = atoi(p + 5);
}
else if (!strcmp(p, "infohash:"))
{
ih = boost::lexical_cast<sha1_hash>(p + 9);
}
p = line + 1;
}
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== Got incoming local announce " << m_remote.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(m_remote.address(), port), ih); }
catch (std::exception&) {}
}
setup_receive();
}
void lsd::setup_receive() try
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** setup_receive" << std::endl;
#endif
assert(m_socket.is_open());
m_socket.async_receive_from(asio::buffer(m_receive_buffer
, sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2));
}
catch (std::exception&)
{}
void lsd::close()
{
m_socket.close();
}
<commit_msg>fixed typo in last check in<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 author 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 "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/xml_parse.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
using boost::bind;
using namespace libtorrent;
address_v4 lsd::lsd_multicast_address;
udp::endpoint lsd::lsd_multicast_endpoint;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios)
, m_broadcast_timer(ios)
, m_disabled(false)
{
// Bittorrent Local discovery multicast address and port
lsd_multicast_address = address_v4::from_string("239.192.152.143");
lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771);
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
assert(lsd_multicast_address.is_multicast());
rebind(listen_interface);
}
lsd::~lsd() {}
void lsd::rebind(address const& listen_interface)
{
address_v4 local_ip;
if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0"))
{
local_ip = listen_interface.to_v4();
}
else
{
// make a best guess of the interface we're using and its IP
udp::resolver r(m_socket.io_service());
udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0"));
for (;i != udp::resolver_iterator(); ++i)
{
if (i->endpoint().address().is_v4()) break;
}
if (i == udp::resolver_iterator())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "local host name did not resolve to an IPv4 address. "
"disabling local service discovery" << std::endl;
#endif
m_disabled = true;
return;
}
local_ip = i->endpoint().address().to_v4();
}
try
{
// the local interface hasn't changed
if (m_socket.is_open()
&& m_socket.local_endpoint().address() == local_ip)
return;
m_socket.close();
using namespace asio::ip::multicast;
m_socket.open(udp::v4());
m_socket.set_option(datagram_socket::reuse_address(true));
m_socket.bind(udp::endpoint(local_ip, 6771));
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "local ip: " << local_ip << std::endl;
#endif
m_socket.set_option(join_group(lsd_multicast_address));
m_socket.set_option(outbound_interface(address_v4()));
m_socket.set_option(enable_loopback(false));
m_socket.set_option(hops(255));
}
catch (std::exception& e)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "socket multicast error " << e.what()
<< ". disabling local service discovery" << std::endl;
#endif
m_disabled = true;
return;
}
m_disabled = false;
setup_receive();
}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << listen_port << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 0;
asio::error_code ec;
m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1)
, lsd_multicast_endpoint, 0, ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
m_socket.send_to(asio::buffer(msg, msg.size() - 1)
, lsd_multicast_endpoint);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(asio::error_code const& e
, std::size_t bytes_transferred)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== on_announce" << std::endl;
#endif
using namespace libtorrent::detail;
if (e) return;
char* p = m_receive_buffer;
char* end = m_receive_buffer + bytes_transferred;
char* line = std::find(p, end, '\n');
for (char* i = p; i < line; ++i) *i = std::tolower(*i);
if (line == end || std::strcmp("bt-search", p))
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== Got incorrect method in announce" << std::string(p, line) << std::endl;
#endif
setup_receive();
return;
}
p = line + 1;
int port = 0;
sha1_hash ih(0);
while (p != end)
{
line = std::find(p, end, '\n');
if (line == end) break;
*line = 0;
for (char* i = p; i < line; ++i) *i = std::tolower(*i);
if (!strcmp(p, "port:"))
{
port = atoi(p + 5);
}
else if (!strcmp(p, "infohash:"))
{
ih = boost::lexical_cast<sha1_hash>(p + 9);
}
p = line + 1;
}
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== Got incoming local announce " << m_remote.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(m_remote.address(), port), ih); }
catch (std::exception&) {}
}
setup_receive();
}
void lsd::setup_receive() try
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** setup_receive" << std::endl;
#endif
assert(m_socket.is_open());
m_socket.async_receive_from(asio::buffer(m_receive_buffer
, sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2));
}
catch (std::exception&)
{}
void lsd::close()
{
m_socket.close();
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include <openssl/obj_mac.h>
#include "eckey.h"
using namespace v8;
void InitCurves(Handle<Object> exports) {
Local<Object> obj = Object::New();
obj->Set(NanNew<String>("secp112r1"), NanNew<Number>(NID_secp112r1));
obj->Set(NanNew<String>("secp112r2"), NanNew<Number>(NID_secp112r2));
obj->Set(NanNew<String>("secp128r1"), NanNew<Number>(NID_secp128r1));
obj->Set(NanNew<String>("secp128r2"), NanNew<Number>(NID_secp128r2));
obj->Set(NanNew<String>("secp160k1"), NanNew<Number>(NID_secp160k1));
obj->Set(NanNew<String>("secp160r1"), NanNew<Number>(NID_secp160r1));
obj->Set(NanNew<String>("secp160r2"), NanNew<Number>(NID_secp160r2));
obj->Set(NanNew<String>("secp192r1"), NanNew<Number>(NID_X9_62_prime192v1));
obj->Set(NanNew<String>("secp192k1"), NanNew<Number>(NID_secp192k1));
obj->Set(NanNew<String>("secp224k1"), NanNew<Number>(NID_secp224k1));
obj->Set(NanNew<String>("secp224r1"), NanNew<Number>(NID_secp224r1));
obj->Set(NanNew<String>("secp256r1"), NanNew<Number>(NID_X9_62_prime256v1));
obj->Set(NanNew<String>("secp256k1"), NanNew<Number>(NID_secp256k1));
obj->Set(NanNew<String>("secp384r1"), NanNew<Number>(NID_secp384r1));
obj->Set(NanNew<String>("secp521r1"), NanNew<Number>(NID_secp521r1));
obj->Set(NanNew<String>("sect113r1"), NanNew<Number>(NID_sect113r1));
obj->Set(NanNew<String>("sect113r2"), NanNew<Number>(NID_sect113r2));
obj->Set(NanNew<String>("sect131r1"), NanNew<Number>(NID_sect131r1));
obj->Set(NanNew<String>("sect131r2"), NanNew<Number>(NID_sect131r2));
obj->Set(NanNew<String>("sect163k1"), NanNew<Number>(NID_sect163k1));
obj->Set(NanNew<String>("sect163r1"), NanNew<Number>(NID_sect163r1));
obj->Set(NanNew<String>("sect163r2"), NanNew<Number>(NID_sect163r2));
obj->Set(NanNew<String>("sect193r1"), NanNew<Number>(NID_sect193r1));
obj->Set(NanNew<String>("sect193r2"), NanNew<Number>(NID_sect193r2));
obj->Set(NanNew<String>("sect233k1"), NanNew<Number>(NID_sect233k1));
obj->Set(NanNew<String>("sect233r1"), NanNew<Number>(NID_sect233r1));
obj->Set(NanNew<String>("sect239k1"), NanNew<Number>(NID_sect239k1));
obj->Set(NanNew<String>("sect283k1"), NanNew<Number>(NID_sect283k1));
obj->Set(NanNew<String>("sect283r1"), NanNew<Number>(NID_sect283r1));
obj->Set(NanNew<String>("sect409k1"), NanNew<Number>(NID_sect409k1));
obj->Set(NanNew<String>("sect409r1"), NanNew<Number>(NID_sect409r1));
obj->Set(NanNew<String>("sect571k1"), NanNew<Number>(NID_sect571k1));
obj->Set(NanNew<String>("sect571r1"), NanNew<Number>(NID_sect571r1));
// Intimidated? Can't go wrong with NIST recommended curves
obj->Set(NanNew<String>("nistp192"), NanNew<Number>(NID_X9_62_prime192v1));
obj->Set(NanNew<String>("nistp224"), NanNew<Number>(NID_secp224r1));
obj->Set(NanNew<String>("nistp256"), NanNew<Number>(NID_X9_62_prime256v1));
obj->Set(NanNew<String>("nistp384"), NanNew<Number>(NID_secp384r1));
obj->Set(NanNew<String>("nistp521"), NanNew<Number>(NID_secp521r1));
exports->Set(NanNew<String>("ECCurves"), obj);
}
void InitModule(Handle<Object> exports) {
ECKey::Init(exports);
InitCurves(exports);
}
NODE_MODULE(native, InitModule)
<commit_msg>Use NanNew<Object> for Object::New<commit_after>#include <node.h>
#include <nan.h>
#include <openssl/obj_mac.h>
#include "eckey.h"
using namespace v8;
void InitCurves(Handle<Object> exports) {
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("secp112r1"), NanNew<Number>(NID_secp112r1));
obj->Set(NanNew<String>("secp112r2"), NanNew<Number>(NID_secp112r2));
obj->Set(NanNew<String>("secp128r1"), NanNew<Number>(NID_secp128r1));
obj->Set(NanNew<String>("secp128r2"), NanNew<Number>(NID_secp128r2));
obj->Set(NanNew<String>("secp160k1"), NanNew<Number>(NID_secp160k1));
obj->Set(NanNew<String>("secp160r1"), NanNew<Number>(NID_secp160r1));
obj->Set(NanNew<String>("secp160r2"), NanNew<Number>(NID_secp160r2));
obj->Set(NanNew<String>("secp192r1"), NanNew<Number>(NID_X9_62_prime192v1));
obj->Set(NanNew<String>("secp192k1"), NanNew<Number>(NID_secp192k1));
obj->Set(NanNew<String>("secp224k1"), NanNew<Number>(NID_secp224k1));
obj->Set(NanNew<String>("secp224r1"), NanNew<Number>(NID_secp224r1));
obj->Set(NanNew<String>("secp256r1"), NanNew<Number>(NID_X9_62_prime256v1));
obj->Set(NanNew<String>("secp256k1"), NanNew<Number>(NID_secp256k1));
obj->Set(NanNew<String>("secp384r1"), NanNew<Number>(NID_secp384r1));
obj->Set(NanNew<String>("secp521r1"), NanNew<Number>(NID_secp521r1));
obj->Set(NanNew<String>("sect113r1"), NanNew<Number>(NID_sect113r1));
obj->Set(NanNew<String>("sect113r2"), NanNew<Number>(NID_sect113r2));
obj->Set(NanNew<String>("sect131r1"), NanNew<Number>(NID_sect131r1));
obj->Set(NanNew<String>("sect131r2"), NanNew<Number>(NID_sect131r2));
obj->Set(NanNew<String>("sect163k1"), NanNew<Number>(NID_sect163k1));
obj->Set(NanNew<String>("sect163r1"), NanNew<Number>(NID_sect163r1));
obj->Set(NanNew<String>("sect163r2"), NanNew<Number>(NID_sect163r2));
obj->Set(NanNew<String>("sect193r1"), NanNew<Number>(NID_sect193r1));
obj->Set(NanNew<String>("sect193r2"), NanNew<Number>(NID_sect193r2));
obj->Set(NanNew<String>("sect233k1"), NanNew<Number>(NID_sect233k1));
obj->Set(NanNew<String>("sect233r1"), NanNew<Number>(NID_sect233r1));
obj->Set(NanNew<String>("sect239k1"), NanNew<Number>(NID_sect239k1));
obj->Set(NanNew<String>("sect283k1"), NanNew<Number>(NID_sect283k1));
obj->Set(NanNew<String>("sect283r1"), NanNew<Number>(NID_sect283r1));
obj->Set(NanNew<String>("sect409k1"), NanNew<Number>(NID_sect409k1));
obj->Set(NanNew<String>("sect409r1"), NanNew<Number>(NID_sect409r1));
obj->Set(NanNew<String>("sect571k1"), NanNew<Number>(NID_sect571k1));
obj->Set(NanNew<String>("sect571r1"), NanNew<Number>(NID_sect571r1));
// Intimidated? Can't go wrong with NIST recommended curves
obj->Set(NanNew<String>("nistp192"), NanNew<Number>(NID_X9_62_prime192v1));
obj->Set(NanNew<String>("nistp224"), NanNew<Number>(NID_secp224r1));
obj->Set(NanNew<String>("nistp256"), NanNew<Number>(NID_X9_62_prime256v1));
obj->Set(NanNew<String>("nistp384"), NanNew<Number>(NID_secp384r1));
obj->Set(NanNew<String>("nistp521"), NanNew<Number>(NID_secp521r1));
exports->Set(NanNew<String>("ECCurves"), obj);
}
void InitModule(Handle<Object> exports) {
ECKey::Init(exports);
InitCurves(exports);
}
NODE_MODULE(native, InitModule)
<|endoftext|> |
<commit_before>/**
* @file main.cc
* @author Rafal Slota
* @copyright (C) 2016 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef linux
/* For pread()/pwrite()/utimensat() */
#define _XOPEN_SOURCE 700
#endif
#include "asio.hpp"
#include "auth/authException.h"
#include "auth/authManager.h"
#include "communication/exception.h"
#include "context.h"
#include "fsOperations.h"
#include "fslogic/composite.h"
#include "fuseOperations.h"
#include "helpers/init.h"
#include "logging.h"
#include "messages/configuration.h"
#include "messages/getConfiguration.h"
#include "messages/handshakeResponse.h"
#include "monitoring/monitoring.h"
#include "monitoring/monitoringConfiguration.h"
#include "options/options.h"
#include "scheduler.h"
#include "scopeExit.h"
#include "version.h"
#include <folly/Singleton.h>
#include <fuse/fuse_lowlevel.h>
#include <fuse/fuse_opt.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <exception>
#include <future>
#include <iostream>
#include <memory>
#include <random>
#include <regex>
#include <string>
#if !defined(NDEBUG)
/**
* We have to expose FLAGS_vmodule variable here, as it is not declared
* publicly by Glog library.
*/
DECLARE_string(vmodule);
#endif
using namespace one;
using namespace one::client;
using namespace one::monitoring;
void startLogging(
const char *programName, std::shared_ptr<options::Options> options)
{
try {
boost::filesystem::create_directories(options->getLogDirPath());
}
catch (const boost::filesystem::filesystem_error &e) {
std::cerr << "Failed to create log directory: '" << e.what()
<< "'. Aborting..." << std::endl;
}
FLAGS_minloglevel = 0;
FLAGS_logtostderr = false;
FLAGS_stderrthreshold = options->getDebug() ? 0 : 2;
FLAGS_log_dir = options->getLogDirPath().c_str();
FLAGS_stop_logging_if_full_disk = true;
#if !defined(NDEBUG)
FLAGS_v = options->getVerboseLogLevel();
FLAGS_vmodule = options->getVerboseLogFilter()
? options->getVerboseLogFilter().get()
: "*";
#endif
google::InitGoogleLogging(programName);
if (options->getProviderHost())
LOG(INFO) << "Connecting to Oneprovider: "
<< options->getProviderHost().get();
LOG(INFO) << "Forced direct io: " << options->isDirectIOForced();
LOG(INFO) << "Forced proxy io: " << options->isDirectIOForced();
LOG(INFO) << "Verify service certificate: " << options->isInsecure();
LOG(INFO) << "File read events disabled: "
<< options->areFileReadEventsDisabled();
LOG(INFO) << "Is IO buffered: " << options->isIOBuffered();
LOG(INFO) << "Oneprovider connection timeout [s]: "
<< options->getProviderTimeout().count();
LOG(INFO) << "Is monitoring enabled: " << options->isMonitoringEnabled();
if (options->getMonitoringType())
LOG(INFO) << "Monitoring type: " << options->getMonitoringType().get();
LOG(INFO) << "Is monitoring level basic: "
<< options->isMonitoringLevelBasic();
LOG(INFO) << "Is monitoring level full: "
<< options->isMonitoringLevelFull();
if (options->getMonitoringGraphiteUrl())
LOG(INFO) << "Graphite URL: "
<< options->getMonitoringGraphiteUrl().get();
if (options->getMonitoringGraphiteNamespacePrefix())
LOG(INFO) << "Graphite URL: "
<< options->getMonitoringGraphiteNamespacePrefix().get();
LOG(INFO) << "Mountpoint: " << options->getMountpoint();
}
int startPerformanceMonitoring(std::shared_ptr<options::Options> options)
{
if (options->isMonitoringEnabled()) {
if (options->getMonitoringType().get() == "graphite") {
if (!options->getMonitoringGraphiteUrl()) {
std::cerr << "Graphite URL not specified - use option "
"--graphite-url."
<< std::endl;
return EXIT_FAILURE;
}
auto config = std::make_shared<GraphiteMonitoringConfiguration>();
try {
config->fromGraphiteURL(
options->getMonitoringGraphiteUrl().get());
}
catch (std::invalid_argument &e) {
std::cerr << "Graphite configuration error: " << e.what()
<< std::endl;
}
if (options->getMonitoringGraphiteNamespacePrefix()) {
config->namespacePrefix =
options->getMonitoringGraphiteNamespacePrefix().get();
}
config->reportingPeriod = options->getMonitoringReportingPeriod();
if (options->isMonitoringLevelFull()) {
config->reportingLevel = cppmetrics::core::ReportingLevel::Full;
}
else {
config->reportingLevel =
cppmetrics::core::ReportingLevel::Basic;
}
LOG(INFO) << "Starting Graphite performance monitoring to host: "
<< config->graphiteHostname;
// Configure and start monitoring threads
helpers::configureMonitoring(config, true);
// Initialize the command line option counter values
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.scheduler_thread_count",
options->getSchedulerThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.communicator_thread_count",
options->getCommunicatorThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.storage_helper_thread_count",
options->getStorageHelperThreadCount());
ONE_METRIC_COUNTER_SET("comp.oneclient.mod.options.buffer_"
"scheduler_helper_thread_count",
options->getBufferSchedulerThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_min_size",
options->getReadBufferMinSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_max_size",
options->getReadBufferMaxSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_min_size",
options->getWriteBufferMinSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_max_size",
options->getWriteBufferMaxSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_prefetch_duration",
options->getReadBufferPrefetchDuration().count());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_flush_delay",
options->getWriteBufferFlushDelay().count());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.metadata_cache_size",
options->getMetadataCacheSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.monitoring_reporting_period",
options->getMonitoringReportingPeriod());
}
else {
std::cerr << "Unsupported performance monitoring reporter: "
<< options->getMonitoringType().get() << std::endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
std::string generateSessionId()
{
std::random_device rd;
std::default_random_engine randomEngine{rd()};
std::uniform_int_distribution<unsigned long long> sessionIdDistribution;
return std::to_string(sessionIdDistribution(randomEngine));
}
std::shared_ptr<communication::Communicator> handshake(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto handshakeHandler = [&](messages::HandshakeResponse msg) {
if (msg.isMacaroonError()) {
authManager->cleanup();
}
return msg.status();
};
auto testCommunicatorTuple = authManager->createCommunicator(
1, sessionId, ONECLIENT_VERSION, handshakeHandler);
auto testCommunicator =
std::get<std::shared_ptr<communication::Communicator>>(
testCommunicatorTuple);
testCommunicator->setScheduler(context->scheduler());
testCommunicator->connect();
communication::wait(
std::get<folly::Future<folly::Unit>>(testCommunicatorTuple),
context->options()->getProviderTimeout());
return testCommunicator;
}
std::shared_ptr<options::Options> getOptions(int argc, char *argv[])
{
auto options = std::make_shared<options::Options>();
try {
options->parse(argc, argv);
return options;
}
catch (const boost::program_options::error &e) {
std::cerr << std::regex_replace(e.what(), std::regex("--"), "") << "\n"
<< "See '" << argv[0] << " --help'." << std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<auth::AuthManager> getAuthManager(
std::shared_ptr<Context> context)
{
try {
auto options = context->options();
return std::make_shared<auth::MacaroonAuthManager>(context,
options->getProviderHost().get(), options->getProviderPort(),
!options->isInsecure(), options->getProviderTimeout());
}
catch (auth::AuthException &e) {
std::cerr << "Authentication error: '" << e.what() << "'. Aborting..."
<< std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<messages::Configuration> getConfiguration(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto options = context->options();
std::cout << "Connecting to provider '" << options->getProviderHost().get()
<< ":" << options->getProviderPort() << "' using session ID: '"
<< sessionId << "'..." << std::endl;
try {
auto communicator =
handshake(sessionId, std::move(authManager), std::move(context));
std::cout << "Getting configuration..." << std::endl;
auto future = communicator->communicate<messages::Configuration>(
messages::GetConfiguration{});
auto configuration =
communication::wait(future, options->getProviderTimeout());
return std::make_shared<messages::Configuration>(
std::move(configuration));
}
catch (const std::exception &e) {
std::cerr << "Connection error: '" << e.what() << "'. Aborting..."
<< std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<communication::Communicator> getCommunicator(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto handshakeHandler = [](auto) { return std::error_code{}; };
auto communicatorTuple = authManager->createCommunicator(
context->options()->getCommunicatorThreadCount(), sessionId,
ONECLIENT_VERSION, handshakeHandler);
auto communicator = std::get<std::shared_ptr<communication::Communicator>>(
communicatorTuple);
communicator->setScheduler(context->scheduler());
return communicator;
}
void unmountFuse(std::shared_ptr<options::Options> options)
{
int status = 0, pid = fork();
if (pid) {
waitpid(pid, &status, 0);
}
else {
#if defined(__APPLE__)
auto exec = "/usr/sbin/diskutil";
execl(exec, exec, "unmount", options->getMountpoint().c_str(), NULL);
#else
auto exec = "/bin/fusermount";
execl(exec, exec, "-u", options->getMountpoint().c_str(), NULL);
#endif
}
if (status == 0) {
std::cout << "Oneclient has been successfully unmounted." << std::endl;
}
exit(status);
}
int main(int argc, char *argv[])
{
helpers::init();
auto context = std::make_shared<Context>();
auto options = getOptions(argc, argv);
context->setOptions(options);
if (options->getHelp()) {
std::cout << options->formatHelp(argv[0]);
return EXIT_SUCCESS;
}
if (options->getVersion()) {
std::cout << "Oneclient: " << ONECLIENT_VERSION << "\n"
<< "FUSE library: " << FUSE_MAJOR_VERSION << "."
<< FUSE_MINOR_VERSION << std::endl;
return EXIT_SUCCESS;
}
if (options->getUnmount()) {
unmountFuse(options);
}
if (!options->getProviderHost()) {
std::cerr << "the option 'host' is required but missing\n"
<< "See '" << argv[0] << " --help'." << std::endl;
return EXIT_FAILURE;
}
if (options->hasDeprecated()) {
std::cout << options->formatDeprecated();
}
startLogging(argv[0], options);
context->setScheduler(
std::make_shared<Scheduler>(options->getSchedulerThreadCount()));
auto authManager = getAuthManager(context);
auto sessionId = generateSessionId();
auto configuration = getConfiguration(sessionId, authManager, context);
auto fuse_oper = fuseOperations();
auto args = options->getFuseArgs(argv[0]);
char *mountpoint;
int multithreaded;
int foreground;
int res;
res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground);
if (res == -1)
return EXIT_FAILURE;
ScopeExit freeMountpoint{[=] { free(mountpoint); }};
auto ch = fuse_mount(mountpoint, &args);
if (!ch)
return EXIT_FAILURE;
ScopeExit unmountFuse{[=] { fuse_unmount(mountpoint, ch); }};
res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC);
if (res == -1)
perror("WARNING: failed to set FD_CLOEXEC on fuse device");
std::unique_ptr<fslogic::Composite> fsLogic;
auto fuse =
fuse_lowlevel_new(&args, &fuse_oper, sizeof(fuse_oper), &fsLogic);
if (fuse == nullptr)
return EXIT_FAILURE;
ScopeExit destroyFuse{[=] { fuse_session_destroy(fuse); }, unmountFuse};
fuse_set_signal_handlers(fuse);
ScopeExit removeHandlers{[&] { fuse_remove_signal_handlers(fuse); }};
fuse_session_add_chan(fuse, ch);
ScopeExit removeChannel{[&] { fuse_session_remove_chan(ch); }};
std::cout << "Oneclient has been successfully mounted in '"
<< options->getMountpoint().c_str() << "'." << std::endl;
if (!foreground) {
context->scheduler()->prepareForDaemonize();
folly::SingletonVault::singleton()->destroyInstances();
fuse_remove_signal_handlers(fuse);
res = fuse_daemonize(foreground);
if (res != -1)
res = fuse_set_signal_handlers(fuse);
if (res == -1)
return EXIT_FAILURE;
folly::SingletonVault::singleton()->reenableInstances();
context->scheduler()->restartAfterDaemonize();
}
else {
FLAGS_stderrthreshold = options->getDebug() ? 0 : 1;
}
if (startPerformanceMonitoring(options) != EXIT_SUCCESS)
return EXIT_FAILURE;
auto communicator = getCommunicator(sessionId, authManager, context);
context->setCommunicator(communicator);
communicator->connect();
auto helpersCache = std::make_unique<cache::HelpersCache>(
*communicator, *context->scheduler(), *options);
const auto &rootUuid = configuration->rootUuid();
fsLogic = std::make_unique<fslogic::Composite>(rootUuid, std::move(context),
std::move(configuration), std::move(helpersCache),
options->areFileReadEventsDisabled(), options->getMetadataCacheSize(),
options->getProviderTimeout());
res = multithreaded ? fuse_session_loop_mt(fuse) : fuse_session_loop(fuse);
communicator->stop();
return res == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
<commit_msg>VFS-4116 Fixed metadata cache size initialization<commit_after>/**
* @file main.cc
* @author Rafal Slota
* @copyright (C) 2016 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef linux
/* For pread()/pwrite()/utimensat() */
#define _XOPEN_SOURCE 700
#endif
#include "asio.hpp"
#include "auth/authException.h"
#include "auth/authManager.h"
#include "communication/exception.h"
#include "context.h"
#include "fsOperations.h"
#include "fslogic/composite.h"
#include "fuseOperations.h"
#include "helpers/init.h"
#include "logging.h"
#include "messages/configuration.h"
#include "messages/getConfiguration.h"
#include "messages/handshakeResponse.h"
#include "monitoring/monitoring.h"
#include "monitoring/monitoringConfiguration.h"
#include "options/options.h"
#include "scheduler.h"
#include "scopeExit.h"
#include "version.h"
#include <folly/Singleton.h>
#include <fuse/fuse_lowlevel.h>
#include <fuse/fuse_opt.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <exception>
#include <future>
#include <iostream>
#include <memory>
#include <random>
#include <regex>
#include <string>
#if !defined(NDEBUG)
/**
* We have to expose FLAGS_vmodule variable here, as it is not declared
* publicly by Glog library.
*/
DECLARE_string(vmodule);
#endif
using namespace one;
using namespace one::client;
using namespace one::monitoring;
void startLogging(
const char *programName, std::shared_ptr<options::Options> options)
{
try {
boost::filesystem::create_directories(options->getLogDirPath());
}
catch (const boost::filesystem::filesystem_error &e) {
std::cerr << "Failed to create log directory: '" << e.what()
<< "'. Aborting..." << std::endl;
}
FLAGS_minloglevel = 0;
FLAGS_logtostderr = false;
FLAGS_stderrthreshold = options->getDebug() ? 0 : 2;
FLAGS_log_dir = options->getLogDirPath().c_str();
FLAGS_stop_logging_if_full_disk = true;
#if !defined(NDEBUG)
FLAGS_v = options->getVerboseLogLevel();
FLAGS_vmodule = options->getVerboseLogFilter()
? options->getVerboseLogFilter().get()
: "*";
#endif
google::InitGoogleLogging(programName);
if (options->getProviderHost())
LOG(INFO) << "Connecting to Oneprovider: "
<< options->getProviderHost().get();
LOG(INFO) << "Forced direct io: " << options->isDirectIOForced();
LOG(INFO) << "Forced proxy io: " << options->isDirectIOForced();
LOG(INFO) << "Verify service certificate: " << options->isInsecure();
LOG(INFO) << "File read events disabled: "
<< options->areFileReadEventsDisabled();
LOG(INFO) << "Is IO buffered: " << options->isIOBuffered();
LOG(INFO) << "Oneprovider connection timeout [s]: "
<< options->getProviderTimeout().count();
LOG(INFO) << "Is monitoring enabled: " << options->isMonitoringEnabled();
if (options->getMonitoringType())
LOG(INFO) << "Monitoring type: " << options->getMonitoringType().get();
LOG(INFO) << "Is monitoring level basic: "
<< options->isMonitoringLevelBasic();
LOG(INFO) << "Is monitoring level full: "
<< options->isMonitoringLevelFull();
if (options->getMonitoringGraphiteUrl())
LOG(INFO) << "Graphite URL: "
<< options->getMonitoringGraphiteUrl().get();
if (options->getMonitoringGraphiteNamespacePrefix())
LOG(INFO) << "Graphite URL: "
<< options->getMonitoringGraphiteNamespacePrefix().get();
LOG(INFO) << "Mountpoint: " << options->getMountpoint();
}
int startPerformanceMonitoring(std::shared_ptr<options::Options> options)
{
if (options->isMonitoringEnabled()) {
if (options->getMonitoringType().get() == "graphite") {
if (!options->getMonitoringGraphiteUrl()) {
std::cerr << "Graphite URL not specified - use option "
"--graphite-url."
<< std::endl;
return EXIT_FAILURE;
}
auto config = std::make_shared<GraphiteMonitoringConfiguration>();
try {
config->fromGraphiteURL(
options->getMonitoringGraphiteUrl().get());
}
catch (std::invalid_argument &e) {
std::cerr << "Graphite configuration error: " << e.what()
<< std::endl;
}
if (options->getMonitoringGraphiteNamespacePrefix()) {
config->namespacePrefix =
options->getMonitoringGraphiteNamespacePrefix().get();
}
config->reportingPeriod = options->getMonitoringReportingPeriod();
if (options->isMonitoringLevelFull()) {
config->reportingLevel = cppmetrics::core::ReportingLevel::Full;
}
else {
config->reportingLevel =
cppmetrics::core::ReportingLevel::Basic;
}
LOG(INFO) << "Starting Graphite performance monitoring to host: "
<< config->graphiteHostname;
// Configure and start monitoring threads
helpers::configureMonitoring(config, true);
// Initialize the command line option counter values
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.scheduler_thread_count",
options->getSchedulerThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.communicator_thread_count",
options->getCommunicatorThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.storage_helper_thread_count",
options->getStorageHelperThreadCount());
ONE_METRIC_COUNTER_SET("comp.oneclient.mod.options.buffer_"
"scheduler_helper_thread_count",
options->getBufferSchedulerThreadCount());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_min_size",
options->getReadBufferMinSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_max_size",
options->getReadBufferMaxSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_min_size",
options->getWriteBufferMinSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_max_size",
options->getWriteBufferMaxSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.read_buffer_prefetch_duration",
options->getReadBufferPrefetchDuration().count());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.write_buffer_flush_delay",
options->getWriteBufferFlushDelay().count());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.metadata_cache_size",
options->getMetadataCacheSize());
ONE_METRIC_COUNTER_SET(
"comp.oneclient.mod.options.monitoring_reporting_period",
options->getMonitoringReportingPeriod());
}
else {
std::cerr << "Unsupported performance monitoring reporter: "
<< options->getMonitoringType().get() << std::endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
std::string generateSessionId()
{
std::random_device rd;
std::default_random_engine randomEngine{rd()};
std::uniform_int_distribution<unsigned long long> sessionIdDistribution;
return std::to_string(sessionIdDistribution(randomEngine));
}
std::shared_ptr<communication::Communicator> handshake(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto handshakeHandler = [&](messages::HandshakeResponse msg) {
if (msg.isMacaroonError()) {
authManager->cleanup();
}
return msg.status();
};
auto testCommunicatorTuple = authManager->createCommunicator(
1, sessionId, ONECLIENT_VERSION, handshakeHandler);
auto testCommunicator =
std::get<std::shared_ptr<communication::Communicator>>(
testCommunicatorTuple);
testCommunicator->setScheduler(context->scheduler());
testCommunicator->connect();
communication::wait(
std::get<folly::Future<folly::Unit>>(testCommunicatorTuple),
context->options()->getProviderTimeout());
return testCommunicator;
}
std::shared_ptr<options::Options> getOptions(int argc, char *argv[])
{
auto options = std::make_shared<options::Options>();
try {
options->parse(argc, argv);
return options;
}
catch (const boost::program_options::error &e) {
std::cerr << std::regex_replace(e.what(), std::regex("--"), "") << "\n"
<< "See '" << argv[0] << " --help'." << std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<auth::AuthManager> getAuthManager(
std::shared_ptr<Context> context)
{
try {
auto options = context->options();
return std::make_shared<auth::MacaroonAuthManager>(context,
options->getProviderHost().get(), options->getProviderPort(),
!options->isInsecure(), options->getProviderTimeout());
}
catch (auth::AuthException &e) {
std::cerr << "Authentication error: '" << e.what() << "'. Aborting..."
<< std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<messages::Configuration> getConfiguration(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto options = context->options();
std::cout << "Connecting to provider '" << options->getProviderHost().get()
<< ":" << options->getProviderPort() << "' using session ID: '"
<< sessionId << "'..." << std::endl;
try {
auto communicator =
handshake(sessionId, std::move(authManager), std::move(context));
std::cout << "Getting configuration..." << std::endl;
auto future = communicator->communicate<messages::Configuration>(
messages::GetConfiguration{});
auto configuration =
communication::wait(future, options->getProviderTimeout());
return std::make_shared<messages::Configuration>(
std::move(configuration));
}
catch (const std::exception &e) {
std::cerr << "Connection error: '" << e.what() << "'. Aborting..."
<< std::endl;
exit(EXIT_FAILURE);
}
}
std::shared_ptr<communication::Communicator> getCommunicator(
const std::string &sessionId,
std::shared_ptr<auth::AuthManager> authManager,
std::shared_ptr<Context> context)
{
auto handshakeHandler = [](auto) { return std::error_code{}; };
auto communicatorTuple = authManager->createCommunicator(
context->options()->getCommunicatorThreadCount(), sessionId,
ONECLIENT_VERSION, handshakeHandler);
auto communicator = std::get<std::shared_ptr<communication::Communicator>>(
communicatorTuple);
communicator->setScheduler(context->scheduler());
return communicator;
}
void unmountFuse(std::shared_ptr<options::Options> options)
{
int status = 0, pid = fork();
if (pid) {
waitpid(pid, &status, 0);
}
else {
#if defined(__APPLE__)
auto exec = "/usr/sbin/diskutil";
execl(exec, exec, "unmount", options->getMountpoint().c_str(), NULL);
#else
auto exec = "/bin/fusermount";
execl(exec, exec, "-u", options->getMountpoint().c_str(), NULL);
#endif
}
if (status == 0) {
std::cout << "Oneclient has been successfully unmounted." << std::endl;
}
exit(status);
}
int main(int argc, char *argv[])
{
helpers::init();
auto context = std::make_shared<Context>();
auto options = getOptions(argc, argv);
context->setOptions(options);
if (options->getHelp()) {
std::cout << options->formatHelp(argv[0]);
return EXIT_SUCCESS;
}
if (options->getVersion()) {
std::cout << "Oneclient: " << ONECLIENT_VERSION << "\n"
<< "FUSE library: " << FUSE_MAJOR_VERSION << "."
<< FUSE_MINOR_VERSION << std::endl;
return EXIT_SUCCESS;
}
if (options->getUnmount()) {
unmountFuse(options);
}
if (!options->getProviderHost()) {
std::cerr << "the option 'host' is required but missing\n"
<< "See '" << argv[0] << " --help'." << std::endl;
return EXIT_FAILURE;
}
if (options->hasDeprecated()) {
std::cout << options->formatDeprecated();
}
startLogging(argv[0], options);
context->setScheduler(
std::make_shared<Scheduler>(options->getSchedulerThreadCount()));
auto authManager = getAuthManager(context);
auto sessionId = generateSessionId();
auto configuration = getConfiguration(sessionId, authManager, context);
auto fuse_oper = fuseOperations();
auto args = options->getFuseArgs(argv[0]);
char *mountpoint;
int multithreaded;
int foreground;
int res;
res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground);
if (res == -1)
return EXIT_FAILURE;
ScopeExit freeMountpoint{[=] { free(mountpoint); }};
auto ch = fuse_mount(mountpoint, &args);
if (!ch)
return EXIT_FAILURE;
ScopeExit unmountFuse{[=] { fuse_unmount(mountpoint, ch); }};
res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC);
if (res == -1)
perror("WARNING: failed to set FD_CLOEXEC on fuse device");
std::unique_ptr<fslogic::Composite> fsLogic;
auto fuse =
fuse_lowlevel_new(&args, &fuse_oper, sizeof(fuse_oper), &fsLogic);
if (fuse == nullptr)
return EXIT_FAILURE;
ScopeExit destroyFuse{[=] { fuse_session_destroy(fuse); }, unmountFuse};
fuse_set_signal_handlers(fuse);
ScopeExit removeHandlers{[&] { fuse_remove_signal_handlers(fuse); }};
fuse_session_add_chan(fuse, ch);
ScopeExit removeChannel{[&] { fuse_session_remove_chan(ch); }};
std::cout << "Oneclient has been successfully mounted in '"
<< options->getMountpoint().c_str() << "'." << std::endl;
if (!foreground) {
context->scheduler()->prepareForDaemonize();
folly::SingletonVault::singleton()->destroyInstances();
fuse_remove_signal_handlers(fuse);
res = fuse_daemonize(foreground);
if (res != -1)
res = fuse_set_signal_handlers(fuse);
if (res == -1)
return EXIT_FAILURE;
folly::SingletonVault::singleton()->reenableInstances();
context->scheduler()->restartAfterDaemonize();
}
else {
FLAGS_stderrthreshold = options->getDebug() ? 0 : 1;
}
if (startPerformanceMonitoring(options) != EXIT_SUCCESS)
return EXIT_FAILURE;
auto communicator = getCommunicator(sessionId, authManager, context);
context->setCommunicator(communicator);
communicator->connect();
auto helpersCache = std::make_unique<cache::HelpersCache>(
*communicator, *context->scheduler(), *options);
const auto &rootUuid = configuration->rootUuid();
fsLogic = std::make_unique<fslogic::Composite>(rootUuid, std::move(context),
std::move(configuration), std::move(helpersCache),
options->getMetadataCacheSize(), options->areFileReadEventsDisabled(),
options->getProviderTimeout());
res = multithreaded ? fuse_session_loop_mt(fuse) : fuse_session_loop(fuse);
communicator->stop();
return res == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "NTClient.h"
int main(int argc, char** argv) {
return 0;
}<commit_msg>Makefile updates<commit_after>#include <iostream>
#include "NTClient.h"
int main(int argc, char** argv) {
NTClient nclient = NTClient("asd4wderg", "123asd123"); // Throw-away account
return 0;
}<|endoftext|> |
<commit_before>//
// Copyright (C) Michael Yang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full
// license information.
//
#include "config.h"
#include "funny_pics.h"
#include "girl_pics.h"
#include "joke.h"
#include "message.h"
#include "quote.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <csignal>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
enum class bot_command : std::uint8_t {
quote,
joke,
funny_pics,
girl_pics,
about
};
using namespace std::chrono_literals;
using bot_command_queue =
boost::lockfree::spsc_queue<bot_command, boost::lockfree::capacity<100>>;
static std::atomic<bool> keep_running(true);
static std::unordered_map<std::int64_t, std::shared_ptr<bot_command_queue>>
message_queue_map;
static std::mutex map_mutex;
static void signal_handler(int signal) { keep_running = false; }
static void consumer(std::int64_t chat_id,
std::shared_ptr<bot_command_queue> queue) {
spdlog::get("logger")->info("ℹ️ thread is created for 💬<{}>",
chat_id);
std::chrono::time_point<std::chrono::steady_clock> start;
for (;;) {
if (!queue->consume_all([&chat_id, &start](bot_command command) {
switch (command) {
case bot_command::quote: {
const auto quote = ohmyarch::get_quote();
if (quote)
ohmyarch::send_message(chat_id, quote->text() + " - " +
quote->author());
break;
}
case bot_command::joke: {
const auto joke = ohmyarch::get_joke();
if (joke)
ohmyarch::send_message(chat_id, joke.value());
break;
}
case bot_command::funny_pics: {
const auto funny_pics = ohmyarch::get_funny_pics();
if (funny_pics) {
for (const auto &pic_uri : funny_pics.value())
if (boost::ends_with(pic_uri, "gif"))
ohmyarch::send_document(chat_id, pic_uri);
else
ohmyarch::send_message(chat_id, pic_uri);
}
break;
}
case bot_command::girl_pics: {
const auto girl_pics = ohmyarch::get_girl_pics();
if (girl_pics) {
for (const auto &pic_uri : girl_pics.value())
if (boost::ends_with(pic_uri, "gif"))
ohmyarch::send_document(chat_id, pic_uri);
else
ohmyarch::send_message(chat_id, pic_uri);
}
break;
}
case bot_command::about: {
ohmyarch::send_message(
chat_id, "https://github.com/ohmyarch/ohmyarch_bot");
break;
}
}
start = std::chrono::steady_clock::now();
})) {
if (std::chrono::duration<double>(std::chrono::steady_clock::now() -
start)
.count() > 10.0) {
break;
} else {
std::this_thread::yield();
std::this_thread::sleep_for(100ms);
}
}
}
{
std::lock_guard<std::mutex> guard(map_mutex);
message_queue_map.erase(chat_id);
}
spdlog::get("logger")->info("ℹ️ thread is destroyed for 💬<{}>",
chat_id);
}
int main(int argc, char *argv[]) {
std::string path_to_config;
boost::program_options::options_description options("options");
options.add_options()(
"config", boost::program_options::value<std::string>(&path_to_config)
->value_name("/path/to/config"),
"specify a path to a custom config file")("help,h",
"print this text and exit");
boost::program_options::variables_map map;
try {
boost::program_options::store(
boost::program_options::parse_command_line(argc, argv, options),
map);
} catch (const boost::program_options::error &error) {
std::cerr << "❌ " << error.what() << std::endl;
return 1;
}
if (map.count("help") || map.empty()) {
std::cout << options;
return 0;
}
boost::program_options::notify(map);
if (path_to_config.empty()) {
std::cerr << "❌ option '--config' is missing" << std::endl;
return 1;
}
std::ifstream config_file(path_to_config);
if (!config_file) {
std::cerr << "❌ config file opening failed" << std::endl;
return 1;
}
nlohmann::json json;
try {
json << config_file;
ohmyarch::api_uri =
"https://api.telegram.org/bot" +
json.at("token").get_ref<const nlohmann::json::string_t &>() + '/';
} catch (const std::exception &error) {
std::cerr << "❌ json: " << error.what() << std::endl;
return 1;
}
const auto iterator_http_proxy = json.find("http_proxy");
if (iterator_http_proxy != json.end())
try {
ohmyarch::client_config.set_proxy(web::web_proxy(
iterator_http_proxy.value()
.get_ref<const nlohmann::json::string_t &>()));
} catch (const std::exception &error) {
std::cerr << "❌ set_proxy: " << error.what() << std::endl;
return 1;
}
spdlog::set_async_mode(8192);
try {
std::vector<spdlog::sink_ptr> sinks{
std::make_shared<spdlog::sinks::ansicolor_sink>(
std::make_shared<spdlog::sinks::stdout_sink_mt>()),
std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
json.at("log_path"), "txt", 1024 * 1024 * 5, 0)};
auto combined_logger = std::make_shared<spdlog::logger>(
"logger", sinks.begin(), sinks.end());
combined_logger->flush_on(spdlog::level::err);
spdlog::register_logger(combined_logger);
} catch (const std::exception &error) {
std::cout << "❌ log failed: " << error.what() << std::endl;
return 1;
}
std::signal(SIGINT, signal_handler);
const auto bot_username = ohmyarch::get_me();
if (!bot_username)
return 1;
const std::string &username = bot_username.value();
const std::string quote_command = "/quote@" + username;
const std::string joke_command = "/joke@" + username;
const std::string funny_pics_command = "/funny_pics@" + username;
const std::string girl_pics_command = "/girl_pics@" + username;
const std::string about_command = "/about@" + username;
spdlog::get("logger")->info("🤖️ @{} is running 😉", username);
spdlog::get("logger")->flush();
while (keep_running) {
const auto updates = ohmyarch::get_updates();
if (updates)
for (const auto &update : updates.value()) {
const auto &message = update.message();
if (message) {
const auto &entities = message->entities();
if (entities) {
const std::int64_t chat_id = message->chat().id();
std::u16string text =
utility::conversions::utf8_to_utf16(
message->text().value());
for (const auto &entity : entities.value())
if (entity.type() == "bot_command") {
bot_command command;
const std::string command_text =
utility::conversions::utf16_to_utf8(
text.substr(entity.offset(),
entity.length()));
if (command_text == "/quote" ||
command_text == quote_command)
command = bot_command::quote;
else if (command_text == "/joke" ||
command_text == joke_command)
command = bot_command::joke;
else if (command_text == "/funny_pics" ||
command_text == funny_pics_command)
command = bot_command::funny_pics;
else if (command_text == "/girl_pics" ||
command_text == girl_pics_command)
command = bot_command::girl_pics;
else if (command_text == "/about" ||
command_text == about_command)
command = bot_command::about;
std::unique_lock<std::mutex> lock(map_mutex);
const auto pair = message_queue_map.emplace(
chat_id,
std::make_shared<bot_command_queue>());
lock.unlock();
auto &queue = pair.first->second;
queue->push(command);
if (pair.second) {
std::thread consumer_thread(consumer,
chat_id, queue);
consumer_thread.detach();
}
}
}
}
}
}
spdlog::get("logger")->info("🤖️ @{} stopped 😴", username);
}
<commit_msg>🐛 Fix a bug<commit_after>//
// Copyright (C) Michael Yang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full
// license information.
//
#include "config.h"
#include "funny_pics.h"
#include "girl_pics.h"
#include "joke.h"
#include "message.h"
#include "quote.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <csignal>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
enum class bot_command : std::uint8_t {
quote,
joke,
funny_pics,
girl_pics,
about
};
using namespace std::chrono_literals;
using bot_command_queue =
boost::lockfree::spsc_queue<bot_command, boost::lockfree::capacity<100>>;
static std::atomic<bool> keep_running(true);
static std::unordered_map<std::int64_t, std::shared_ptr<bot_command_queue>>
message_queue_map;
static std::mutex map_mutex;
static void signal_handler(int signal) { keep_running = false; }
static void consumer(std::int64_t chat_id,
std::shared_ptr<bot_command_queue> queue) {
spdlog::get("logger")->info("ℹ️ thread is created for 💬<{}>",
chat_id);
std::chrono::time_point<std::chrono::steady_clock> start;
for (;;) {
if (!queue->consume_all([&chat_id, &start](bot_command command) {
switch (command) {
case bot_command::quote: {
const auto quote = ohmyarch::get_quote();
if (quote)
ohmyarch::send_message(chat_id, quote->text() + " - " +
quote->author());
break;
}
case bot_command::joke: {
const auto joke = ohmyarch::get_joke();
if (joke)
ohmyarch::send_message(chat_id, joke.value());
break;
}
case bot_command::funny_pics: {
const auto funny_pics = ohmyarch::get_funny_pics();
if (funny_pics) {
for (const auto &pic_uri : funny_pics.value())
if (boost::ends_with(pic_uri, "gif"))
ohmyarch::send_document(chat_id, pic_uri);
else
ohmyarch::send_message(chat_id, pic_uri);
}
break;
}
case bot_command::girl_pics: {
const auto girl_pics = ohmyarch::get_girl_pics();
if (girl_pics) {
for (const auto &pic_uri : girl_pics.value())
if (boost::ends_with(pic_uri, "gif"))
ohmyarch::send_document(chat_id, pic_uri);
else
ohmyarch::send_message(chat_id, pic_uri);
}
break;
}
case bot_command::about: {
ohmyarch::send_message(
chat_id, "https://github.com/ohmyarch/ohmyarch_bot");
break;
}
}
start = std::chrono::steady_clock::now();
})) {
if (std::chrono::duration<double>(std::chrono::steady_clock::now() -
start)
.count() > 10.0) {
break;
} else {
std::this_thread::yield();
std::this_thread::sleep_for(100ms);
}
}
}
{
std::lock_guard<std::mutex> guard(map_mutex);
message_queue_map.erase(chat_id);
}
spdlog::get("logger")->info("ℹ️ thread is destroyed for 💬<{}>",
chat_id);
}
int main(int argc, char *argv[]) {
std::string path_to_config;
boost::program_options::options_description options("options");
options.add_options()(
"config", boost::program_options::value<std::string>(&path_to_config)
->value_name("/path/to/config"),
"specify a path to a custom config file")("help,h",
"print this text and exit");
boost::program_options::variables_map map;
try {
boost::program_options::store(
boost::program_options::parse_command_line(argc, argv, options),
map);
} catch (const boost::program_options::error &error) {
std::cerr << "❌ " << error.what() << std::endl;
return 1;
}
if (map.count("help") || map.empty()) {
std::cout << options;
return 0;
}
boost::program_options::notify(map);
if (path_to_config.empty()) {
std::cerr << "❌ option '--config' is missing" << std::endl;
return 1;
}
std::ifstream config_file(path_to_config);
if (!config_file) {
std::cerr << "❌ config file opening failed" << std::endl;
return 1;
}
nlohmann::json json;
try {
json << config_file;
ohmyarch::api_uri =
"https://api.telegram.org/bot" +
json.at("token").get_ref<const nlohmann::json::string_t &>() + '/';
} catch (const std::exception &error) {
std::cerr << "❌ json: " << error.what() << std::endl;
return 1;
}
const auto iterator_http_proxy = json.find("http_proxy");
if (iterator_http_proxy != json.end())
try {
ohmyarch::client_config.set_proxy(web::web_proxy(
iterator_http_proxy.value()
.get_ref<const nlohmann::json::string_t &>()));
} catch (const std::exception &error) {
std::cerr << "❌ set_proxy: " << error.what() << std::endl;
return 1;
}
spdlog::set_async_mode(8192);
try {
std::vector<spdlog::sink_ptr> sinks{
std::make_shared<spdlog::sinks::ansicolor_sink>(
std::make_shared<spdlog::sinks::stdout_sink_mt>()),
std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
json.at("log_path"), "txt", 1024 * 1024 * 5, 0)};
auto combined_logger = std::make_shared<spdlog::logger>(
"logger", sinks.begin(), sinks.end());
combined_logger->flush_on(spdlog::level::err);
spdlog::register_logger(combined_logger);
} catch (const std::exception &error) {
std::cout << "❌ log failed: " << error.what() << std::endl;
return 1;
}
std::signal(SIGINT, signal_handler);
const auto bot_username = ohmyarch::get_me();
if (!bot_username)
return 1;
const std::string &username = bot_username.value();
const std::string quote_command = "/quote@" + username;
const std::string joke_command = "/joke@" + username;
const std::string funny_pics_command = "/funny_pics@" + username;
const std::string girl_pics_command = "/girl_pics@" + username;
const std::string about_command = "/about@" + username;
spdlog::get("logger")->info("🤖️ @{} is running 😉", username);
spdlog::get("logger")->flush();
while (keep_running) {
const auto updates = ohmyarch::get_updates();
if (updates)
for (const auto &update : updates.value()) {
const auto &message = update.message();
if (message) {
const auto &entities = message->entities();
if (entities) {
const std::int64_t chat_id = message->chat().id();
std::u16string text =
utility::conversions::utf8_to_utf16(
message->text().value());
for (const auto &entity : entities.value())
if (entity.type() == "bot_command") {
std::experimental::optional<bot_command>
command;
const std::string command_text =
utility::conversions::utf16_to_utf8(
text.substr(entity.offset(),
entity.length()));
if (command_text == "/quote" ||
command_text == quote_command)
command = bot_command::quote;
else if (command_text == "/joke" ||
command_text == joke_command)
command = bot_command::joke;
else if (command_text == "/funny_pics" ||
command_text == funny_pics_command)
command = bot_command::funny_pics;
else if (command_text == "/girl_pics" ||
command_text == girl_pics_command)
command = bot_command::girl_pics;
else if (command_text == "/about" ||
command_text == about_command)
command = bot_command::about;
if (command) {
std::unique_lock<std::mutex> lock(
map_mutex);
const auto pair = message_queue_map.emplace(
chat_id,
std::make_shared<bot_command_queue>());
lock.unlock();
auto &queue = pair.first->second;
queue->push(command.value());
if (pair.second) {
std::thread consumer_thread(
consumer, chat_id, queue);
consumer_thread.detach();
}
}
}
}
}
}
}
spdlog::get("logger")->info("🤖️ @{} stopped 😴", username);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* 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 "NcursesTerminal.hh"
#include "Shibuya.hh"
#include "Exceptions.hh"
#include "BGFile.hh"
#include <iostream>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
NcursesTerminal * toDump = NULL;
void sighandle ( int signo ) {
switch ( signo ) {
case SIGUSR1:
if ( ! toDump )
return;
for ( int iy = 0; iy < toDump->get_height(); ++iy ) {
for ( int ix = 0; ix < toDump->get_width(); ++ix ) {
int offset = ( toDump->get_width() * iy ) + ix;
std::cerr << toDump->chars[offset].ch;
}
std::cerr << std::endl;
}
break;
case SIGWINCH:
/* Something's wrong with this... */
uninit_screen();
init_screen();
update_screen();
/* XXX: Handle background re-center */
break;
case SIGTERM:
uninit_screen();
exit(0);
break;
case SIGINT:
toDump->sigint(); /* Fixme */
break;
default:
break;
}
}
int main ( int argc, char ** argv ) {
set_clog(); // XXX: This is ugly
init_screen();
NcursesTerminal nt( 80, 25, 3, 2 );
nt.fork("/bin/bash");
toDump = &nt;
signal( SIGUSR1, sighandle );
signal( SIGTERM, sighandle );
signal( SIGINT, sighandle );
signal( SIGWINCH, sighandle );
try {
while ( true ) {
nt.poke();
if ( nt.render() )
update_screen();
timeout(0);
int ch = getch();
if ( ch != ERR ) {
if ( ch == 0x05 ) {
/* 0x05 is ENQ - let's use it for our special sequence. */
nt.resize( 100, 30 );
} else {
nt.type(ch);
}
} else {
usleep( 2000 );
}
}
} catch ( DeadChildException * e ) {
delete e;
}
uninit_screen();
}
<commit_msg>ignoring ncurses kruft<commit_after>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* 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 "NcursesTerminal.hh"
#include "Shibuya.hh"
#include "Exceptions.hh"
#include "BGFile.hh"
#include <iostream>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
NcursesTerminal * toDump = NULL;
void sighandle ( int signo ) {
switch ( signo ) {
case SIGUSR1:
if ( ! toDump )
return;
for ( int iy = 0; iy < toDump->get_height(); ++iy ) {
for ( int ix = 0; ix < toDump->get_width(); ++ix ) {
int offset = ( toDump->get_width() * iy ) + ix;
std::cerr << toDump->chars[offset].ch;
}
std::cerr << std::endl;
}
break;
case SIGWINCH:
/* Something's wrong with this... */
uninit_screen();
init_screen();
update_screen();
/* XXX: Handle background re-center */
break;
case SIGTERM:
uninit_screen();
exit(0);
break;
case SIGINT:
toDump->sigint(); /* Fixme */
break;
default:
break;
}
}
int main ( int argc, char ** argv ) {
set_clog(); // XXX: This is ugly
init_screen();
NcursesTerminal nt( 80, 25, 3, 2 );
nt.fork("/bin/bash");
toDump = &nt;
signal( SIGUSR1, sighandle );
signal( SIGTERM, sighandle );
signal( SIGINT, sighandle );
signal( SIGWINCH, sighandle );
try {
while ( true ) {
nt.poke();
if ( nt.render() )
update_screen();
timeout(0);
int ch = getch();
if ( ch != ERR ) {
if ( ch == 0x05 ) {
/* 0x05 is ENQ - let's use it for our special sequence. */
nt.resize( 100, 30 );
} else if ( ch < 128 ) {
nt.type(ch);
}
} else {
usleep( 2000 );
}
}
} catch ( DeadChildException * e ) {
delete e;
}
uninit_screen();
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
#include <vector>
#include "yaml-cpp/yaml.h"
#include "scene/filters.h"
#include "data/tileData.h"
#include "scene/sceneLoader.h"
#include "scene/scene.h"
#include "scene/styleContext.h"
using namespace Tangram;
using YAML::Node;
using Context = StyleContext;
Context ctx;
Feature civic, bmw1, bike;
Filter load(const std::string& filterYaml) {
Scene scene;
YAML::Node node = YAML::Load(filterYaml);
return SceneLoader::generateFilter(node["filter"], scene);
}
void init() {
civic.props.clear();
civic.props.add("name", "civic");
civic.props.add("brand", "honda");
civic.props.add("wheel", 4);
civic.props.add("drive", "fwd");
civic.props.add("type", "car");
bmw1.props.clear();
bmw1.props.add("name", "bmw320i");
bmw1.props.add("brand", "bmw");
bmw1.props.add("check", "false");
bmw1.props.add("series", "3");
bmw1.props.add("wheel", 4);
bmw1.props.add("drive", "all");
bmw1.props.add("type", "car");
bike.props.clear();
bike.props.add("name", "cb1100");
bike.props.add("brand", "honda");
bike.props.add("wheel", 2);
bike.props.add("type", "bike");
bike.props.add("series", "CB");
bike.props.add("check", "available");
ctx.setGlobal("$geometry", Value(1));
ctx.setGlobal("$zoom", Value("false"));
}
//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { series: !!str 3}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { name : [civic, bmw320i] }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {min : 3}}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {max : 2}}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {min : 2, max : 5}}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {any : [{name : civic}, {name : bmw320i}]}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {none : [{name : civic}, {name : bmw320i}]}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {not : {name : civic}}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$geometry : 1}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {max: bogus}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean true filter as existence check", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { drive : true }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean false filter as existence check", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { drive : false}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean true filter as existence check for keyword", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$geometry : 1}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean false filter as existence check for keyword", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$zoom : false}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
<commit_msg>Add a test case for filtering with large integer values<commit_after>#include "catch.hpp"
#include <iostream>
#include <vector>
#include "yaml-cpp/yaml.h"
#include "scene/filters.h"
#include "data/tileData.h"
#include "scene/sceneLoader.h"
#include "scene/scene.h"
#include "scene/styleContext.h"
using namespace Tangram;
using YAML::Node;
using Context = StyleContext;
Context ctx;
Feature civic, bmw1, bike;
Filter load(const std::string& filterYaml) {
Scene scene;
YAML::Node node = YAML::Load(filterYaml);
return SceneLoader::generateFilter(node["filter"], scene);
}
void init() {
civic.props.clear();
civic.props.add("name", "civic");
civic.props.add("brand", "honda");
civic.props.add("wheel", 4);
civic.props.add("drive", "fwd");
civic.props.add("type", "car");
bmw1.props.clear();
bmw1.props.add("name", "bmw320i");
bmw1.props.add("brand", "bmw");
bmw1.props.add("check", "false");
bmw1.props.add("series", "3");
bmw1.props.add("wheel", 4);
bmw1.props.add("drive", "all");
bmw1.props.add("type", "car");
bmw1.props.add("serial", 4398046511104); // 2^42
bike.props.clear();
bike.props.add("name", "cb1100");
bike.props.add("brand", "honda");
bike.props.add("wheel", 2);
bike.props.add("type", "bike");
bike.props.add("series", "CB");
bike.props.add("check", "available");
bike.props.add("serial", 4398046511105); // 2^42 + 1
ctx.setGlobal("$geometry", Value(1));
ctx.setGlobal("$zoom", Value("false"));
}
//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { series: !!str 3}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { name : [civic, bmw320i] }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {min : 3}}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {max : 2}}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {wheel : {min : 2, max : 5}}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {any : [{name : civic}, {name : bmw320i}]}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {none : [{name : civic}, {name : bmw320i}]}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {not : {name : civic}}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$geometry : 1}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {max: bogus}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean true filter as existence check", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { drive : true }");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean false filter as existence check", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { drive : false}");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(!filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean true filter as existence check for keyword", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$geometry : 1}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: boolean false filter as existence check for keyword", "[filters][core][yaml]") {
init();
Filter filter = load("filter: {$zoom : false}");
REQUIRE(filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(filter.eval(bike, ctx));
}
TEST_CASE( "yaml-filter-tests: predicate with large integers", "[filters][core][yaml]") {
init();
Filter filter = load("filter: { serial : [4398046511104] }");
REQUIRE(!filter.eval(civic, ctx));
REQUIRE(filter.eval(bmw1, ctx));
REQUIRE(!filter.eval(bike, ctx));
}<|endoftext|> |
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/analysermodel.h"
#include <algorithm>
#include "libcellml/variable.h"
#include "analysermodel_p.h"
namespace libcellml {
bool AnalyserModel::AnalyserModelImpl::haveEquivalentVariables(const Variable *variable1,
const Variable *variable2,
std::vector<const Variable *> &testedVariables)
{
if (variable1 == variable2) {
return true;
}
testedVariables.push_back(variable2);
auto testedVariablesBegin = testedVariables.begin();
auto testedVariablesEnd = testedVariables.end();
for (size_t i = 0; i < variable2->equivalentVariableCount(); ++i) {
Variable *equivalentVariable2 = variable2->equivalentVariable(i).get();
if ((std::find(testedVariablesBegin, testedVariablesEnd, equivalentVariable2) == testedVariablesEnd)
&& haveEquivalentVariables(variable1, equivalentVariable2, testedVariables)) {
return true;
}
}
return false;
}
AnalyserModel::AnalyserModel()
: mPimpl(new AnalyserModelImpl())
{
}
AnalyserModel::~AnalyserModel()
{
delete mPimpl;
}
bool AnalyserModel::isValid() const
{
return (mPimpl->mType == AnalyserModel::Type::ALGEBRAIC)
|| (mPimpl->mType == AnalyserModel::Type::ODE);
}
AnalyserModel::Type AnalyserModel::type() const
{
return mPimpl->mType;
}
AnalyserVariablePtr AnalyserModel::voi() const
{
if (!isValid()) {
return {};
}
return mPimpl->mVoi;
}
size_t AnalyserModel::stateCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mStates.size();
}
std::vector<AnalyserVariablePtr> AnalyserModel::states() const
{
if (!isValid()) {
return {};
}
return mPimpl->mStates;
}
AnalyserVariablePtr AnalyserModel::state(size_t index) const
{
if (!isValid()
|| (index >= mPimpl->mStates.size())) {
return {};
}
return mPimpl->mStates[index];
}
size_t AnalyserModel::variableCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mVariables.size();
}
std::vector<AnalyserVariablePtr> AnalyserModel::variables() const
{
if (!isValid()) {
return {};
}
return mPimpl->mVariables;
}
AnalyserVariablePtr AnalyserModel::variable(size_t index) const
{
if (!isValid() || (index >= mPimpl->mVariables.size())) {
return {};
}
return mPimpl->mVariables[index];
}
size_t AnalyserModel::equationCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mEquations.size();
}
std::vector<AnalyserEquationPtr> AnalyserModel::equations() const
{
if (!isValid()) {
return {};
}
return mPimpl->mEquations;
}
AnalyserEquationPtr AnalyserModel::equation(size_t index) const
{
if (!isValid() || (index >= mPimpl->mEquations.size())) {
return {};
}
return mPimpl->mEquations[index];
}
bool AnalyserModel::needEqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedEqFunction;
}
bool AnalyserModel::needNeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedNeqFunction;
}
bool AnalyserModel::needLtFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedLtFunction;
}
bool AnalyserModel::needLeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedLeqFunction;
}
bool AnalyserModel::needGtFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedGtFunction;
}
bool AnalyserModel::needGeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedGeqFunction;
}
bool AnalyserModel::needAndFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAndFunction;
}
bool AnalyserModel::needOrFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedOrFunction;
}
bool AnalyserModel::needXorFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedXorFunction;
}
bool AnalyserModel::needNotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedNotFunction;
}
bool AnalyserModel::needMinFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedMinFunction;
}
bool AnalyserModel::needMaxFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedMaxFunction;
}
bool AnalyserModel::needSecFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedSecFunction;
}
bool AnalyserModel::needCscFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCscFunction;
}
bool AnalyserModel::needCotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCotFunction;
}
bool AnalyserModel::needSechFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedSechFunction;
}
bool AnalyserModel::needCschFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCschFunction;
}
bool AnalyserModel::needCothFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCothFunction;
}
bool AnalyserModel::needAsecFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAsecFunction;
}
bool AnalyserModel::needAcscFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcscFunction;
}
bool AnalyserModel::needAcotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcotFunction;
}
bool AnalyserModel::needAsechFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAsechFunction;
}
bool AnalyserModel::needAcschFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcschFunction;
}
bool AnalyserModel::needAcothFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcothFunction;
}
bool AnalyserModel::areEquivalentVariables(const VariablePtr &variable1,
const VariablePtr &variable2)
{
if (variable1 == variable2) {
return true;
}
auto key = reinterpret_cast<intptr_t>(variable1.get()) * reinterpret_cast<intptr_t>(variable2.get());
auto cacheKey = mPimpl->mCachedEquivalentVariables.find(key);
if (cacheKey != mPimpl->mCachedEquivalentVariables.end()) {
return cacheKey->second;
}
std::vector<const Variable *> testedVariables;
bool res = mPimpl->haveEquivalentVariables(variable1.get(), variable2.get(), testedVariables);
mPimpl->mCachedEquivalentVariables[key] = res;
return res;
}
} // namespace libcellml
<commit_msg>AnalyserModel: added some background information to the `areEquivalentVariables()` method.<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/analysermodel.h"
#include <algorithm>
#include "libcellml/variable.h"
#include "analysermodel_p.h"
namespace libcellml {
bool AnalyserModel::AnalyserModelImpl::haveEquivalentVariables(const Variable *variable1,
const Variable *variable2,
std::vector<const Variable *> &testedVariables)
{
if (variable1 == variable2) {
return true;
}
testedVariables.push_back(variable2);
auto testedVariablesBegin = testedVariables.begin();
auto testedVariablesEnd = testedVariables.end();
for (size_t i = 0; i < variable2->equivalentVariableCount(); ++i) {
Variable *equivalentVariable2 = variable2->equivalentVariable(i).get();
if ((std::find(testedVariablesBegin, testedVariablesEnd, equivalentVariable2) == testedVariablesEnd)
&& haveEquivalentVariables(variable1, equivalentVariable2, testedVariables)) {
return true;
}
}
return false;
}
AnalyserModel::AnalyserModel()
: mPimpl(new AnalyserModelImpl())
{
}
AnalyserModel::~AnalyserModel()
{
delete mPimpl;
}
bool AnalyserModel::isValid() const
{
return (mPimpl->mType == AnalyserModel::Type::ALGEBRAIC)
|| (mPimpl->mType == AnalyserModel::Type::ODE);
}
AnalyserModel::Type AnalyserModel::type() const
{
return mPimpl->mType;
}
AnalyserVariablePtr AnalyserModel::voi() const
{
if (!isValid()) {
return {};
}
return mPimpl->mVoi;
}
size_t AnalyserModel::stateCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mStates.size();
}
std::vector<AnalyserVariablePtr> AnalyserModel::states() const
{
if (!isValid()) {
return {};
}
return mPimpl->mStates;
}
AnalyserVariablePtr AnalyserModel::state(size_t index) const
{
if (!isValid()
|| (index >= mPimpl->mStates.size())) {
return {};
}
return mPimpl->mStates[index];
}
size_t AnalyserModel::variableCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mVariables.size();
}
std::vector<AnalyserVariablePtr> AnalyserModel::variables() const
{
if (!isValid()) {
return {};
}
return mPimpl->mVariables;
}
AnalyserVariablePtr AnalyserModel::variable(size_t index) const
{
if (!isValid() || (index >= mPimpl->mVariables.size())) {
return {};
}
return mPimpl->mVariables[index];
}
size_t AnalyserModel::equationCount() const
{
if (!isValid()) {
return 0;
}
return mPimpl->mEquations.size();
}
std::vector<AnalyserEquationPtr> AnalyserModel::equations() const
{
if (!isValid()) {
return {};
}
return mPimpl->mEquations;
}
AnalyserEquationPtr AnalyserModel::equation(size_t index) const
{
if (!isValid() || (index >= mPimpl->mEquations.size())) {
return {};
}
return mPimpl->mEquations[index];
}
bool AnalyserModel::needEqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedEqFunction;
}
bool AnalyserModel::needNeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedNeqFunction;
}
bool AnalyserModel::needLtFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedLtFunction;
}
bool AnalyserModel::needLeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedLeqFunction;
}
bool AnalyserModel::needGtFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedGtFunction;
}
bool AnalyserModel::needGeqFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedGeqFunction;
}
bool AnalyserModel::needAndFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAndFunction;
}
bool AnalyserModel::needOrFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedOrFunction;
}
bool AnalyserModel::needXorFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedXorFunction;
}
bool AnalyserModel::needNotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedNotFunction;
}
bool AnalyserModel::needMinFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedMinFunction;
}
bool AnalyserModel::needMaxFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedMaxFunction;
}
bool AnalyserModel::needSecFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedSecFunction;
}
bool AnalyserModel::needCscFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCscFunction;
}
bool AnalyserModel::needCotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCotFunction;
}
bool AnalyserModel::needSechFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedSechFunction;
}
bool AnalyserModel::needCschFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCschFunction;
}
bool AnalyserModel::needCothFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedCothFunction;
}
bool AnalyserModel::needAsecFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAsecFunction;
}
bool AnalyserModel::needAcscFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcscFunction;
}
bool AnalyserModel::needAcotFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcotFunction;
}
bool AnalyserModel::needAsechFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAsechFunction;
}
bool AnalyserModel::needAcschFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcschFunction;
}
bool AnalyserModel::needAcothFunction() const
{
if (!isValid()) {
return false;
}
return mPimpl->mNeedAcothFunction;
}
bool AnalyserModel::areEquivalentVariables(const VariablePtr &variable1,
const VariablePtr &variable2)
{
// We used to have a utilities method which implementation was:
//
// return (variable1 == variable2)
// || variable1->hasEquivalentVariable(variable2, true);
//
// However, a call to Variable::hasEquivalentVariable() can be time
// consuming. So, here, we stripped down the implementation of that method
// (and of others that it calls) and cache its results for future re-use.
if (variable1 == variable2) {
return true;
}
auto key = reinterpret_cast<intptr_t>(variable1.get()) * reinterpret_cast<intptr_t>(variable2.get());
auto cacheKey = mPimpl->mCachedEquivalentVariables.find(key);
if (cacheKey != mPimpl->mCachedEquivalentVariables.end()) {
return cacheKey->second;
}
std::vector<const Variable *> testedVariables;
bool res = mPimpl->haveEquivalentVariables(variable1.get(), variable2.get(), testedVariables);
mPimpl->mCachedEquivalentVariables[key] = res;
return res;
}
} // namespace libcellml
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
//////////////////////////////////////////////////////////////////////////////
//
// mapKeys
//
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_mapKeys)
{
mapKeys[key.GetPubKey()] = key.GetPrivKey();
mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
}
}
<commit_msg>CKeyStore::AddKey must return a boolean<commit_after>// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
//////////////////////////////////////////////////////////////////////////////
//
// mapKeys
//
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_mapKeys)
{
mapKeys[key.GetPubKey()] = key.GetPrivKey();
mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
}
return true;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_filter.hxx"
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
//============================ RASWriter ==================================
class RASWriter {
private:
SvStream* mpOStm;
USHORT mpOStmOldModus;
BOOL mbStatus;
BitmapReadAccess* mpAcc;
ULONG mnWidth, mnHeight;
USHORT mnColors, mnDepth;
ULONG mnRepCount;
BYTE mnRepVal;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
void ImplCallback( ULONG nCurrentYPos );
BOOL ImplWriteHeader();
void ImplWritePalette();
void ImplWriteBody();
void ImplPutByte( BYTE ); // RLE decoding
public:
RASWriter();
~RASWriter();
BOOL WriteRAS( const Graphic& rGraphic, SvStream& rRAS, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von RASWriter ==============================
RASWriter::RASWriter() :
mbStatus ( TRUE ),
mpAcc ( NULL ),
mnRepCount ( 0xffffffff )
{
}
// ------------------------------------------------------------------------
RASWriter::~RASWriter()
{
}
// ------------------------------------------------------------------------
void RASWriter::ImplCallback( ULONG nYPos )
{
if ( xStatusIndicator.is() )
xStatusIndicator->setValue( (USHORT)( ( 100 * nYPos ) / mnHeight ) );
}
// ------------------------------------------------------------------------
BOOL RASWriter::WriteRAS( const Graphic& rGraphic, SvStream& rRAS, FilterConfigItem* pFilterConfigItem)
{
Bitmap aBmp;
mpOStm = &rRAS;
if ( pFilterConfigItem )
{
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
rtl::OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
aBmp = aBmpEx.GetBitmap();
if ( aBmp.GetBitCount() == 4 )
aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
mnDepth = aBmp.GetBitCount();
// export code below only handles three discrete cases
mnDepth = mnDepth <= 1 ? 1 : mnDepth <= 8 ? 8 : 24;
mpAcc = aBmp.AcquireReadAccess();
if ( mpAcc )
{
mpOStmOldModus = mpOStm->GetNumberFormatInt();
mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
if ( ImplWriteHeader() )
{
if ( mnDepth <= 8 )
ImplWritePalette();
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = FALSE;
mpOStm->SetNumberFormatInt( mpOStmOldModus );
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
// ------------------------------------------------------------------------
BOOL RASWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnDepth <= 8 )
{
mnColors = mpAcc->GetPaletteEntryCount();
if (mnColors == 0)
mbStatus = FALSE;
}
if ( mbStatus && mnWidth && mnHeight && mnDepth )
{
*mpOStm << (UINT32)0x59a66a95 << (UINT32)mnWidth << (UINT32)mnHeight
<< (UINT32)mnDepth
<< (UINT32)(( ( ( ( mnWidth * mnDepth ) + 15 ) >> 4 ) << 1 ) * mnHeight)
<< (UINT32)2;
if ( mnDepth > 8 )
*mpOStm << (UINT32)0 << (UINT32)0;
else
{
*mpOStm << (UINT32)1 << (UINT32)( mnColors * 3 );
}
}
else mbStatus = FALSE;
return mbStatus;
}
// ------------------------------------------------------------------------
void RASWriter::ImplWritePalette()
{
USHORT i;
for ( i = 0; i < mnColors; *mpOStm << mpAcc->GetPaletteColor( i++ ).GetRed() ) ;
for ( i = 0; i < mnColors; *mpOStm << mpAcc->GetPaletteColor( i++ ).GetGreen() ) ;
for ( i = 0; i < mnColors; *mpOStm << mpAcc->GetPaletteColor( i++ ).GetBlue() ) ;
}
// ------------------------------------------------------------------------
void RASWriter::ImplWriteBody()
{
ULONG x, y;
if ( mnDepth == 24 )
{
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
BitmapColor aColor( mpAcc->GetPixel( y, x ) );
ImplPutByte( aColor.GetBlue() ); // Format ist BGR
ImplPutByte( aColor.GetGreen() );
ImplPutByte( aColor.GetRed() );
}
if ( x & 1 ) ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
else if ( mnDepth == 8 )
{
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
ImplPutByte ( mpAcc->GetPixel( y, x ) );
}
if ( x & 1 ) ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
else if ( mnDepth == 1 )
{
BYTE nDat = 0;
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
nDat = ( ( nDat << 1 ) | ( mpAcc->GetPixel ( y, x ) & 1 ) );
if ( ( x & 7 ) == 7 )
ImplPutByte( nDat );
}
if ( x & 7 )
ImplPutByte( sal::static_int_cast< BYTE >(nDat << ( ( ( x & 7 ) ^ 7 ) + 1)) );// write remaining bits
if (!( ( x - 1 ) & 0x8 ) )
ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
ImplPutByte( mnRepVal + 1 ); // end of RLE decoding
}
// ------------------------------------------------------------------------
void RASWriter::ImplPutByte( BYTE nPutThis )
{
if ( mnRepCount == 0xffffffff )
{
mnRepCount = 0;
mnRepVal = nPutThis;
}
else
{
if ( ( nPutThis == mnRepVal ) && ( mnRepCount != 0xff ) )
mnRepCount++;
else
{
if ( mnRepCount == 0 )
{
*mpOStm << (BYTE)mnRepVal;
if ( mnRepVal == 0x80 )
*mpOStm << (BYTE)0;
}
else
{
*mpOStm << (BYTE)0x80;
*mpOStm << (BYTE)mnRepCount;
*mpOStm << (BYTE)mnRepVal;
}
mnRepVal = nPutThis;
mnRepCount = 0;
}
}
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, BOOL )
{
RASWriter aRASWriter;
return aRASWriter.WriteRAS( rGraphic, rStream, pFilterConfigItem );
}
// ---------------
// - Win16 trash -
// ---------------
#ifdef WIN
static HINSTANCE hDLLInst = 0;
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
if ( nHeap )
UnlockData( 0 );
hDLLInst = hDLL;
return TRUE;
}
// ------------------------------------------------------------------------
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>no need for the pointer fetishism<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_filter.hxx"
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
//============================ RASWriter ==================================
class RASWriter {
private:
SvStream & m_rOStm;
USHORT mpOStmOldModus;
BOOL mbStatus;
BitmapReadAccess* mpAcc;
ULONG mnWidth, mnHeight;
USHORT mnColors, mnDepth;
ULONG mnRepCount;
BYTE mnRepVal;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
void ImplCallback( ULONG nCurrentYPos );
BOOL ImplWriteHeader();
void ImplWritePalette();
void ImplWriteBody();
void ImplPutByte( BYTE ); // RLE decoding
public:
RASWriter(SvStream &rStream);
~RASWriter();
BOOL WriteRAS( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von RASWriter ==============================
RASWriter::RASWriter(SvStream &rStream)
: m_rOStm(rStream)
, mbStatus(TRUE)
, mpAcc(NULL)
, mnRepCount( 0xffffffff )
{
}
// ------------------------------------------------------------------------
RASWriter::~RASWriter()
{
}
// ------------------------------------------------------------------------
void RASWriter::ImplCallback( ULONG nYPos )
{
if ( xStatusIndicator.is() )
xStatusIndicator->setValue( (USHORT)( ( 100 * nYPos ) / mnHeight ) );
}
// ------------------------------------------------------------------------
BOOL RASWriter::WriteRAS( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem)
{
Bitmap aBmp;
if ( pFilterConfigItem )
{
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
rtl::OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
aBmp = aBmpEx.GetBitmap();
if ( aBmp.GetBitCount() == 4 )
aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
mnDepth = aBmp.GetBitCount();
// export code below only handles three discrete cases
mnDepth = mnDepth <= 1 ? 1 : mnDepth <= 8 ? 8 : 24;
mpAcc = aBmp.AcquireReadAccess();
if ( mpAcc )
{
mpOStmOldModus = m_rOStm.GetNumberFormatInt();
m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
if ( ImplWriteHeader() )
{
if ( mnDepth <= 8 )
ImplWritePalette();
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = FALSE;
m_rOStm.SetNumberFormatInt( mpOStmOldModus );
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
// ------------------------------------------------------------------------
BOOL RASWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnDepth <= 8 )
{
mnColors = mpAcc->GetPaletteEntryCount();
if (mnColors == 0)
mbStatus = FALSE;
}
if ( mbStatus && mnWidth && mnHeight && mnDepth )
{
m_rOStm << (UINT32)0x59a66a95 << (UINT32)mnWidth << (UINT32)mnHeight
<< (UINT32)mnDepth
<< (UINT32)(( ( ( ( mnWidth * mnDepth ) + 15 ) >> 4 ) << 1 ) * mnHeight)
<< (UINT32)2;
if ( mnDepth > 8 )
m_rOStm << (UINT32)0 << (UINT32)0;
else
{
m_rOStm << (UINT32)1 << (UINT32)( mnColors * 3 );
}
}
else mbStatus = FALSE;
return mbStatus;
}
// ------------------------------------------------------------------------
void RASWriter::ImplWritePalette()
{
USHORT i;
for ( i = 0; i < mnColors; m_rOStm << mpAcc->GetPaletteColor( i++ ).GetRed() ) ;
for ( i = 0; i < mnColors; m_rOStm << mpAcc->GetPaletteColor( i++ ).GetGreen() ) ;
for ( i = 0; i < mnColors; m_rOStm << mpAcc->GetPaletteColor( i++ ).GetBlue() ) ;
}
// ------------------------------------------------------------------------
void RASWriter::ImplWriteBody()
{
ULONG x, y;
if ( mnDepth == 24 )
{
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
BitmapColor aColor( mpAcc->GetPixel( y, x ) );
ImplPutByte( aColor.GetBlue() ); // Format ist BGR
ImplPutByte( aColor.GetGreen() );
ImplPutByte( aColor.GetRed() );
}
if ( x & 1 ) ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
else if ( mnDepth == 8 )
{
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
ImplPutByte ( mpAcc->GetPixel( y, x ) );
}
if ( x & 1 ) ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
else if ( mnDepth == 1 )
{
BYTE nDat = 0;
for ( y = 0; y < mnHeight; y++ )
{
ImplCallback( y ); // processing output
for ( x = 0; x < mnWidth; x++ )
{
nDat = ( ( nDat << 1 ) | ( mpAcc->GetPixel ( y, x ) & 1 ) );
if ( ( x & 7 ) == 7 )
ImplPutByte( nDat );
}
if ( x & 7 )
ImplPutByte( sal::static_int_cast< BYTE >(nDat << ( ( ( x & 7 ) ^ 7 ) + 1)) );// write remaining bits
if (!( ( x - 1 ) & 0x8 ) )
ImplPutByte( 0 ); // WORD ALIGNMENT ???
}
}
ImplPutByte( mnRepVal + 1 ); // end of RLE decoding
}
// ------------------------------------------------------------------------
void RASWriter::ImplPutByte( BYTE nPutThis )
{
if ( mnRepCount == 0xffffffff )
{
mnRepCount = 0;
mnRepVal = nPutThis;
}
else
{
if ( ( nPutThis == mnRepVal ) && ( mnRepCount != 0xff ) )
mnRepCount++;
else
{
if ( mnRepCount == 0 )
{
m_rOStm << (BYTE)mnRepVal;
if ( mnRepVal == 0x80 )
m_rOStm << (BYTE)0;
}
else
{
m_rOStm << (BYTE)0x80;
m_rOStm << (BYTE)mnRepCount;
m_rOStm << (BYTE)mnRepVal;
}
mnRepVal = nPutThis;
mnRepCount = 0;
}
}
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, BOOL )
{
RASWriter aRASWriter(rStream);
return aRASWriter.WriteRAS( rGraphic, pFilterConfigItem );
}
// ---------------
// - Win16 trash -
// ---------------
#ifdef WIN
static HINSTANCE hDLLInst = 0;
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
if ( nHeap )
UnlockData( 0 );
hDLLInst = hDLL;
return TRUE;
}
// ------------------------------------------------------------------------
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "condor_common.h"
#include "directory.h"
#include "condor_debug.h"
#ifdef LINUX
bool isChildOf(const char *subdir, pid_t parent);
#endif
// Given a parent pid, find the first child pid of that parent pid
// by groveling through /proc
pid_t
findChildProc(pid_t parent) {
#ifdef LINUX
Directory d("/proc");
const char *subdir;
while ((subdir = d.Next())) {
// skip over all the non-pid subdirs of /proc (and 1)
int pid = atoi(subdir);
if (pid < 2) {
continue;
}
if (isChildOf(subdir, parent)) {
return pid;
}
}
return -1;
#else
return -1;
#endif
}
#ifdef LINUX
bool
isChildOf(const char *subdir, pid_t parent) {
int fd;
std::string fileName;
char buf[512];
buf[0] = '\0';
formatstr(fileName, "/proc/%s/stat", subdir);
fd = safe_open_wrapper(fileName.c_str(), O_RDONLY, 0666);
if (fd < 0) {
return false;
}
if (read(fd, buf, 511) < 0) {
close(fd);
return false;
}
close(fd);
int pid = 0;
int ppid = -1;
// Format of /proc/self/stat is
// pid program_name State ppid
int matched = sscanf(buf, "%d%*s%*s%d", &pid, &ppid);
if ((ppid == parent) && (matched > 0)) {
return true;
}
return false;
}
#endif
<commit_msg>Check return value of read #6992<commit_after>#include "condor_common.h"
#include "directory.h"
#include "condor_debug.h"
#ifdef LINUX
bool isChildOf(const char *subdir, pid_t parent);
#endif
// Given a parent pid, find the first child pid of that parent pid
// by groveling through /proc
pid_t
findChildProc(pid_t parent) {
#ifdef LINUX
Directory d("/proc");
const char *subdir;
while ((subdir = d.Next())) {
// skip over all the non-pid subdirs of /proc (and 1)
int pid = atoi(subdir);
if (pid < 2) {
continue;
}
if (isChildOf(subdir, parent)) {
return pid;
}
}
return -1;
#else
return -1;
#endif
}
#ifdef LINUX
bool
isChildOf(const char *subdir, pid_t parent) {
int fd;
std::string fileName;
char buf[512];
buf[0] = '\0';
formatstr(fileName, "/proc/%s/stat", subdir);
fd = safe_open_wrapper(fileName.c_str(), O_RDONLY, 0666);
if (fd < 0) {
return false;
}
ssize_t num_read = read(fd, buf, 511);
if (num_read < 5) { // minimum # of bytes for legal stat line
close(fd);
return false;
}
close(fd);
int pid = 0;
int ppid = -1;
// Format of /proc/self/stat is
// pid program_name State ppid
int matched = sscanf(buf, "%d%*s%*s%d", &pid, &ppid);
if ((ppid == parent) && (matched > 0)) {
return true;
}
return false;
}
#endif
<|endoftext|> |
<commit_before>/*
* JPetCmdParser.cpp
*
*
* Created by Karol Stola on 13-11-22.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetCmdParser.h"
//#ifndef __CINT__ // guard against being included into dictionary
JPetCmdParser::JPetCmdParser()
: fOptDescriptions("Allowed options")
{
vector<int> tmp;
tmp.push_back(-1);
tmp.push_back(-1);
fOptDescriptions.add_options()
("help,h", "produce help message")
("type,t", po::value<string>()->required(), "type of file: hld or root")
("file,f", po::value<string>()->required(), "File to open")
("range,r", po::value< vector<int> >()->multitoken()->default_value(tmp,""), "Range of events to process.")
("param,p", po::value<string>(), "File with TRB numbers.")
;
}
void JPetCmdParser::parse(int argc, char** argv){
try{
if (argc == 1){
cout << "No options provided." << endl;
cout << fOptDescriptions << "\n";
exit(0);
}
po::store(po::parse_command_line(argc, argv, fOptDescriptions), fVariablesMap);
/* print out help */
if (fVariablesMap.count("help")) {
cout << fOptDescriptions << "\n";
exit(0);
}
po::notify(fVariablesMap);
/* parse range of events */
if (fVariablesMap.count("range")) {
if (fVariablesMap["range"].as< vector<int> >().size() != 2) {
cerr << "Wrong number of bounds in range: " << fVariablesMap["range"].as< vector<int> >().size() << endl;
exit(-1);
}
if (
fVariablesMap["range"].as< vector<int> >()[0]
> fVariablesMap["range"].as< vector<int> >()[1])
{
cerr << "Wrong range of events." << endl;
exit(-1);
}
}
/* check if correct file type was provided */
if (
fVariablesMap["type"].as <string>().compare("hld")
&& fVariablesMap["type"].as <string>().compare("root")
)
{
cerr << "Wrong type of file: " << fVariablesMap["type"].as< string >() << endl;
cerr << "Possible options: hld or root" << endl;
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
return;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
}
//#endif /* __CINT__ */<commit_msg>drobniutka poprawka parsera<commit_after>/*
* JPetCmdParser.cpp
*
*
* Created by Karol Stola on 13-11-22.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetCmdParser.h"
//#ifndef __CINT__ // guard against being included into dictionary
JPetCmdParser::JPetCmdParser()
: fOptDescriptions("Allowed options")
{
vector<int> tmp;
tmp.push_back(-1);
tmp.push_back(-1);
fOptDescriptions.add_options()
("help,h", "produce help message")
("type,t", po::value<string>()->required(), "type of file: hld or root")
("file,f", po::value<string>()->required(), "File to open")
("range,r", po::value< vector<int> >()->multitoken()->default_value(tmp,""), "Range of events to process.")
("param,p", po::value<string>(), "File with TRB numbers.")
;
}
void JPetCmdParser::parse(int argc, char** argv){
try{
if (argc == 1){
cout << "No options provided." << endl;
cout << fOptDescriptions << "\n";
exit(0);
}
po::store(po::parse_command_line(argc, argv, fOptDescriptions), fVariablesMap);
/* print out help */
if (fVariablesMap.count("help")) {
cout << fOptDescriptions << "\n";
exit(0);
}
po::notify(fVariablesMap);
/* parse range of events */
if (fVariablesMap.count("range")) {
if (fVariablesMap["range"].as< vector<int> >().size() != 2) {
cerr << "Wrong number of bounds in range: " << fVariablesMap["range"].as< vector<int> >().size() << endl;
exit(-1);
}
if (
fVariablesMap["range"].as< vector<int> >()[0]
> fVariablesMap["range"].as< vector<int> >()[1])
{
cerr << "Wrong range of events." << endl;
exit(-1);
}
}
/* check if correct file type was provided */
if (
fVariablesMap["type"].as <string>().compare("hld")
&& fVariablesMap["type"].as <string>().compare("root")
)
{
cerr << "Wrong type of file: " << fVariablesMap["type"].as< string >() << endl;
cerr << "Possible options: hld or root" << endl;
exit(-1);
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
return;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
}
//#endif /* __CINT__ */<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <arith_uint256.h>
#include <uint256.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <stdio.h>
#include <string.h>
template <unsigned int BITS>
base_uint<BITS>::base_uint(const std::string& str)
{
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
SetHex(str);
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator<<=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++) {
if (i + k + 1 < WIDTH && shift != 0)
pn[i + k + 1] |= (a.pn[i] >> (32 - shift));
if (i + k < WIDTH)
pn[i + k] |= (a.pn[i] << shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator>>=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++) {
if (i - k - 1 >= 0 && shift != 0)
pn[i - k - 1] |= (a.pn[i] << (32 - shift));
if (i - k >= 0)
pn[i - k] |= (a.pn[i] >> shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++) {
uint64_t n = carry + (uint64_t)b32 * pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b)
{
base_uint<BITS> a = *this;
*this = 0;
for (int j = 0; j < WIDTH; j++) {
uint64_t carry = 0;
for (int i = 0; i + j < WIDTH; i++) {
uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i];
pn[i + j] = n & 0xffffffff;
carry = n >> 32;
}
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator/=(const base_uint& b)
{
base_uint<BITS> div = b; // make a copy, so we can shift.
base_uint<BITS> num = *this; // make a copy, so we can subtract.
*this = 0; // the quotient.
int num_bits = num.bits();
int div_bits = div.bits();
if (div_bits == 0)
throw uint_error("Division by zero");
if (div_bits > num_bits) // the result is certainly 0.
return *this;
int shift = num_bits - div_bits;
div <<= shift; // shift so that div and num align.
while (shift >= 0) {
if (num >= div) {
num -= div;
pn[shift / 32] |= (1 << (shift & 31)); // set a bit of the result.
}
div >>= 1; // shift back.
shift--;
}
// num now contains the remainder of the division.
return *this;
}
template <unsigned int BITS>
int base_uint<BITS>::CompareTo(const base_uint<BITS>& b) const
{
for (int i = WIDTH - 1; i >= 0; i--) {
if (pn[i] < b.pn[i])
return -1;
if (pn[i] > b.pn[i])
return 1;
}
return 0;
}
template <unsigned int BITS>
bool base_uint<BITS>::EqualTo(uint64_t b) const
{
for (int i = WIDTH - 1; i >= 2; i--) {
if (pn[i])
return false;
}
if (pn[1] != (b >> 32))
return false;
if (pn[0] != (b & 0xfffffffful))
return false;
return true;
}
template <unsigned int BITS>
double base_uint<BITS>::getdouble() const
{
double ret = 0.0;
double fact = 1.0;
for (int i = 0; i < WIDTH; i++) {
ret += fact * pn[i];
fact *= 4294967296.0;
}
return ret;
}
template <unsigned int BITS>
std::string base_uint<BITS>::GetHex() const
{
return ArithToUint256(*this).GetHex();
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const char* psz)
{
*this = UintToArith256(uint256S(psz));
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const std::string& str)
{
SetHex(str.c_str());
}
template <unsigned int BITS>
std::string base_uint<BITS>::ToString() const
{
return (GetHex());
}
template <unsigned int BITS>
unsigned int base_uint<BITS>::bits() const
{
for (int pos = WIDTH - 1; pos >= 0; pos--) {
if (pn[pos]) {
for (int nbits = 31; nbits > 0; nbits--) {
if (pn[pos] & 1 << nbits)
return 32 * pos + nbits + 1;
}
return 32 * pos + 1;
}
}
return 0;
}
// Explicit instantiations for base_uint<256>
template base_uint<256>::base_uint(const std::string&);
template base_uint<256>& base_uint<256>::operator<<=(unsigned int);
template base_uint<256>& base_uint<256>::operator>>=(unsigned int);
template base_uint<256>& base_uint<256>::operator*=(uint32_t b32);
template base_uint<256>& base_uint<256>::operator*=(const base_uint<256>& b);
template base_uint<256>& base_uint<256>::operator/=(const base_uint<256>& b);
template int base_uint<256>::CompareTo(const base_uint<256>&) const;
template bool base_uint<256>::EqualTo(uint64_t) const;
template double base_uint<256>::getdouble() const;
template std::string base_uint<256>::GetHex() const;
template std::string base_uint<256>::ToString() const;
template void base_uint<256>::SetHex(const char*);
template void base_uint<256>::SetHex(const std::string&);
template unsigned int base_uint<256>::bits() const;
// This implementation directly uses shifts instead of going
// through an intermediate MPI representation.
arith_uint256& arith_uint256::SetCompact(uint32_t nCompact, bool* pfNegative, bool* pfOverflow)
{
int nSize = nCompact >> 24;
uint32_t nWord = nCompact & 0x007fffff;
if (nSize <= 3) {
nWord >>= 8 * (3 - nSize);
*this = nWord;
} else {
*this = nWord;
*this <<= 8 * (nSize - 3);
}
if (pfNegative)
*pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0;
if (pfOverflow)
*pfOverflow = nWord != 0 && ((nSize > 34) ||
(nWord > 0xff && nSize > 33) ||
(nWord > 0xffff && nSize > 32));
return *this;
}
uint32_t arith_uint256::GetCompact(bool fNegative) const
{
int nSize = (bits() + 7) / 8;
uint32_t nCompact = 0;
if (nSize <= 3) {
nCompact = GetLow64() << 8 * (3 - nSize);
} else {
arith_uint256 bn = *this >> 8 * (nSize - 3);
nCompact = bn.GetLow64();
}
// The 0x00800000 bit denotes the sign.
// Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
if (nCompact & 0x00800000) {
nCompact >>= 8;
nSize++;
}
assert((nCompact & ~0x007fffff) == 0);
assert(nSize < 256);
nCompact |= nSize << 24;
nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0);
return nCompact;
}
uint256 ArithToUint256(const arith_uint256 &a)
{
uint256 b;
for(int x=0; x<a.WIDTH; ++x)
WriteLE32(b.begin() + x*4, a.pn[x]);
return b;
}
arith_uint256 UintToArith256(const uint256 &a)
{
arith_uint256 b;
for(int x=0; x<b.WIDTH; ++x)
b.pn[x] = ReadLE32(a.begin() + x*4);
return b;
}
<commit_msg>[arith_uint256] Do not destroy *this content if passed-in operator may reference it<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <arith_uint256.h>
#include <uint256.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <stdio.h>
#include <string.h>
template <unsigned int BITS>
base_uint<BITS>::base_uint(const std::string& str)
{
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
SetHex(str);
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator<<=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++) {
if (i + k + 1 < WIDTH && shift != 0)
pn[i + k + 1] |= (a.pn[i] >> (32 - shift));
if (i + k < WIDTH)
pn[i + k] |= (a.pn[i] << shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator>>=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++) {
if (i - k - 1 >= 0 && shift != 0)
pn[i - k - 1] |= (a.pn[i] << (32 - shift));
if (i - k >= 0)
pn[i - k] |= (a.pn[i] >> shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++) {
uint64_t n = carry + (uint64_t)b32 * pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b)
{
base_uint<BITS> a;
for (int j = 0; j < WIDTH; j++) {
uint64_t carry = 0;
for (int i = 0; i + j < WIDTH; i++) {
uint64_t n = carry + a.pn[i + j] + (uint64_t)pn[j] * b.pn[i];
a.pn[i + j] = n & 0xffffffff;
carry = n >> 32;
}
}
*this = a;
return *this;
}
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator/=(const base_uint& b)
{
base_uint<BITS> div = b; // make a copy, so we can shift.
base_uint<BITS> num = *this; // make a copy, so we can subtract.
*this = 0; // the quotient.
int num_bits = num.bits();
int div_bits = div.bits();
if (div_bits == 0)
throw uint_error("Division by zero");
if (div_bits > num_bits) // the result is certainly 0.
return *this;
int shift = num_bits - div_bits;
div <<= shift; // shift so that div and num align.
while (shift >= 0) {
if (num >= div) {
num -= div;
pn[shift / 32] |= (1 << (shift & 31)); // set a bit of the result.
}
div >>= 1; // shift back.
shift--;
}
// num now contains the remainder of the division.
return *this;
}
template <unsigned int BITS>
int base_uint<BITS>::CompareTo(const base_uint<BITS>& b) const
{
for (int i = WIDTH - 1; i >= 0; i--) {
if (pn[i] < b.pn[i])
return -1;
if (pn[i] > b.pn[i])
return 1;
}
return 0;
}
template <unsigned int BITS>
bool base_uint<BITS>::EqualTo(uint64_t b) const
{
for (int i = WIDTH - 1; i >= 2; i--) {
if (pn[i])
return false;
}
if (pn[1] != (b >> 32))
return false;
if (pn[0] != (b & 0xfffffffful))
return false;
return true;
}
template <unsigned int BITS>
double base_uint<BITS>::getdouble() const
{
double ret = 0.0;
double fact = 1.0;
for (int i = 0; i < WIDTH; i++) {
ret += fact * pn[i];
fact *= 4294967296.0;
}
return ret;
}
template <unsigned int BITS>
std::string base_uint<BITS>::GetHex() const
{
return ArithToUint256(*this).GetHex();
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const char* psz)
{
*this = UintToArith256(uint256S(psz));
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const std::string& str)
{
SetHex(str.c_str());
}
template <unsigned int BITS>
std::string base_uint<BITS>::ToString() const
{
return (GetHex());
}
template <unsigned int BITS>
unsigned int base_uint<BITS>::bits() const
{
for (int pos = WIDTH - 1; pos >= 0; pos--) {
if (pn[pos]) {
for (int nbits = 31; nbits > 0; nbits--) {
if (pn[pos] & 1 << nbits)
return 32 * pos + nbits + 1;
}
return 32 * pos + 1;
}
}
return 0;
}
// Explicit instantiations for base_uint<256>
template base_uint<256>::base_uint(const std::string&);
template base_uint<256>& base_uint<256>::operator<<=(unsigned int);
template base_uint<256>& base_uint<256>::operator>>=(unsigned int);
template base_uint<256>& base_uint<256>::operator*=(uint32_t b32);
template base_uint<256>& base_uint<256>::operator*=(const base_uint<256>& b);
template base_uint<256>& base_uint<256>::operator/=(const base_uint<256>& b);
template int base_uint<256>::CompareTo(const base_uint<256>&) const;
template bool base_uint<256>::EqualTo(uint64_t) const;
template double base_uint<256>::getdouble() const;
template std::string base_uint<256>::GetHex() const;
template std::string base_uint<256>::ToString() const;
template void base_uint<256>::SetHex(const char*);
template void base_uint<256>::SetHex(const std::string&);
template unsigned int base_uint<256>::bits() const;
// This implementation directly uses shifts instead of going
// through an intermediate MPI representation.
arith_uint256& arith_uint256::SetCompact(uint32_t nCompact, bool* pfNegative, bool* pfOverflow)
{
int nSize = nCompact >> 24;
uint32_t nWord = nCompact & 0x007fffff;
if (nSize <= 3) {
nWord >>= 8 * (3 - nSize);
*this = nWord;
} else {
*this = nWord;
*this <<= 8 * (nSize - 3);
}
if (pfNegative)
*pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0;
if (pfOverflow)
*pfOverflow = nWord != 0 && ((nSize > 34) ||
(nWord > 0xff && nSize > 33) ||
(nWord > 0xffff && nSize > 32));
return *this;
}
uint32_t arith_uint256::GetCompact(bool fNegative) const
{
int nSize = (bits() + 7) / 8;
uint32_t nCompact = 0;
if (nSize <= 3) {
nCompact = GetLow64() << 8 * (3 - nSize);
} else {
arith_uint256 bn = *this >> 8 * (nSize - 3);
nCompact = bn.GetLow64();
}
// The 0x00800000 bit denotes the sign.
// Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
if (nCompact & 0x00800000) {
nCompact >>= 8;
nSize++;
}
assert((nCompact & ~0x007fffff) == 0);
assert(nSize < 256);
nCompact |= nSize << 24;
nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0);
return nCompact;
}
uint256 ArithToUint256(const arith_uint256 &a)
{
uint256 b;
for(int x=0; x<a.WIDTH; ++x)
WriteLE32(b.begin() + x*4, a.pn[x]);
return b;
}
arith_uint256 UintToArith256(const uint256 &a)
{
arith_uint256 b;
for(int x=0; x<b.WIDTH; ++x)
b.pn[x] = ReadLE32(a.begin() + x*4);
return b;
}
<|endoftext|> |
<commit_before>///
/// @file pi_deleglise_rivat2.cpp
/// @brief Implementation of the Deleglise-Rivat prime counting
/// algorithm. Compared to pi_deleglise_rivat1.cpp this version
/// uses compression (FactorTable & PiTable) to reduce the
/// memory usage.
///
/// This implementation is based on the paper:
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006,
/// pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <S1.hpp>
#include <tos_counters.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T>
void cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve,
T& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Calculate the contribution of the trivial leaves.
///
int64_t S2_trivial(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes)
{
int64_t pi_y = pi(y);
int64_t pi_sqrtz = pi(min(isqrt(z), y));
int64_t S2_result = 0;
// Find all trivial leaves: n = primes[b] * primes[l]
// which satisfy phi(x / n), b - 1) = 1
for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++)
{
int64_t prime = primes[b];
S2_result += pi_y - pi(max(x / (prime * prime), prime));
}
return S2_result;
}
/// Calculate the contribution of the trivial leaves, the clustered
/// easy leaves and the sparse easy leaves.
///
int64_t S2_easy(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes)
{
int64_t pi_sqrty = pi(isqrt(y));
int64_t pi_x13 = pi(iroot<3>(x));
int64_t S2_result = 0;
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
int64_t prime = primes[b];
int64_t min_trivial_leaf = x / (prime * prime);
int64_t min_clustered_easy_leaf = isqrt(x / prime);
int64_t min_sparse_easy_leaf = z / prime;
int64_t min_hard_leaf = max(y / prime, prime);
min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf);
min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf);
int64_t l = pi(min(min_trivial_leaf, y));
// Find all clustered easy leaves:
// x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (primes[l] > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
int64_t phi_xn = pi(xn) - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t xm = max(x / m, min_clustered_easy_leaf);
int64_t l2 = pi(xm);
S2_result += phi_xn * (l - l2);
l = l2;
}
// Find all sparse easy leaves:
// x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
S2_result += pi(xn) - b + 2;
}
}
return S2_result;
}
/// Calculate the contribution of the special leaves which require
/// a sieve (in order to reduce the memory usage).
///
int64_t S2_sieve(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors)
{
int64_t limit = z + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t pi_sqrty = pi(isqrt(y));
int64_t pi_sqrtz = pi(min(isqrt(z), y));
int64_t S2_result = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next(primes.begin(), primes.end());
vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 2;
sieve.fill(low, high);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime * 2)
sieve.unset(k - low);
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b <= pi_sqrty; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_result -= factors.mu(m) * phi_xn;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_sqrtz; b++)
{
int64_t prime = primes[b];
int64_t l = pi(min3(x / (prime * low), z / prime, y));
int64_t min_hard_leaf = max3(x / (prime * high), y / prime, prime);
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_result += phi_xn;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_result;
}
/// Calculate the contribution of the special leaves.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t c,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors)
{
int64_t S2_total = 0;
PiTable pi(y);
S2_total += S2_trivial(x, y, z, c, pi, primes);
S2_total += S2_easy(x, y, z, c, pi, primes);
S2_total += S2_sieve(x, y, z, c, pi, primes, factors);
return S2_total;
}
/// alpha is a tuning factor which should grow like (log(x))^3
/// for the Deleglise-Rivat prime counting algorithm.
///
double compute_alpha(int64_t x)
{
double d = (double) x;
double alpha = log(d) * log(d) * log(d) / 1200;
return in_between(1, alpha, iroot<6>(x));
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat2(int64_t x)
{
if (x < 2)
return 0;
double alpha = compute_alpha(x);
int64_t y = (int64_t) (alpha * iroot<3>(x));
int64_t z = x / y;
int64_t p2 = P2(x, y, 1);
vector<int32_t> primes = generate_primes(y);
FactorTable<uint16_t> factors(y);
int64_t pi_y = pi_bsearch(primes, y);
int64_t c = min(pi_y, PhiTiny::max_a());
int64_t s1 = S1(x, y, c, primes[c], factors, 1);
int64_t s2 = S2(x, y, z, c, primes, factors);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<commit_msg>Update pi_deleglise_rivat2.cpp<commit_after>///
/// @file pi_deleglise_rivat2.cpp
/// @brief Implementation of the Deleglise-Rivat prime counting
/// algorithm. Compared to pi_deleglise_rivat1.cpp this version
/// uses compression (FactorTable & PiTable) to reduce the
/// memory usage.
///
/// This implementation is based on the paper:
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006,
/// pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <S1.hpp>
#include <tos_counters.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T>
void cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve,
T& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Calculate the contribution of the trivial leaves.
///
int64_t S2_trivial(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes)
{
int64_t pi_y = pi(y);
int64_t pi_sqrtz = pi(min(isqrt(z), y));
int64_t S2_result = 0;
// Find all trivial leaves: n = primes[b] * primes[l]
// which satisfy phi(x / n), b - 1) = 1
for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++)
{
int64_t prime = primes[b];
S2_result += pi_y - pi(max(x / (prime * prime), prime));
}
return S2_result;
}
/// Calculate the contribution of the clustered easy
/// leaves and the sparse easy leaves.
///
int64_t S2_easy(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes)
{
int64_t pi_sqrty = pi(isqrt(y));
int64_t pi_x13 = pi(iroot<3>(x));
int64_t S2_result = 0;
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
int64_t prime = primes[b];
int64_t min_trivial_leaf = x / (prime * prime);
int64_t min_clustered_easy_leaf = isqrt(x / prime);
int64_t min_sparse_easy_leaf = z / prime;
int64_t min_hard_leaf = max(y / prime, prime);
min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf);
min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf);
int64_t l = pi(min(min_trivial_leaf, y));
// Find all clustered easy leaves:
// x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (primes[l] > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
int64_t phi_xn = pi(xn) - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t xm = max(x / m, min_clustered_easy_leaf);
int64_t l2 = pi(xm);
S2_result += phi_xn * (l - l2);
l = l2;
}
// Find all sparse easy leaves:
// x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
S2_result += pi(xn) - b + 2;
}
}
return S2_result;
}
/// Calculate the contribution of the special leaves which require
/// a sieve (in order to reduce the memory usage).
///
int64_t S2_sieve(int64_t x,
int64_t y,
int64_t z,
int64_t c,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors)
{
int64_t limit = z + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t pi_sqrty = pi(isqrt(y));
int64_t pi_sqrtz = pi(min(isqrt(z), y));
int64_t S2_result = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next(primes.begin(), primes.end());
vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 2;
sieve.fill(low, high);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime * 2)
sieve.unset(k - low);
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b <= pi_sqrty; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_result -= factors.mu(m) * phi_xn;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_sqrtz; b++)
{
int64_t prime = primes[b];
int64_t l = pi(min3(x / (prime * low), z / prime, y));
int64_t min_hard_leaf = max3(x / (prime * high), y / prime, prime);
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_result += phi_xn;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_result;
}
/// Calculate the contribution of the special leaves.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t c,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors)
{
int64_t S2_total = 0;
PiTable pi(y);
S2_total += S2_trivial(x, y, z, c, pi, primes);
S2_total += S2_easy(x, y, z, c, pi, primes);
S2_total += S2_sieve(x, y, z, c, pi, primes, factors);
return S2_total;
}
/// alpha is a tuning factor which should grow like (log(x))^3
/// for the Deleglise-Rivat prime counting algorithm.
///
double compute_alpha(int64_t x)
{
double d = (double) x;
double alpha = log(d) * log(d) * log(d) / 1200;
return in_between(1, alpha, iroot<6>(x));
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat2(int64_t x)
{
if (x < 2)
return 0;
double alpha = compute_alpha(x);
int64_t y = (int64_t) (alpha * iroot<3>(x));
int64_t z = x / y;
int64_t p2 = P2(x, y, 1);
vector<int32_t> primes = generate_primes(y);
FactorTable<uint16_t> factors(y);
int64_t pi_y = pi_bsearch(primes, y);
int64_t c = min(pi_y, PhiTiny::max_a());
int64_t s1 = S1(x, y, c, primes[c], factors, 1);
int64_t s2 = S2(x, y, z, c, primes, factors);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<|endoftext|> |
<commit_before>/**
* @file grAdapter.cc
* @author Konrad Zemek
* @copyright (C) 2014 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "auth/grAdapter.h"
#include "auth/authException.h"
#include "config.h"
#include "context.h"
#include "logging.h"
#include <boost/algorithm/string.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <json11.hpp>
#include <array>
#include <chrono>
#include <fstream>
#include <istream>
#include <ostream>
#include <sstream>
using namespace std::literals::chrono_literals;
namespace one {
namespace client {
static constexpr const char *OPENID_CLIENT_TOKENS_ENDPOINT =
"/openid/client/tokens";
namespace auth {
GRAdapter::GRAdapter(std::string clientName,
boost::filesystem::path userDataDir, std::string hostname,
const unsigned int port, const bool checkCertificate)
: m_clientName{std::move(clientName)}
, m_userDataDir{std::move(userDataDir)}
, m_hostname{std::move(hostname)}
, m_port{port}
, m_checkCertificate{checkCertificate}
{
}
boost::optional<TokenAuthDetails> GRAdapter::retrieveToken() const
{
const auto accessTokenFile = tokenFilePath();
boost::system::error_code ec;
const auto exists = boost::filesystem::exists(accessTokenFile, ec);
if (ec || !exists) {
LOG(INFO) << "No previously saved authorization details exist under "
"path " << accessTokenFile.string();
return {};
}
boost::filesystem::ifstream stream{accessTokenFile};
TokenAuthDetails auth;
stream >> auth;
if (!stream) {
LOG(WARNING) << "Failed to retrieve authorization details from "
<< accessTokenFile.string();
return {};
}
if (auth.expirationTime() < std::chrono::system_clock::now() + 1min) {
LOG(INFO) << "Saved Access Token expired. Refreshing";
try {
return refreshAccess(auth);
}
catch (const BadAccess &e) {
LOG(WARNING) << "Authorization error: " << e.what();
return {}; // Try with new credentials
}
}
return auth;
}
TokenAuthDetails GRAdapter::exchangeCode(const std::string &code) const
{
using namespace json11;
LOG(INFO) << "Exchanging OpenID Authorization Code for authorization "
"details. Identifying as '" << m_clientName << "'";
const auto content =
Json{Json::object{{"grant_type", "authorization_code"}, {"code", code},
{"client_name", m_clientName}}}.dump();
return communicate(content);
}
TokenAuthDetails GRAdapter::refreshAccess(const TokenAuthDetails &details) const
{
using namespace json11;
LOG(INFO) << "Refreshing OpenID Access Token";
const auto content =
Json{Json::object{{"grant_type", "refresh_token"},
{"refresh_token", details.refreshToken()}}}.dump();
return communicate(content);
}
TokenAuthDetails GRAdapter::communicate(const std::string &content) const
{
boost::asio::io_service ioService;
const auto socket = connect(ioService);
requestToken(content, *socket);
const auto response = getResponse(*socket);
return parseToken(response);
}
void GRAdapter::requestToken(
const std::string &content, GRAdapter::Socket &socket) const
{
boost::asio::streambuf request;
std::ostream requestStream(&request);
requestStream << "POST " << OPENID_CLIENT_TOKENS_ENDPOINT << " HTTP/1.1\r\n"
<< "Host: " << m_hostname << ":" << m_port << "\r\n"
<< "User-Agent: oneclient\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << content.size() << "\r\n"
<< "\r\n" << content;
requestStream.flush();
const auto requestSize = request.size();
const auto writtenSize = boost::asio::write(socket, request);
if (writtenSize != requestSize)
throw AuthException{"error while sending a request"};
}
std::string GRAdapter::getResponse(GRAdapter::Socket &socket) const
{
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
std::istream responseStream(&response);
std::string httpVersion;
unsigned int statusCode;
std::string statusMessage;
responseStream >> httpVersion >> statusCode;
std::getline(responseStream, statusMessage);
if (!responseStream || !boost::algorithm::starts_with(httpVersion, "HTTP/"))
throw AuthException{"malformed response headers"};
const auto headersSize =
boost::asio::read_until(socket, response, "\r\n\r\n");
response.consume(headersSize);
boost::system::error_code ec;
boost::asio::read(socket, response, boost::asio::transfer_all(), ec);
if (ec != boost::asio::error::eof)
throw AuthException{"malformed response: " + ec.message()};
std::istreambuf_iterator<char> eos;
std::string content{std::istreambuf_iterator<char>{responseStream}, eos};
if (statusCode >= 400 && statusCode <= 499)
throw BadAccess{"invalid data used to access Global Registry. "
"Status: " +
std::to_string(statusCode) + ". Response: '" + content + "'"};
if (statusCode != 200)
throw AuthException{"Global Registry responded with non-ok code " +
std::to_string(statusCode) + ". Response: '" + content +
"'"};
return content;
}
TokenAuthDetails GRAdapter::parseToken(const std::string &response) const
{
std::string err;
const auto json = json11::Json::parse(response, err);
if (!err.empty())
throw AuthException{"malformed JSON response: " + err};
const auto accessToken = json["access_token"].string_value();
const auto refreshToken = json["refresh_token"].string_value();
const auto jwt = json["id_token"].string_value();
const auto expiresIn = json["expires_in"].int_value();
using unbase = boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<
std::string::const_iterator>,
8, 6>;
std::vector<std::string> items;
boost::algorithm::split(items, jwt, boost::is_any_of("."));
const std::string idTokenRaw{
unbase{items[1].begin()}, unbase{items[1].end()}};
const auto idTokenJson = json11::Json::parse(idTokenRaw, err);
if (!err.empty())
throw AuthException{"malformed id_token: " + err};
TokenAuthDetails auth{accessToken, refreshToken,
idTokenJson["sub"].string_value(), expiresIn};
boost::filesystem::ofstream stream{tokenFilePath(), std::ios_base::trunc};
stream << auth;
if (!stream)
LOG(WARNING) << "Failed to save authorization details to a file: "
<< tokenFilePath().string();
return auth;
}
std::unique_ptr<GRAdapter::Socket> GRAdapter::connect(
boost::asio::io_service &ioService) const
{
namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;
tcp::resolver resolver{ioService};
tcp::resolver::query query{m_hostname, std::to_string(m_port),
boost::asio::ip::resolver_query_base::numeric_service};
auto iterator = resolver.resolve(query);
ssl::context ctx{ssl::context::method::tlsv12_client};
ctx.set_default_verify_paths();
auto socket = std::make_unique<Socket>(ioService, ctx);
socket->set_verify_mode(m_checkCertificate ? boost::asio::ssl::verify_peer
: boost::asio::ssl::verify_none);
socket->set_verify_callback(ssl::rfc2818_verification{m_hostname});
boost::asio::connect(socket->lowest_layer(), iterator);
socket->lowest_layer().set_option(tcp::no_delay(true));
socket->handshake(ssl::stream_base::client);
return socket;
}
boost::filesystem::path GRAdapter::tokenFilePath() const
{
return m_userDataDir / "accessToken";
}
} // namespace auth
} // namespace client
} // namespace one
<commit_msg>VFS-1142 Remove unused config.h import.<commit_after>/**
* @file grAdapter.cc
* @author Konrad Zemek
* @copyright (C) 2014 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "auth/grAdapter.h"
#include "auth/authException.h"
#include "context.h"
#include "logging.h"
#include <boost/algorithm/string.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <json11.hpp>
#include <array>
#include <chrono>
#include <fstream>
#include <istream>
#include <ostream>
#include <sstream>
using namespace std::literals::chrono_literals;
namespace one {
namespace client {
static constexpr const char *OPENID_CLIENT_TOKENS_ENDPOINT =
"/openid/client/tokens";
namespace auth {
GRAdapter::GRAdapter(std::string clientName,
boost::filesystem::path userDataDir, std::string hostname,
const unsigned int port, const bool checkCertificate)
: m_clientName{std::move(clientName)}
, m_userDataDir{std::move(userDataDir)}
, m_hostname{std::move(hostname)}
, m_port{port}
, m_checkCertificate{checkCertificate}
{
}
boost::optional<TokenAuthDetails> GRAdapter::retrieveToken() const
{
const auto accessTokenFile = tokenFilePath();
boost::system::error_code ec;
const auto exists = boost::filesystem::exists(accessTokenFile, ec);
if (ec || !exists) {
LOG(INFO) << "No previously saved authorization details exist under "
"path " << accessTokenFile.string();
return {};
}
boost::filesystem::ifstream stream{accessTokenFile};
TokenAuthDetails auth;
stream >> auth;
if (!stream) {
LOG(WARNING) << "Failed to retrieve authorization details from "
<< accessTokenFile.string();
return {};
}
if (auth.expirationTime() < std::chrono::system_clock::now() + 1min) {
LOG(INFO) << "Saved Access Token expired. Refreshing";
try {
return refreshAccess(auth);
}
catch (const BadAccess &e) {
LOG(WARNING) << "Authorization error: " << e.what();
return {}; // Try with new credentials
}
}
return auth;
}
TokenAuthDetails GRAdapter::exchangeCode(const std::string &code) const
{
using namespace json11;
LOG(INFO) << "Exchanging OpenID Authorization Code for authorization "
"details. Identifying as '" << m_clientName << "'";
const auto content =
Json{Json::object{{"grant_type", "authorization_code"}, {"code", code},
{"client_name", m_clientName}}}.dump();
return communicate(content);
}
TokenAuthDetails GRAdapter::refreshAccess(const TokenAuthDetails &details) const
{
using namespace json11;
LOG(INFO) << "Refreshing OpenID Access Token";
const auto content =
Json{Json::object{{"grant_type", "refresh_token"},
{"refresh_token", details.refreshToken()}}}.dump();
return communicate(content);
}
TokenAuthDetails GRAdapter::communicate(const std::string &content) const
{
boost::asio::io_service ioService;
const auto socket = connect(ioService);
requestToken(content, *socket);
const auto response = getResponse(*socket);
return parseToken(response);
}
void GRAdapter::requestToken(
const std::string &content, GRAdapter::Socket &socket) const
{
boost::asio::streambuf request;
std::ostream requestStream(&request);
requestStream << "POST " << OPENID_CLIENT_TOKENS_ENDPOINT << " HTTP/1.1\r\n"
<< "Host: " << m_hostname << ":" << m_port << "\r\n"
<< "User-Agent: oneclient\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << content.size() << "\r\n"
<< "\r\n" << content;
requestStream.flush();
const auto requestSize = request.size();
const auto writtenSize = boost::asio::write(socket, request);
if (writtenSize != requestSize)
throw AuthException{"error while sending a request"};
}
std::string GRAdapter::getResponse(GRAdapter::Socket &socket) const
{
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
std::istream responseStream(&response);
std::string httpVersion;
unsigned int statusCode;
std::string statusMessage;
responseStream >> httpVersion >> statusCode;
std::getline(responseStream, statusMessage);
if (!responseStream || !boost::algorithm::starts_with(httpVersion, "HTTP/"))
throw AuthException{"malformed response headers"};
const auto headersSize =
boost::asio::read_until(socket, response, "\r\n\r\n");
response.consume(headersSize);
boost::system::error_code ec;
boost::asio::read(socket, response, boost::asio::transfer_all(), ec);
if (ec != boost::asio::error::eof)
throw AuthException{"malformed response: " + ec.message()};
std::istreambuf_iterator<char> eos;
std::string content{std::istreambuf_iterator<char>{responseStream}, eos};
if (statusCode >= 400 && statusCode <= 499)
throw BadAccess{"invalid data used to access Global Registry. "
"Status: " +
std::to_string(statusCode) + ". Response: '" + content + "'"};
if (statusCode != 200)
throw AuthException{"Global Registry responded with non-ok code " +
std::to_string(statusCode) + ". Response: '" + content +
"'"};
return content;
}
TokenAuthDetails GRAdapter::parseToken(const std::string &response) const
{
std::string err;
const auto json = json11::Json::parse(response, err);
if (!err.empty())
throw AuthException{"malformed JSON response: " + err};
const auto accessToken = json["access_token"].string_value();
const auto refreshToken = json["refresh_token"].string_value();
const auto jwt = json["id_token"].string_value();
const auto expiresIn = json["expires_in"].int_value();
using unbase = boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<
std::string::const_iterator>,
8, 6>;
std::vector<std::string> items;
boost::algorithm::split(items, jwt, boost::is_any_of("."));
const std::string idTokenRaw{
unbase{items[1].begin()}, unbase{items[1].end()}};
const auto idTokenJson = json11::Json::parse(idTokenRaw, err);
if (!err.empty())
throw AuthException{"malformed id_token: " + err};
TokenAuthDetails auth{accessToken, refreshToken,
idTokenJson["sub"].string_value(), expiresIn};
boost::filesystem::ofstream stream{tokenFilePath(), std::ios_base::trunc};
stream << auth;
if (!stream)
LOG(WARNING) << "Failed to save authorization details to a file: "
<< tokenFilePath().string();
return auth;
}
std::unique_ptr<GRAdapter::Socket> GRAdapter::connect(
boost::asio::io_service &ioService) const
{
namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;
tcp::resolver resolver{ioService};
tcp::resolver::query query{m_hostname, std::to_string(m_port),
boost::asio::ip::resolver_query_base::numeric_service};
auto iterator = resolver.resolve(query);
ssl::context ctx{ssl::context::method::tlsv12_client};
ctx.set_default_verify_paths();
auto socket = std::make_unique<Socket>(ioService, ctx);
socket->set_verify_mode(m_checkCertificate ? boost::asio::ssl::verify_peer
: boost::asio::ssl::verify_none);
socket->set_verify_callback(ssl::rfc2818_verification{m_hostname});
boost::asio::connect(socket->lowest_layer(), iterator);
socket->lowest_layer().set_option(tcp::no_delay(true));
socket->handshake(ssl::stream_base::client);
return socket;
}
boost::filesystem::path GRAdapter::tokenFilePath() const
{
return m_userDataDir / "accessToken";
}
} // namespace auth
} // namespace client
} // namespace one
<|endoftext|> |
<commit_before>/*************************************************
* Library Internal/Global State Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/libstate.h>
#include <botan/engine.h>
#include <botan/x509stat.h>
#include <botan/stl_util.h>
#include <botan/mutex.h>
#include <botan/timers.h>
#include <botan/charset.h>
namespace Botan {
/*************************************************
* Botan's global state *
*************************************************/
namespace {
Library_State* global_lib_state = 0;
}
Library_State& global_state()
{
if(!global_lib_state)
throw Invalid_State("Library was not intialized correctly");
return (*global_lib_state);
}
void set_global_state(Library_State* new_state)
{
delete swap_global_state(new_state);
}
Library_State* swap_global_state(Library_State* new_state)
{
Library_State* old_state = global_lib_state;
global_lib_state = new_state;
return old_state;
}
namespace {
/*************************************************
* Named Mutex Holder *
*************************************************/
class Named_Mutex_Holder
{
public:
Named_Mutex_Holder(const std::map<std::string, Mutex*>& mutexes,
const std::string& name)
{
mux = search_map<std::string, Mutex*>(mutexes, name, 0);
if(!mux)
throw Invalid_Argument("Named_Mutex_Holder: mutex not found");
mux->lock();
}
~Named_Mutex_Holder() { mux->unlock(); }
private:
Mutex* mux;
};
}
/*************************************************
* Increment the Engine iterator *
*************************************************/
Engine* Library_State::Engine_Iterator::next()
{
return lib.get_engine_n(n++);
}
/*************************************************
* Get a new mutex object *
*************************************************/
Mutex* Library_State::get_mutex() const
{
return mutex_factory->make();
}
/*************************************************
* Get an allocator by its name *
*************************************************/
Allocator* Library_State::get_allocator(const std::string& type) const
{
Named_Mutex_Holder lock(locks, "allocator");
if(type != "")
return search_map<std::string, Allocator*>(alloc_factory, type, 0);
if(!cached_default_allocator)
{
const std::string key_name = "conf/base/default_allocator";
Named_Mutex_Holder lock(locks, "settings");
std::string chosen = search_map(settings, key_name);
if(chosen == "")
chosen = "malloc";
cached_default_allocator =
search_map<std::string, Allocator*>(alloc_factory, chosen, 0);
}
return cached_default_allocator;
}
/*************************************************
* Create a new name to object mapping *
*************************************************/
void Library_State::add_allocator(const std::string& type,
Allocator* allocator)
{
Named_Mutex_Holder lock(locks, "allocator");
allocator->init();
if(alloc_factory[type])
delete alloc_factory[type];
alloc_factory[type] = allocator;
}
/*************************************************
* Read a high resolution clock *
*************************************************/
u64bit Library_State::system_clock() const
{
return timer->clock();
}
/*************************************************
* Set the global PRNG *
*************************************************/
void Library_State::set_prng(RandomNumberGenerator* new_rng)
{
Named_Mutex_Holder lock(locks, "rng");
delete rng;
rng = new_rng;
}
/*************************************************
* Get bytes from the global PRNG *
*************************************************/
void Library_State::randomize(byte out[], u32bit length)
{
Named_Mutex_Holder lock(locks, "rng");
rng->randomize(out, length);
}
/*************************************************
* Add a new entropy source to use *
*************************************************/
void Library_State::add_entropy_source(EntropySource* src, bool last_in_list)
{
Named_Mutex_Holder lock(locks, "rng");
if(last_in_list)
entropy_sources.push_back(src);
else
entropy_sources.insert(entropy_sources.begin(), src);
}
/*************************************************
* Add some bytes of entropy to the global PRNG *
*************************************************/
void Library_State::add_entropy(const byte in[], u32bit length)
{
Named_Mutex_Holder lock(locks, "rng");
rng->add_entropy(in, length);
}
/*************************************************
* Add some bytes of entropy to the global PRNG *
*************************************************/
void Library_State::add_entropy(EntropySource& source, bool slow_poll)
{
Named_Mutex_Holder lock(locks, "rng");
rng->add_entropy(source, slow_poll);
}
/*************************************************
* Gather entropy for our PRNG object *
*************************************************/
u32bit Library_State::seed_prng(bool slow_poll, u32bit bits_to_get)
{
Named_Mutex_Holder lock(locks, "rng");
u32bit bits = 0;
for(u32bit j = 0; j != entropy_sources.size(); ++j)
{
bits += rng->add_entropy(*(entropy_sources[j]), slow_poll);
if(bits_to_get && bits >= bits_to_get)
return bits;
}
return bits;
}
/*************************************************
* Set a named option *
*************************************************/
void Library_State::set_option(const std::string& section,
const std::string& name,
const std::string& value,
bool overwrite)
{
Named_Mutex_Holder lock(locks, "settings");
std::map<std::string, std::string>::const_iterator i = settings.find(name);
if(overwrite || i == settings.end() || i->second == "")
{
const std::string full_name = section + "/" + name;
settings[full_name] = value;
if(full_name == "base/default_allocator")
cached_default_allocator = 0;
}
}
/*************************************************
* Get the value of the named option *
*************************************************/
std::string Library_State::get_option(const std::string& section,
const std::string& name) const
{
Named_Mutex_Holder lock(locks, "settings");
return search_map<std::string, std::string>(settings,
section + "/" + name, "");
}
/*************************************************
* See if a particular option has been set *
*************************************************/
bool Library_State::option_set(const std::string& section,
const std::string& name) const
{
Named_Mutex_Holder lock(locks, "settings");
return search_map(settings, section + "/" + name, false, true);
}
/*************************************************
* Get an engine out of the list *
*************************************************/
Engine* Library_State::get_engine_n(u32bit n) const
{
Named_Mutex_Holder lock(locks, "engine");
if(n >= engines.size())
return 0;
return engines[n];
}
/*************************************************
* Add a new engine to the list *
*************************************************/
void Library_State::add_engine(Engine* engine)
{
Named_Mutex_Holder lock(locks, "engine");
engines.push_back(engine);
}
/*************************************************
* Set the character set transcoder object *
*************************************************/
void Library_State::set_transcoder(class Charset_Transcoder* transcoder)
{
if(this->transcoder)
delete this->transcoder;
this->transcoder = transcoder;
}
/*************************************************
* Transcode a string from one charset to another *
*************************************************/
std::string Library_State::transcode(const std::string str,
Character_Set to,
Character_Set from) const
{
if(!transcoder)
throw Invalid_State("Library_State::transcode: No transcoder set");
return transcoder->transcode(str, to, from);
}
/*************************************************
* Set the X509 global state class *
*************************************************/
void Library_State::set_x509_state(X509_GlobalState* new_x509_state_obj)
{
delete x509_state_obj;
x509_state_obj = new_x509_state_obj;
}
/*************************************************
* Set the X509 global state class *
*************************************************/
X509_GlobalState& Library_State::x509_state() const
{
if(!x509_state_obj)
throw Invalid_State("Library_State::x509_state: No state set");
return (*x509_state_obj);
}
/*************************************************
* Library_State Constructor *
*************************************************/
Library_State::Library_State(Mutex_Factory* mutex_factory, Timer* timer)
{
if(!mutex_factory)
mutex_factory = new Mutex_Factory;
if(!timer)
timer = new Timer;
this->mutex_factory = mutex_factory;
this->timer = timer;
this->transcoder = 0;
locks["settings"] = get_mutex();
locks["allocator"] = get_mutex();
locks["rng"] = get_mutex();
locks["engine"] = get_mutex();
rng = 0;
cached_default_allocator = 0;
x509_state_obj = new X509_GlobalState();
set_default_policy();
}
/*************************************************
* Library_State Destructor *
*************************************************/
Library_State::~Library_State()
{
cached_default_allocator = 0;
delete rng;
delete x509_state_obj;
for(u32bit j = 0; j != entropy_sources.size(); ++j)
delete entropy_sources[j];
for(u32bit j = 0; j != engines.size(); ++j)
delete engines[j];
for(std::map<std::string, Allocator*>::iterator j = alloc_factory.begin();
j != alloc_factory.end(); ++j)
{
j->second->destroy();
delete j->second;
}
delete transcoder;
delete mutex_factory;
delete timer;
for(std::map<std::string, Mutex*>::iterator j = locks.begin();
j != locks.end(); ++j)
delete j->second;
}
}
<commit_msg>Have system_clock return 0, rather than crash, if no timer is set<commit_after>/*************************************************
* Library Internal/Global State Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/libstate.h>
#include <botan/engine.h>
#include <botan/x509stat.h>
#include <botan/stl_util.h>
#include <botan/mutex.h>
#include <botan/timers.h>
#include <botan/charset.h>
namespace Botan {
/*************************************************
* Botan's global state *
*************************************************/
namespace {
Library_State* global_lib_state = 0;
}
Library_State& global_state()
{
if(!global_lib_state)
throw Invalid_State("Library was not intialized correctly");
return (*global_lib_state);
}
void set_global_state(Library_State* new_state)
{
delete swap_global_state(new_state);
}
Library_State* swap_global_state(Library_State* new_state)
{
Library_State* old_state = global_lib_state;
global_lib_state = new_state;
return old_state;
}
namespace {
/*************************************************
* Named Mutex Holder *
*************************************************/
class Named_Mutex_Holder
{
public:
Named_Mutex_Holder(const std::map<std::string, Mutex*>& mutexes,
const std::string& name)
{
mux = search_map<std::string, Mutex*>(mutexes, name, 0);
if(!mux)
throw Invalid_Argument("Named_Mutex_Holder: mutex not found");
mux->lock();
}
~Named_Mutex_Holder() { mux->unlock(); }
private:
Mutex* mux;
};
}
/*************************************************
* Increment the Engine iterator *
*************************************************/
Engine* Library_State::Engine_Iterator::next()
{
return lib.get_engine_n(n++);
}
/*************************************************
* Get a new mutex object *
*************************************************/
Mutex* Library_State::get_mutex() const
{
return mutex_factory->make();
}
/*************************************************
* Get an allocator by its name *
*************************************************/
Allocator* Library_State::get_allocator(const std::string& type) const
{
Named_Mutex_Holder lock(locks, "allocator");
if(type != "")
return search_map<std::string, Allocator*>(alloc_factory, type, 0);
if(!cached_default_allocator)
{
const std::string key_name = "conf/base/default_allocator";
Named_Mutex_Holder lock(locks, "settings");
std::string chosen = search_map(settings, key_name);
if(chosen == "")
chosen = "malloc";
cached_default_allocator =
search_map<std::string, Allocator*>(alloc_factory, chosen, 0);
}
return cached_default_allocator;
}
/*************************************************
* Create a new name to object mapping *
*************************************************/
void Library_State::add_allocator(const std::string& type,
Allocator* allocator)
{
Named_Mutex_Holder lock(locks, "allocator");
allocator->init();
if(alloc_factory[type])
delete alloc_factory[type];
alloc_factory[type] = allocator;
}
/*************************************************
* Read a high resolution clock *
*************************************************/
u64bit Library_State::system_clock() const
{
return (timer) ? timer->clock() : 0;
}
/*************************************************
* Set the global PRNG *
*************************************************/
void Library_State::set_prng(RandomNumberGenerator* new_rng)
{
Named_Mutex_Holder lock(locks, "rng");
delete rng;
rng = new_rng;
}
/*************************************************
* Get bytes from the global PRNG *
*************************************************/
void Library_State::randomize(byte out[], u32bit length)
{
Named_Mutex_Holder lock(locks, "rng");
rng->randomize(out, length);
}
/*************************************************
* Add a new entropy source to use *
*************************************************/
void Library_State::add_entropy_source(EntropySource* src, bool last_in_list)
{
Named_Mutex_Holder lock(locks, "rng");
if(last_in_list)
entropy_sources.push_back(src);
else
entropy_sources.insert(entropy_sources.begin(), src);
}
/*************************************************
* Add some bytes of entropy to the global PRNG *
*************************************************/
void Library_State::add_entropy(const byte in[], u32bit length)
{
Named_Mutex_Holder lock(locks, "rng");
rng->add_entropy(in, length);
}
/*************************************************
* Add some bytes of entropy to the global PRNG *
*************************************************/
void Library_State::add_entropy(EntropySource& source, bool slow_poll)
{
Named_Mutex_Holder lock(locks, "rng");
rng->add_entropy(source, slow_poll);
}
/*************************************************
* Gather entropy for our PRNG object *
*************************************************/
u32bit Library_State::seed_prng(bool slow_poll, u32bit bits_to_get)
{
Named_Mutex_Holder lock(locks, "rng");
u32bit bits = 0;
for(u32bit j = 0; j != entropy_sources.size(); ++j)
{
bits += rng->add_entropy(*(entropy_sources[j]), slow_poll);
if(bits_to_get && bits >= bits_to_get)
return bits;
}
return bits;
}
/*************************************************
* Set a named option *
*************************************************/
void Library_State::set_option(const std::string& section,
const std::string& name,
const std::string& value,
bool overwrite)
{
Named_Mutex_Holder lock(locks, "settings");
std::map<std::string, std::string>::const_iterator i = settings.find(name);
if(overwrite || i == settings.end() || i->second == "")
{
const std::string full_name = section + "/" + name;
settings[full_name] = value;
if(full_name == "base/default_allocator")
cached_default_allocator = 0;
}
}
/*************************************************
* Get the value of the named option *
*************************************************/
std::string Library_State::get_option(const std::string& section,
const std::string& name) const
{
Named_Mutex_Holder lock(locks, "settings");
return search_map<std::string, std::string>(settings,
section + "/" + name, "");
}
/*************************************************
* See if a particular option has been set *
*************************************************/
bool Library_State::option_set(const std::string& section,
const std::string& name) const
{
Named_Mutex_Holder lock(locks, "settings");
return search_map(settings, section + "/" + name, false, true);
}
/*************************************************
* Get an engine out of the list *
*************************************************/
Engine* Library_State::get_engine_n(u32bit n) const
{
Named_Mutex_Holder lock(locks, "engine");
if(n >= engines.size())
return 0;
return engines[n];
}
/*************************************************
* Add a new engine to the list *
*************************************************/
void Library_State::add_engine(Engine* engine)
{
Named_Mutex_Holder lock(locks, "engine");
engines.push_back(engine);
}
/*************************************************
* Set the character set transcoder object *
*************************************************/
void Library_State::set_transcoder(class Charset_Transcoder* transcoder)
{
if(this->transcoder)
delete this->transcoder;
this->transcoder = transcoder;
}
/*************************************************
* Transcode a string from one charset to another *
*************************************************/
std::string Library_State::transcode(const std::string str,
Character_Set to,
Character_Set from) const
{
if(!transcoder)
throw Invalid_State("Library_State::transcode: No transcoder set");
return transcoder->transcode(str, to, from);
}
/*************************************************
* Set the X509 global state class *
*************************************************/
void Library_State::set_x509_state(X509_GlobalState* new_x509_state_obj)
{
delete x509_state_obj;
x509_state_obj = new_x509_state_obj;
}
/*************************************************
* Set the X509 global state class *
*************************************************/
X509_GlobalState& Library_State::x509_state() const
{
if(!x509_state_obj)
x509_state_obj = new X509_GlobalState();
return (*x509_state_obj);
}
/*************************************************
* Library_State Constructor *
*************************************************/
Library_State::Library_State(Mutex_Factory* mutex_factory, Timer* timer)
{
if(!mutex_factory)
mutex_factory = new Mutex_Factory;
if(!timer)
timer = new Timer;
this->mutex_factory = mutex_factory;
this->timer = timer;
this->transcoder = 0;
locks["settings"] = get_mutex();
locks["allocator"] = get_mutex();
locks["rng"] = get_mutex();
locks["engine"] = get_mutex();
rng = 0;
cached_default_allocator = 0;
x509_state_obj = 0;
set_default_policy();
}
/*************************************************
* Library_State Destructor *
*************************************************/
Library_State::~Library_State()
{
delete x509_state_obj;
delete transcoder;
for(u32bit j = 0; j != entropy_sources.size(); ++j)
delete entropy_sources[j];
delete rng;
for(u32bit j = 0; j != engines.size(); ++j)
delete engines[j];
cached_default_allocator = 0;
for(std::map<std::string, Allocator*>::iterator j = alloc_factory.begin();
j != alloc_factory.end(); ++j)
{
j->second->destroy();
delete j->second;
}
delete mutex_factory;
delete timer;
for(std::map<std::string, Mutex*>::iterator j = locks.begin();
j != locks.end(); ++j)
delete j->second;
}
}
<|endoftext|> |
<commit_before>//!@todo: performance: Review string formatting. Use attached stream.
//!@todo: api: Make elasticsearch frontend. Use swarm + asio and only index request with simple response checking.
//!@todo: files_t: Make file naming by pattern.
//!@todo: api: Ability to set global attribute mapper (?)
//!@todo: api: Global thread-safe guarantee. Do not lock if underlying class is thread-safe itself.
//!@todo: api: Make fallback logger. Make it configurable.
//!@todo: aux: Make internal exception class with attribute keeping, e.g. line, file or path.
//!@todo: msgpack_t: Attribute mappings.
//!@todo: socket_t: Make asynchronous TCP backend.
//!@todo: benchmark: File logging comparing with boost::log.
//!@todo: benchmark: Socket logging with json.
<commit_msg>One task less.<commit_after>//!@todo: performance: Review string formatting. Use attached stream.
//!@todo: api: Make elasticsearch frontend. Use swarm + asio and only index request with simple response checking.
//!@todo: api: Ability to set global attribute mapper (?)
//!@todo: api: Global thread-safe guarantee. Do not lock if underlying class is thread-safe itself.
//!@todo: api: Make fallback logger. Make it configurable.
//!@todo: aux: Make internal exception class with attribute keeping, e.g. line, file or path.
//!@todo: msgpack_t: Attribute mappings.
//!@todo: socket_t: Make asynchronous TCP backend.
//!@todo: benchmark: File logging comparing with boost::log.
//!@todo: benchmark: Socket logging with json.
<|endoftext|> |
<commit_before>#ifndef BUILTIN_UTIL_I_HH
#define BUILTIN_UTIL_I_HH
#ifndef BUILTIN_UTIL_HH
#error "Please include via parent file"
#endif
#include <stack>
#include <vector>
#include <array>
#include <cstdio>
#include "util.hh"
#include "lisp_ptr.hh"
#include "cons.hh"
#include "vm.hh"
template<bool dot_list, typename StackT>
Lisp_ptr stack_to_list(StackT& st){
Lisp_ptr argc = st.back();
st.pop_back();
if(argc.get<int>() == 0){
return Cons::NIL;
}
Cons* c = new Cons;
Cons* prev_c = c;
Lisp_ptr ret = c;
for(int i = 0; i < argc.get<int>(); ++i){
c->rplaca(st.back());
st.pop_back();
Cons* newc = new Cons;
c->rplacd(newc);
prev_c = c;
c = newc;
}
if(dot_list){
if(c != prev_c){
prev_c->rplacd(c->car());
}else{
ret = c->car();
}
delete c;
}else{
c->rplacd(Cons::NIL);
}
return ret;
}
template<typename StackT, typename VectorT>
void stack_to_vector(StackT& st, VectorT& v){
Lisp_ptr argc = st.back();
st.pop_back();
for(int i = 0; i < argc.get<int>(); ++i){
v.push_back(st.back());
st.pop_back();
}
}
template<typename StackT>
int list_to_stack(const char* opname, Lisp_ptr l, StackT& st){
std::stack<Lisp_ptr, std::vector<Lisp_ptr>> tmp;
do_list(l,
[&](Cons* c) -> bool {
tmp.push(c->car());
return true;
},
[&](Lisp_ptr last_cdr){
if(!nullp(last_cdr)){
fprintf(zs::err, "eval warning: dot list has read as proper list. (in %s)\n",
opname);
tmp.push(last_cdr);
}
});
int ret = 0;
while(!tmp.empty()){
st.push_back(tmp.top());
tmp.pop();
++ret;
}
return ret;
}
template<int size>
std::array<Lisp_ptr, size> pick_args(){
Lisp_ptr argc = vm.stack.back();
vm.stack.pop_back();
auto ret = std::array<Lisp_ptr, size>();
if(argc.get<int>() != size){
ret.fill({});
return ret;
}
for(int i = 0; i < size; ++i){
ret[i] = vm.stack.back();
vm.stack.pop_back();
}
return ret;
}
#endif //BUILTIN_UTIL_I_HH
<commit_msg>fixed arg passing<commit_after>#ifndef BUILTIN_UTIL_I_HH
#define BUILTIN_UTIL_I_HH
#ifndef BUILTIN_UTIL_HH
#error "Please include via parent file"
#endif
#include <stack>
#include <vector>
#include <array>
#include <cstdio>
#include <iterator>
#include "util.hh"
#include "lisp_ptr.hh"
#include "cons.hh"
#include "vm.hh"
template<bool dot_list, typename StackT>
Lisp_ptr stack_to_list(StackT& st){
Lisp_ptr argc = st.back();
st.pop_back();
if(argc.get<int>() == 0){
return Cons::NIL;
}
Cons* c = new Cons;
Cons* prev_c = c;
Lisp_ptr ret = c;
for(int i = 0; i < argc.get<int>(); ++i){
c->rplaca(st.back());
st.pop_back();
Cons* newc = new Cons;
c->rplacd(newc);
prev_c = c;
c = newc;
}
if(dot_list){
if(c != prev_c){
prev_c->rplacd(c->car());
}else{
ret = c->car();
}
delete c;
}else{
c->rplacd(Cons::NIL);
}
return ret;
}
template<typename StackT, typename VectorT>
void stack_to_vector(StackT& st, VectorT& v){
Lisp_ptr argc = st.back();
st.pop_back();
auto arg_start = st.end() - argc.get<int>();
auto arg_end = st.end();
for(auto i = arg_start; i != arg_end; ++i){
v.push_back(*i);
}
st.erase(arg_start, arg_end);
}
template<typename StackT>
int list_to_stack(const char* opname, Lisp_ptr l, StackT& st){
std::stack<Lisp_ptr> tmp;
do_list(l,
[&](Cons* c) -> bool {
tmp.push(c->car());
return true;
},
[&](Lisp_ptr last_cdr){
if(!nullp(last_cdr)){
fprintf(zs::err, "eval warning: dot list has read as proper list. (in %s)\n",
opname);
tmp.push(last_cdr);
}
});
int ret = 0;
while(!tmp.empty()){
st.push_back(tmp.top());
tmp.pop();
++ret;
}
return ret;
}
template<int size>
std::array<Lisp_ptr, size> pick_args(){
Lisp_ptr argc = vm.stack.back();
vm.stack.pop_back();
auto ret = std::array<Lisp_ptr, size>();
if(argc.get<int>() != size){
ret.fill({});
return ret;
}
for(int i = 0; i < size; ++i){
ret[i] = vm.stack[vm.stack.size() - size + i];
}
vm.stack.erase(vm.stack.end() - size, vm.stack.end());
return ret;
}
#endif //BUILTIN_UTIL_I_HH
<|endoftext|> |
<commit_before>#include "client_manager.hh"
#include "buffer_manager.hh"
#include "command_manager.hh"
#include "containers.hh"
#include "event_manager.hh"
#include "face_registry.hh"
#include "file.hh"
#include "user_interface.hh"
#include "window.hh"
namespace Kakoune
{
ClientManager::ClientManager() = default;
ClientManager::~ClientManager() = default;
String ClientManager::generate_name() const
{
for (int i = 0; true; ++i)
{
String name = "unnamed" + to_string(i);
if (validate_client_name(name))
return name;
}
}
Client* ClientManager::create_client(std::unique_ptr<UserInterface>&& ui,
EnvVarMap env_vars,
StringView init_commands)
{
Buffer& buffer = **BufferManager::instance().begin();
WindowAndSelections ws = get_free_window(buffer);
Client* client = new Client{std::move(ui), std::move(ws.window),
std::move(ws.selections), std::move(env_vars),
generate_name()};
m_clients.emplace_back(client);
try
{
CommandManager::instance().execute(init_commands, client->context());
}
catch (Kakoune::runtime_error& error)
{
client->context().print_status({ error.what(), get_face("Error") });
client->context().hooks().run_hook("RuntimeError", error.what(),
client->context());
}
catch (Kakoune::client_removed&)
{
m_clients.pop_back();
return nullptr;
}
client->ui().set_input_callback([client](EventMode mode) {
client->handle_available_input(mode);
});
return client;
}
void ClientManager::handle_pending_inputs() const
{
for (auto& client : m_clients)
client->handle_available_input(EventMode::Pending);
}
void ClientManager::remove_client(Client& client)
{
for (auto it = m_clients.begin(); it != m_clients.end(); ++it)
{
if (it->get() == &client)
{
m_clients.erase(it);
return;
}
}
kak_assert(false);
}
WindowAndSelections ClientManager::get_free_window(Buffer& buffer)
{
for (auto it = m_free_windows.rbegin(), end = m_free_windows.rend();
it != end; ++it)
{
auto& w = it->window;
if (&w->buffer() == &buffer)
{
w->forget_timestamp();
WindowAndSelections res = std::move(*it);
m_free_windows.erase(it.base()-1);
res.selections.update();
return res;
}
}
return WindowAndSelections{ std::unique_ptr<Window>{new Window{buffer}},
SelectionList{ buffer, Selection{} } };
}
void ClientManager::add_free_window(std::unique_ptr<Window>&& window, SelectionList selections)
{
Buffer& buffer = window->buffer();
m_free_windows.push_back({ std::move(window), SelectionList{ std::move(selections) }, buffer.timestamp() });
}
void ClientManager::ensure_no_client_uses_buffer(Buffer& buffer)
{
for (auto& client : m_clients)
{
client->context().forget_jumps_to_buffer(buffer);
if (&client->context().buffer() != &buffer)
continue;
if (client->context().is_editing())
throw runtime_error("client '" + client->context().name() + "' is inserting in '" +
buffer.display_name() + "'");
// change client context to edit the first buffer which is not the
// specified one. As BufferManager stores buffer according to last
// access, this selects a sensible buffer to display.
for (auto& buf : BufferManager::instance())
{
if (buf != &buffer)
{
client->context().change_buffer(*buf);
break;
}
}
}
auto end = std::remove_if(m_free_windows.begin(), m_free_windows.end(),
[&buffer](const WindowAndSelections& ws)
{ return &ws.window->buffer() == &buffer; });
m_free_windows.erase(end, m_free_windows.end());
}
bool ClientManager::validate_client_name(StringView name) const
{
auto it = find_if(m_clients, [&](const std::unique_ptr<Client>& client)
{ return client->context().name() == name; });
return it == m_clients.end();
}
Client* ClientManager::get_client_ifp(StringView name)
{
for (auto& client : m_clients)
{
if (client->context().name() == name)
return client.get();
}
return nullptr;
}
Client& ClientManager::get_client(StringView name)
{
Client* client = get_client_ifp(name);
if (not client)
throw runtime_error("no client named: " + name);
return *client;
}
void ClientManager::redraw_clients() const
{
for (auto& client : m_clients)
client->redraw_ifn();
}
void ClientManager::clear_mode_trashes() const
{
for (auto& client : m_clients)
client->input_handler().clear_mode_trash();
}
CandidateList ClientManager::complete_client_name(StringView prefix,
ByteCount cursor_pos) const
{
auto c = transformed(m_clients, [](const std::unique_ptr<Client>& c){ return c->context().name(); });
return complete(prefix, cursor_pos, c, prefix_match, subsequence_match);
}
}
<commit_msg>Another stule tweak<commit_after>#include "client_manager.hh"
#include "buffer_manager.hh"
#include "command_manager.hh"
#include "containers.hh"
#include "event_manager.hh"
#include "face_registry.hh"
#include "file.hh"
#include "user_interface.hh"
#include "window.hh"
namespace Kakoune
{
ClientManager::ClientManager() = default;
ClientManager::~ClientManager() = default;
String ClientManager::generate_name() const
{
for (int i = 0; true; ++i)
{
String name = "unnamed" + to_string(i);
if (validate_client_name(name))
return name;
}
}
Client* ClientManager::create_client(std::unique_ptr<UserInterface>&& ui,
EnvVarMap env_vars,
StringView init_commands)
{
Buffer& buffer = **BufferManager::instance().begin();
WindowAndSelections ws = get_free_window(buffer);
Client* client = new Client{std::move(ui), std::move(ws.window),
std::move(ws.selections), std::move(env_vars),
generate_name()};
m_clients.emplace_back(client);
try
{
CommandManager::instance().execute(init_commands, client->context());
}
catch (Kakoune::runtime_error& error)
{
client->context().print_status({ error.what(), get_face("Error") });
client->context().hooks().run_hook("RuntimeError", error.what(),
client->context());
}
catch (Kakoune::client_removed&)
{
m_clients.pop_back();
return nullptr;
}
client->ui().set_input_callback([client](EventMode mode) {
client->handle_available_input(mode);
});
return client;
}
void ClientManager::handle_pending_inputs() const
{
for (auto& client : m_clients)
client->handle_available_input(EventMode::Pending);
}
void ClientManager::remove_client(Client& client)
{
for (auto it = m_clients.begin(); it != m_clients.end(); ++it)
{
if (it->get() == &client)
{
m_clients.erase(it);
return;
}
}
kak_assert(false);
}
WindowAndSelections ClientManager::get_free_window(Buffer& buffer)
{
for (auto it = m_free_windows.rbegin(), end = m_free_windows.rend();
it != end; ++it)
{
auto& w = it->window;
if (&w->buffer() == &buffer)
{
w->forget_timestamp();
WindowAndSelections res = std::move(*it);
m_free_windows.erase(it.base()-1);
res.selections.update();
return res;
}
}
return WindowAndSelections{ std::unique_ptr<Window>{new Window{buffer}},
SelectionList{ buffer, Selection{} } };
}
void ClientManager::add_free_window(std::unique_ptr<Window>&& window, SelectionList selections)
{
Buffer& buffer = window->buffer();
m_free_windows.push_back({ std::move(window), SelectionList{ std::move(selections) }, buffer.timestamp() });
}
void ClientManager::ensure_no_client_uses_buffer(Buffer& buffer)
{
for (auto& client : m_clients)
{
client->context().forget_jumps_to_buffer(buffer);
if (&client->context().buffer() != &buffer)
continue;
if (client->context().is_editing())
throw runtime_error("client '" + client->context().name() + "' is inserting in '" +
buffer.display_name() + "'");
// change client context to edit the first buffer which is not the
// specified one. As BufferManager stores buffer according to last
// access, this selects a sensible buffer to display.
for (auto& buf : BufferManager::instance())
{
if (buf != &buffer)
{
client->context().change_buffer(*buf);
break;
}
}
}
auto end = std::remove_if(m_free_windows.begin(), m_free_windows.end(),
[&buffer](const WindowAndSelections& ws)
{ return &ws.window->buffer() == &buffer; });
m_free_windows.erase(end, m_free_windows.end());
}
bool ClientManager::validate_client_name(StringView name) const
{
auto it = find_if(m_clients, [&](const std::unique_ptr<Client>& client)
{ return client->context().name() == name; });
return it == m_clients.end();
}
Client* ClientManager::get_client_ifp(StringView name)
{
for (auto& client : m_clients)
{
if (client->context().name() == name)
return client.get();
}
return nullptr;
}
Client& ClientManager::get_client(StringView name)
{
if (Client* client = get_client_ifp(name))
return *client;
throw runtime_error("no client named: " + name);
}
void ClientManager::redraw_clients() const
{
for (auto& client : m_clients)
client->redraw_ifn();
}
void ClientManager::clear_mode_trashes() const
{
for (auto& client : m_clients)
client->input_handler().clear_mode_trash();
}
CandidateList ClientManager::complete_client_name(StringView prefix,
ByteCount cursor_pos) const
{
auto c = transformed(m_clients, [](const std::unique_ptr<Client>& c){ return c->context().name(); });
return complete(prefix, cursor_pos, c, prefix_match, subsequence_match);
}
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CStepMatrix.cpp,v $
// $Revision: 1.6 $
// $Name: $
// $Author: shoops $
// $Date: 2009/09/24 18:13:13 $
// End CVS Header
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "copasi.h"
#include "CStepMatrix.h"
#include "CStepMatrixColumn.h"
#include "utilities/CMatrix.h"
CStepMatrix::CStepMatrix():
std::list< CStepMatrixColumn * >(),
mRows(0),
mPivot(0),
mFirstUnconvertedRow(0)
{}
CStepMatrix::CStepMatrix(CMatrix< C_INT32 > & nullspaceMatrix):
std::list< CStepMatrixColumn * >(),
mRows(nullspaceMatrix.numRows()),
mPivot(nullspaceMatrix.numRows()),
mFirstUnconvertedRow(0)
{
size_t Cols = nullspaceMatrix.numCols();
CVector< CStepMatrixColumn * > Columns(Cols);
CStepMatrixColumn ** pColumn = Columns.array();
CStepMatrixColumn ** pColumnEnd = pColumn + Cols;
for (; pColumn != pColumnEnd; ++pColumn)
{
*pColumn = new CStepMatrixColumn(mRows);
push_back(*pColumn);
}
size_t i;
size_t j;
const C_INT32 * pValue = nullspaceMatrix.array();
size_t * pPivot = mPivot.array();
std::vector< size_t > NegativeRows;
bool hasNegative;
bool hasPositive;
for (i = 0; i < mRows; ++i, ++pPivot)
{
*pPivot = i;
hasNegative = false;
hasPositive = false;
for (j = 0; j < Cols; ++j, ++pValue)
{
if (*pValue > 0.0)
{
hasPositive = true;
}
else if (*pValue < 0.0)
{
hasNegative = true;
}
}
if ((hasNegative && !hasPositive) ||
(!hasNegative && hasPositive))
{
convertRow(i, nullspaceMatrix);
}
}
// We need to add the information of the unconverted rows of nullspace matrix
// to the columns
pValue = & nullspaceMatrix(mFirstUnconvertedRow, 0);
for (i = mFirstUnconvertedRow; i < mRows; ++i)
{
pColumn = Columns.array();
for (j = 0; j < Cols; ++j, ++pValue, ++pColumn)
{
(*pColumn)->push_front(*pValue);
}
}
}
CStepMatrix::~CStepMatrix()
{
iterator it = begin();
const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
delete *it;
}
}
void CStepMatrix::convertRow()
{
CZeroSet::CIndex Index(mFirstUnconvertedRow);
iterator it = begin();
const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
if ((*it)->getMultiplier() != 0)
{
(*it)->unsetBit(Index);
}
(*it)->truncate();
}
mFirstUnconvertedRow++;
}
size_t CStepMatrix::getFirstUnconvertedRow() const
{
return mFirstUnconvertedRow;
}
size_t CStepMatrix::getNumUnconvertedRows() const
{
return mRows - mFirstUnconvertedRow;
}
CStepMatrixColumn * CStepMatrix::addColumn(const CZeroSet & set,
CStepMatrixColumn const * pPositive,
CStepMatrixColumn const * pNegative)
{
CStepMatrixColumn * pColumn = new CStepMatrixColumn(set, pPositive, pNegative);
push_back(pColumn);
return pColumn;
}
bool CStepMatrix::splitColumns(std::list< CStepMatrixColumn * > & PositiveColumns,
std::list< CStepMatrixColumn * > & NegativeColumns,
std::list< CStepMatrixColumn * > & NullColumns)
{
PositiveColumns.clear();
NegativeColumns.clear();
iterator it = begin();
const_iterator itEnd = end();
while (it != itEnd)
{
const C_FLOAT64 & Value = (*it)->getMultiplier();
if (Value > 0.0)
{
PositiveColumns.push_back(*it);
++it;
}
else if (Value < 0.0)
{
NegativeColumns.push_back(*it);
// Since all negative columns have to be removed this is the perfect place to do so.
it = erase(it);
}
else
{
NullColumns.push_back(*it);
++it;
}
}
if (NegativeColumns.empty())
{
convertRow();
return false;
}
else if (PositiveColumns.empty())
{
// We can not remove the negative columns therefore we add them again.
std::list< CStepMatrixColumn * >::const_iterator itNeg = NegativeColumns.begin();
std::list< CStepMatrixColumn * >::const_iterator endNeg = NegativeColumns.end();
for (; itNeg != endNeg; ++itNeg)
{
push_back(*itNeg);
}
convertRow();
return false;
}
return true;
}
void CStepMatrix::removeInvalidColumns(const std::vector< CStepMatrixColumn * > & invalidColumns)
{
std::vector< CStepMatrixColumn * >::const_iterator it = invalidColumns.begin();
std::vector< CStepMatrixColumn * >::const_iterator end = invalidColumns.end();
for (; it != end; ++it)
{
remove(*it);
delete *it;
}
}
void CStepMatrix::getUnsetBitIndexes(const CStepMatrixColumn * pColumn,
CVector< size_t > & indexes) const
{
const CZeroSet & ZeroSet = pColumn->getZeroSet();
indexes.resize(ZeroSet.getNumberOfUnsetBits());
size_t * pIndex = indexes.array();
size_t * pIndexEnd = pIndex + indexes.size();
CZeroSet::CIndex Bit = 0;
size_t Index = 0;
for (; pIndex != pIndexEnd; ++Bit, ++Index)
{
if (!ZeroSet.isSet(Bit))
{
// Apply pivot.
*pIndex = mPivot[Index];
pIndex++;
}
}
return;
}
void CStepMatrix::convertRow(const size_t & index,
CMatrix< C_INT32 > & nullspaceMatrix)
{
CZeroSet::CIndex Index(mFirstUnconvertedRow);
iterator it = begin();
const_iterator itEnd = end();
C_INT32 * pValue = & nullspaceMatrix(index, 0);
if (mFirstUnconvertedRow != index)
{
C_INT32 * pFirstUnconvertedValue = & nullspaceMatrix(mFirstUnconvertedRow, 0);
for (; it != itEnd; ++it, ++pValue, ++pFirstUnconvertedValue)
{
if (*pValue != 0)
{
(*it)->unsetBit(Index);
}
*pValue = *pFirstUnconvertedValue;
}
// We need to remember the reordering.
size_t tmp = mPivot[index];
mPivot[index] = mPivot[mFirstUnconvertedRow];
mPivot[mFirstUnconvertedRow] = tmp;
}
else
{
for (; it != itEnd; ++it, ++pValue)
{
if (*pValue != 0)
{
(*it)->unsetBit(Index);
}
}
}
mFirstUnconvertedRow++;
}
std::ostream & operator << (std::ostream & os, const CStepMatrix & m)
{
os << m.mPivot << std::endl;
size_t i;
CZeroSet::CIndex Bit;
CStepMatrix::const_iterator it;
CStepMatrix::const_iterator end = m.end();
for (i = 0, Bit = 0; i < m.mFirstUnconvertedRow; ++i, ++Bit)
{
for (it = m.begin(); it != end; ++it)
{
if ((*it)->getZeroSet().isSet(Bit))
{
os << "*\t";
}
else
{
os << ".\t";
}
}
os << std::endl;
}
for (i = m.mRows - m.mFirstUnconvertedRow; i > 0;)
{
--i;
for (it = m.begin(); it != end; ++it)
{
os << (*it)->getReaction()[i] << '\t';
}
os << std::endl;
}
return os;
}
<commit_msg>Fixed crash when the model does not contain any reactions.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CStepMatrix.cpp,v $
// $Revision: 1.7 $
// $Name: $
// $Author: shoops $
// $Date: 2009/09/29 16:33:48 $
// End CVS Header
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "copasi.h"
#include "CStepMatrix.h"
#include "CStepMatrixColumn.h"
#include "utilities/CMatrix.h"
CStepMatrix::CStepMatrix():
std::list< CStepMatrixColumn * >(),
mRows(0),
mPivot(0),
mFirstUnconvertedRow(0)
{}
CStepMatrix::CStepMatrix(CMatrix< C_INT32 > & nullspaceMatrix):
std::list< CStepMatrixColumn * >(),
mRows(nullspaceMatrix.numRows()),
mPivot(nullspaceMatrix.numRows()),
mFirstUnconvertedRow(0)
{
size_t Cols = nullspaceMatrix.numCols();
CVector< CStepMatrixColumn * > Columns(Cols);
CStepMatrixColumn ** pColumn = Columns.array();
CStepMatrixColumn ** pColumnEnd = pColumn + Cols;
for (; pColumn != pColumnEnd; ++pColumn)
{
*pColumn = new CStepMatrixColumn(mRows);
push_back(*pColumn);
}
size_t i;
size_t j;
const C_INT32 * pValue = nullspaceMatrix.array();
size_t * pPivot = mPivot.array();
std::vector< size_t > NegativeRows;
bool hasNegative;
bool hasPositive;
for (i = 0; i < mRows; ++i, ++pPivot)
{
*pPivot = i;
hasNegative = false;
hasPositive = false;
for (j = 0; j < Cols; ++j, ++pValue)
{
if (*pValue > 0.0)
{
hasPositive = true;
}
else if (*pValue < 0.0)
{
hasNegative = true;
}
}
if ((hasNegative && !hasPositive) ||
(!hasNegative && hasPositive))
{
convertRow(i, nullspaceMatrix);
}
}
// We need to add the information of the unconverted rows of nullspace matrix
// to the columns
if (nullspaceMatrix.size() != 0)
{
pValue = & nullspaceMatrix(mFirstUnconvertedRow, 0);
}
else
{
pValue = NULL;
}
for (i = mFirstUnconvertedRow; i < mRows; ++i)
{
pColumn = Columns.array();
for (j = 0; j < Cols; ++j, ++pValue, ++pColumn)
{
(*pColumn)->push_front(*pValue);
}
}
}
CStepMatrix::~CStepMatrix()
{
iterator it = begin();
const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
delete *it;
}
}
void CStepMatrix::convertRow()
{
CZeroSet::CIndex Index(mFirstUnconvertedRow);
iterator it = begin();
const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
if ((*it)->getMultiplier() != 0)
{
(*it)->unsetBit(Index);
}
(*it)->truncate();
}
mFirstUnconvertedRow++;
}
size_t CStepMatrix::getFirstUnconvertedRow() const
{
return mFirstUnconvertedRow;
}
size_t CStepMatrix::getNumUnconvertedRows() const
{
return mRows - mFirstUnconvertedRow;
}
CStepMatrixColumn * CStepMatrix::addColumn(const CZeroSet & set,
CStepMatrixColumn const * pPositive,
CStepMatrixColumn const * pNegative)
{
CStepMatrixColumn * pColumn = new CStepMatrixColumn(set, pPositive, pNegative);
push_back(pColumn);
return pColumn;
}
bool CStepMatrix::splitColumns(std::list< CStepMatrixColumn * > & PositiveColumns,
std::list< CStepMatrixColumn * > & NegativeColumns,
std::list< CStepMatrixColumn * > & NullColumns)
{
PositiveColumns.clear();
NegativeColumns.clear();
iterator it = begin();
const_iterator itEnd = end();
while (it != itEnd)
{
const C_FLOAT64 & Value = (*it)->getMultiplier();
if (Value > 0.0)
{
PositiveColumns.push_back(*it);
++it;
}
else if (Value < 0.0)
{
NegativeColumns.push_back(*it);
// Since all negative columns have to be removed this is the perfect place to do so.
it = erase(it);
}
else
{
NullColumns.push_back(*it);
++it;
}
}
if (NegativeColumns.empty())
{
convertRow();
return false;
}
else if (PositiveColumns.empty())
{
// We can not remove the negative columns therefore we add them again.
std::list< CStepMatrixColumn * >::const_iterator itNeg = NegativeColumns.begin();
std::list< CStepMatrixColumn * >::const_iterator endNeg = NegativeColumns.end();
for (; itNeg != endNeg; ++itNeg)
{
push_back(*itNeg);
}
convertRow();
return false;
}
return true;
}
void CStepMatrix::removeInvalidColumns(const std::vector< CStepMatrixColumn * > & invalidColumns)
{
std::vector< CStepMatrixColumn * >::const_iterator it = invalidColumns.begin();
std::vector< CStepMatrixColumn * >::const_iterator end = invalidColumns.end();
for (; it != end; ++it)
{
remove(*it);
delete *it;
}
}
void CStepMatrix::getUnsetBitIndexes(const CStepMatrixColumn * pColumn,
CVector< size_t > & indexes) const
{
const CZeroSet & ZeroSet = pColumn->getZeroSet();
indexes.resize(ZeroSet.getNumberOfUnsetBits());
size_t * pIndex = indexes.array();
size_t * pIndexEnd = pIndex + indexes.size();
CZeroSet::CIndex Bit = 0;
size_t Index = 0;
for (; pIndex != pIndexEnd; ++Bit, ++Index)
{
if (!ZeroSet.isSet(Bit))
{
// Apply pivot.
*pIndex = mPivot[Index];
pIndex++;
}
}
return;
}
void CStepMatrix::convertRow(const size_t & index,
CMatrix< C_INT32 > & nullspaceMatrix)
{
CZeroSet::CIndex Index(mFirstUnconvertedRow);
iterator it = begin();
const_iterator itEnd = end();
C_INT32 * pValue = & nullspaceMatrix(index, 0);
if (mFirstUnconvertedRow != index)
{
C_INT32 * pFirstUnconvertedValue = & nullspaceMatrix(mFirstUnconvertedRow, 0);
for (; it != itEnd; ++it, ++pValue, ++pFirstUnconvertedValue)
{
if (*pValue != 0)
{
(*it)->unsetBit(Index);
}
*pValue = *pFirstUnconvertedValue;
}
// We need to remember the reordering.
size_t tmp = mPivot[index];
mPivot[index] = mPivot[mFirstUnconvertedRow];
mPivot[mFirstUnconvertedRow] = tmp;
}
else
{
for (; it != itEnd; ++it, ++pValue)
{
if (*pValue != 0)
{
(*it)->unsetBit(Index);
}
}
}
mFirstUnconvertedRow++;
}
std::ostream & operator << (std::ostream & os, const CStepMatrix & m)
{
os << m.mPivot << std::endl;
size_t i;
CZeroSet::CIndex Bit;
CStepMatrix::const_iterator it;
CStepMatrix::const_iterator end = m.end();
for (i = 0, Bit = 0; i < m.mFirstUnconvertedRow; ++i, ++Bit)
{
for (it = m.begin(); it != end; ++it)
{
if ((*it)->getZeroSet().isSet(Bit))
{
os << "*\t";
}
else
{
os << ".\t";
}
}
os << std::endl;
}
for (i = m.mRows - m.mFirstUnconvertedRow; i > 0;)
{
--i;
for (it = m.begin(); it != end; ++it)
{
os << (*it)->getReaction()[i] << '\t';
}
os << std::endl;
}
return os;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "perfetto/ext/base/file_utils.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <deque>
#include <string>
#include <vector>
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/platform_handle.h"
#include "perfetto/base/status.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
} // namespace
ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}
bool ReadFileDescriptor(int fd, std::string* out) {
// Do not override existing data in string.
size_t i = out->size();
struct stat buf {};
if (fstat(fd, &buf) != -1) {
if (buf.st_size > 0)
out->resize(i + static_cast<size_t>(buf.st_size));
}
ssize_t bytes_read;
for (;;) {
if (out->size() < i + kBufSize)
out->resize(out->size() + kBufSize);
bytes_read = Read(fd, &((*out)[i]), kBufSize);
if (bytes_read > 0) {
i += static_cast<size_t>(bytes_read);
} else {
out->resize(i);
return bytes_read == 0;
}
}
}
bool ReadPlatformHandle(PlatformHandle h, std::string* out) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Do not override existing data in string.
size_t i = out->size();
for (;;) {
if (out->size() < i + kBufSize)
out->resize(out->size() + kBufSize);
DWORD bytes_read = 0;
auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);
if (res && bytes_read > 0) {
i += static_cast<size_t>(bytes_read);
} else {
out->resize(i);
const bool is_eof = res && bytes_read == 0;
auto err = res ? 0 : GetLastError();
// The "Broken pipe" error on Windows is slighly different than Unix:
// On Unix: a "broken pipe" error can happen only on the writer side. On
// the reader there is no broken pipe, just a EOF.
// On windows: the reader also sees a broken pipe error.
// Here we normalize on the Unix behavior, treating broken pipe as EOF.
return is_eof || err == ERROR_BROKEN_PIPE;
}
}
#else
return ReadFileDescriptor(h, out);
#endif
}
bool ReadFileStream(FILE* f, std::string* out) {
return ReadFileDescriptor(fileno(f), out);
}
bool ReadFile(const std::string& path, std::string* out) {
base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
if (!fd)
return false;
return ReadFileDescriptor(*fd, out);
}
ssize_t WriteAll(int fd, const void* buf, size_t count) {
size_t written = 0;
while (written < count) {
// write() on windows takes an unsigned int size.
uint32_t bytes_left = static_cast<uint32_t>(
std::min(count - written, static_cast<size_t>(UINT32_MAX)));
ssize_t wr = PERFETTO_EINTR(
write(fd, static_cast<const char*>(buf) + written, bytes_left));
if (wr == 0)
break;
if (wr < 0)
return wr;
written += static_cast<size_t>(wr);
}
return static_cast<ssize_t>(written);
}
ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
DWORD wsize = 0;
if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {
return wsize;
} else {
return -1;
}
#else
return WriteAll(h, buf, count);
#endif
}
bool FlushFile(int fd) {
PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return !PERFETTO_EINTR(_commit(fd));
#else
return !PERFETTO_EINTR(fsync(fd));
#endif
}
bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _mkdir(path.c_str()) == 0;
#else
return mkdir(path.c_str(), 0755) == 0;
#endif
}
bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _rmdir(path.c_str()) == 0;
#else
return rmdir(path.c_str()) == 0;
#endif
}
int CloseFile(int fd) {
return close(fd);
}
ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {
PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Always use O_BINARY on Windows, to avoid silly EOL translations.
ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
// Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
return fd;
}
bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _access(path.c_str(), 0) == 0;
#else
return access(path.c_str(), F_OK) == 0;
#endif
}
// Declared in base/platform_handle.h.
int ClosePlatformHandle(PlatformHandle handle) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Make the return value UNIX-style.
return CloseHandle(handle) ? 0 : -1;
#else
return close(handle);
#endif
}
base::Status ListFilesRecursive(const std::string& dir_path,
std::vector<std::string>& output) {
std::string root_dir_path = dir_path;
if (root_dir_path.back() == '\\') {
root_dir_path.back() = '/';
} else if (root_dir_path.back() != '/') {
root_dir_path.push_back('/');
}
// dir_queue contains full paths to the directories. The paths include the
// root_dir_path at the beginning and the trailing slash at the end.
std::deque<std::string> dir_queue;
dir_queue.push_back(root_dir_path);
while (!dir_queue.empty()) {
const std::string cur_dir = std::move(dir_queue.front());
dir_queue.pop_front();
#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
return base::ErrStatus("ListFilesRecursive not supported yet");
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
std::string glob_path = cur_dir + "*";
// + 1 because we also have to count the NULL terminator.
if (glob_path.length() + 1 > MAX_PATH)
return base::ErrStatus("Directory path %s is too long", dir_path.c_str());
WIN32_FIND_DATAA ffd;
base::ScopedResource<HANDLE, FindClose, nullptr, false,
base::PlatformHandleChecker>
hFind(FindFirstFileA(glob_path.c_str(), &ffd));
if (!hFind) {
// For empty directories, there should be at least one entry '.'.
// If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory
// couldn't be accessed.
return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
}
do {
if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0)
continue;
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::string subdir_path = cur_dir + ffd.cFileName + '/';
dir_queue.push_back(subdir_path);
} else {
const std::string full_path = cur_dir + ffd.cFileName;
PERFETTO_CHECK(full_path.length() > root_dir_path.length());
output.push_back(full_path.substr(root_dir_path.length()));
}
} while (FindNextFileA(*hFind, &ffd));
#else
ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));
if (!dir) {
return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
}
for (auto* dirent = readdir(dir.get()); dirent != nullptr;
dirent = readdir(dir.get())) {
if (strcmp(dirent->d_name, ".") == 0 ||
strcmp(dirent->d_name, "..") == 0) {
continue;
}
if (dirent->d_type == DT_DIR) {
dir_queue.push_back(cur_dir + dirent->d_name + '/');
} else if (dirent->d_type == DT_REG) {
const std::string full_path = cur_dir + dirent->d_name;
PERFETTO_CHECK(full_path.length() > root_dir_path.length());
output.push_back(full_path.substr(root_dir_path.length()));
}
}
#endif
}
return base::OkStatus();
}
std::string GetFileExtension(const std::string& filename) {
auto ext_idx = filename.rfind('.');
if (ext_idx == std::string::npos)
return std::string();
return filename.substr(ext_idx);
}
base::Optional<size_t> GetFileSize(const std::string& file_path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
HANDLE file =
CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return nullopt;
}
LARGE_INTEGER file_size;
file_size.QuadPart = 0;
BOOL ok = GetFileSizeEx(file, &file_size);
CloseHandle(file);
if (!ok) {
return nullopt;
}
return static_cast<size_t>(file_size.QuadPart);
#else
base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));
if (!fd) {
return nullopt;
}
struct stat buf{};
if (fstat(*fd, &buf) == -1) {
return nullopt;
}
return static_cast<size_t>(buf.st_size);
#endif
}
} // namespace base
} // namespace perfetto
<commit_msg>Speculative fix of Windows build breakage am: 0f3d962283 am: 456a82d668<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "perfetto/ext/base/file_utils.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <deque>
#include <string>
#include <vector>
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/platform_handle.h"
#include "perfetto/base/status.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
} // namespace
ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}
bool ReadFileDescriptor(int fd, std::string* out) {
// Do not override existing data in string.
size_t i = out->size();
struct stat buf {};
if (fstat(fd, &buf) != -1) {
if (buf.st_size > 0)
out->resize(i + static_cast<size_t>(buf.st_size));
}
ssize_t bytes_read;
for (;;) {
if (out->size() < i + kBufSize)
out->resize(out->size() + kBufSize);
bytes_read = Read(fd, &((*out)[i]), kBufSize);
if (bytes_read > 0) {
i += static_cast<size_t>(bytes_read);
} else {
out->resize(i);
return bytes_read == 0;
}
}
}
bool ReadPlatformHandle(PlatformHandle h, std::string* out) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Do not override existing data in string.
size_t i = out->size();
for (;;) {
if (out->size() < i + kBufSize)
out->resize(out->size() + kBufSize);
DWORD bytes_read = 0;
auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);
if (res && bytes_read > 0) {
i += static_cast<size_t>(bytes_read);
} else {
out->resize(i);
const bool is_eof = res && bytes_read == 0;
auto err = res ? 0 : GetLastError();
// The "Broken pipe" error on Windows is slighly different than Unix:
// On Unix: a "broken pipe" error can happen only on the writer side. On
// the reader there is no broken pipe, just a EOF.
// On windows: the reader also sees a broken pipe error.
// Here we normalize on the Unix behavior, treating broken pipe as EOF.
return is_eof || err == ERROR_BROKEN_PIPE;
}
}
#else
return ReadFileDescriptor(h, out);
#endif
}
bool ReadFileStream(FILE* f, std::string* out) {
return ReadFileDescriptor(fileno(f), out);
}
bool ReadFile(const std::string& path, std::string* out) {
base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
if (!fd)
return false;
return ReadFileDescriptor(*fd, out);
}
ssize_t WriteAll(int fd, const void* buf, size_t count) {
size_t written = 0;
while (written < count) {
// write() on windows takes an unsigned int size.
uint32_t bytes_left = static_cast<uint32_t>(
std::min(count - written, static_cast<size_t>(UINT32_MAX)));
ssize_t wr = PERFETTO_EINTR(
write(fd, static_cast<const char*>(buf) + written, bytes_left));
if (wr == 0)
break;
if (wr < 0)
return wr;
written += static_cast<size_t>(wr);
}
return static_cast<ssize_t>(written);
}
ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
DWORD wsize = 0;
if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {
return wsize;
} else {
return -1;
}
#else
return WriteAll(h, buf, count);
#endif
}
bool FlushFile(int fd) {
PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return !PERFETTO_EINTR(_commit(fd));
#else
return !PERFETTO_EINTR(fsync(fd));
#endif
}
bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _mkdir(path.c_str()) == 0;
#else
return mkdir(path.c_str(), 0755) == 0;
#endif
}
bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _rmdir(path.c_str()) == 0;
#else
return rmdir(path.c_str()) == 0;
#endif
}
int CloseFile(int fd) {
return close(fd);
}
ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {
PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Always use O_BINARY on Windows, to avoid silly EOL translations.
ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
// Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
return fd;
}
bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
return _access(path.c_str(), 0) == 0;
#else
return access(path.c_str(), F_OK) == 0;
#endif
}
// Declared in base/platform_handle.h.
int ClosePlatformHandle(PlatformHandle handle) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Make the return value UNIX-style.
return CloseHandle(handle) ? 0 : -1;
#else
return close(handle);
#endif
}
base::Status ListFilesRecursive(const std::string& dir_path,
std::vector<std::string>& output) {
std::string root_dir_path = dir_path;
if (root_dir_path.back() == '\\') {
root_dir_path.back() = '/';
} else if (root_dir_path.back() != '/') {
root_dir_path.push_back('/');
}
// dir_queue contains full paths to the directories. The paths include the
// root_dir_path at the beginning and the trailing slash at the end.
std::deque<std::string> dir_queue;
dir_queue.push_back(root_dir_path);
while (!dir_queue.empty()) {
const std::string cur_dir = std::move(dir_queue.front());
dir_queue.pop_front();
#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
return base::ErrStatus("ListFilesRecursive not supported yet");
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
std::string glob_path = cur_dir + "*";
// + 1 because we also have to count the NULL terminator.
if (glob_path.length() + 1 > MAX_PATH)
return base::ErrStatus("Directory path %s is too long", dir_path.c_str());
WIN32_FIND_DATAA ffd;
// Wrap FindClose to: (1) make the return unix-style; (2) deal w/ stdcall.
static auto find_close = [](HANDLE h) { return FindClose(h) ? 0 : -1; };
base::ScopedResource<HANDLE, find_close, nullptr, false,
base::PlatformHandleChecker>
hFind(FindFirstFileA(glob_path.c_str(), &ffd));
if (!hFind) {
// For empty directories, there should be at least one entry '.'.
// If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory
// couldn't be accessed.
return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
}
do {
if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0)
continue;
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::string subdir_path = cur_dir + ffd.cFileName + '/';
dir_queue.push_back(subdir_path);
} else {
const std::string full_path = cur_dir + ffd.cFileName;
PERFETTO_CHECK(full_path.length() > root_dir_path.length());
output.push_back(full_path.substr(root_dir_path.length()));
}
} while (FindNextFileA(*hFind, &ffd));
#else
ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));
if (!dir) {
return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
}
for (auto* dirent = readdir(dir.get()); dirent != nullptr;
dirent = readdir(dir.get())) {
if (strcmp(dirent->d_name, ".") == 0 ||
strcmp(dirent->d_name, "..") == 0) {
continue;
}
if (dirent->d_type == DT_DIR) {
dir_queue.push_back(cur_dir + dirent->d_name + '/');
} else if (dirent->d_type == DT_REG) {
const std::string full_path = cur_dir + dirent->d_name;
PERFETTO_CHECK(full_path.length() > root_dir_path.length());
output.push_back(full_path.substr(root_dir_path.length()));
}
}
#endif
}
return base::OkStatus();
}
std::string GetFileExtension(const std::string& filename) {
auto ext_idx = filename.rfind('.');
if (ext_idx == std::string::npos)
return std::string();
return filename.substr(ext_idx);
}
base::Optional<size_t> GetFileSize(const std::string& file_path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
HANDLE file =
CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return nullopt;
}
LARGE_INTEGER file_size;
file_size.QuadPart = 0;
BOOL ok = GetFileSizeEx(file, &file_size);
CloseHandle(file);
if (!ok) {
return nullopt;
}
return static_cast<size_t>(file_size.QuadPart);
#else
base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));
if (!fd) {
return nullopt;
}
struct stat buf{};
if (fstat(*fd, &buf) == -1) {
return nullopt;
}
return static_cast<size_t>(buf.st_size);
#endif
}
} // namespace base
} // namespace perfetto
<|endoftext|> |
<commit_before>#include <time.h>
#include <unistd.h>
#include <iostream>
struct node {
struct node *pr;
struct node *lf;
struct node *rg;
int value;
} typedef Node;
class BST
{
public:
void insert_node(int value);
void delete_node(int value);
void print_nodes(void);
BST();
private:
Node *root;
void insert_node(Node *node, int value);
void delete_node(Node *node, int value);
void transplant(Node *x, Node *y);
void print_nodes(Node *node);
Node *create_node(Node *pr, int value);
Node *min_node(Node *node);
};
BST::BST(void)
{
root = NULL;
}
Node *BST::create_node(Node *pr, int value)
{
Node *new_node = new Node();
new_node->value = value;
new_node->lf = NULL;
new_node->rg = NULL;
new_node->pr = pr;
return new_node;
}
void BST::insert_node(Node *node, int value)
{
if (node == NULL)
root = create_node(NULL, value);
else if (node->value > value) {
if (node->lf)
insert_node(node->lf, value);
else {
Node *new_node = create_node(node, value);
node->lf = new_node;
}
} else {
if (node->rg)
insert_node(node->rg, value);
else {
Node *new_node = create_node(node, value);
node->rg = new_node;
}
}
}
void BST::insert_node(int value)
{
insert_node(root, value);
}
void BST::transplant(Node *x, Node *y)
{
if (x == root)
root = y;
if (x == x->pr->rg)
x->pr->rg = y;
else
x->pr->lf = y;
if (y)
y->pr = x->pr;
}
Node *BST::min_node(Node *node)
{
if (!node->lf)
return node;
return min_node(node->lf);
}
void BST::delete_node(Node *node, int value)
{
if (node == NULL)
return;
else if (node->value > value)
delete_node(node->lf, value);
else if (node->value < value)
delete_node(node->rg, value);
else {
if (node->rg and !node->lf)
transplant(node, node->rg);
else if (node->lf and !node->rg)
transplant(node, node->lf);
else {
Node *s = min_node(node->rg);
if (s->pr != node) {
transplant(s, s->rg);
s->rg = node->rg;
s->rg->pr = s;
}
transplant(node, s);
s->lf = node->lf;
s->lf->pr = s;
}
}
}
void BST::delete_node(int value)
{
delete_node(root, value);
}
void BST::print_nodes(Node *node)
{
if (!node)
return;
print_nodes(node->lf);
std::cout << "Value: " << node->value << std::endl;
print_nodes(node->rg);
}
void BST::print_nodes(void)
{
print_nodes(root);
}
int main(int argc, char *argv[])
{
std::cout << "Binary Search Tree!" << std::endl;
int number_of_test_values = 10;
BST tree = BST();
std::cout << "Inserting <" << number_of_test_values;
std::cout << "> random values...." << std::endl;
srand(time(NULL));
for (int i=0; i < number_of_test_values; i++) {
int value = rand() % 100;
std::cout << "Inserting " << value << std::endl;
tree.insert_node(value);
}
tree.print_nodes();
return 0;
}
<commit_msg>Generic Binary Search Tree!<commit_after>#include <time.h>
#include <unistd.h>
#include <iostream>
template <class T>
class Node
{
public:
Node<T> *pr;
Node<T> *lf;
Node<T> *rg;
T value;
Node(T value) {
pr = NULL;
lf = NULL;
rg = NULL;
this->value = value;
}
};
template <class T>
class BST
{
public:
void insert_node(T value);
void delete_node(T value);
void print_nodes(void);
BST();
private:
Node<T> *root;
void insert_node(Node<T> *node, T value);
void delete_node(Node<T> *node, T value);
void transplant(Node<T> *x, Node<T> *y);
void print_nodes(Node<T> *node);
Node<T> *create_node(Node<T> *pr, T value);
Node<T> *min_node(Node<T> *node);
};
template <class T>
BST<T>::BST(void)
{
root = NULL;
}
template <class T>
void BST<T>::insert_node(Node<T> *node, T value)
{
if (node == NULL)
root = new Node<T>(value);
else if (node->value > value) {
if (node->lf)
insert_node(node->lf, value);
else {
Node<T> *new_node = new Node<T>(value);
node->lf = new_node;
new_node->pr = node;
}
} else {
if (node->rg)
insert_node(node->rg, value);
else {
Node<T> *new_node = new Node<T>(value);
node->rg = new_node;
new_node->pr = node;
}
}
}
template <class T>
void BST<T>::insert_node(T value)
{
insert_node(root, value);
}
template <class T>
void BST<T>::transplant(Node<T> *x, Node<T> *y)
{
if (x == root)
root = y;
if (x == x->pr->rg)
x->pr->rg = y;
else
x->pr->lf = y;
if (y)
y->pr = x->pr;
}
template <class T>
Node<T> *BST<T>::min_node(Node<T> *node)
{
if (!node->lf)
return node;
return min_node(node->lf);
}
template <class T>
void BST<T>::delete_node(Node<T> *node, T value)
{
if (node == NULL)
return;
else if (node->value > value)
delete_node(node->lf, value);
else if (node->value < value)
delete_node(node->rg, value);
else {
if (!node->lf)
transplant(node, node->rg);
else if (!node->rg)
transplant(node, node->lf);
else {
Node<T> *s = min_node(node->rg);
if (s->pr != node) {
transplant(s, s->rg);
s->rg = node->rg;
s->rg->pr = s;
}
transplant(node, s);
s->lf = node->lf;
s->lf->pr = s;
}
}
}
template <class T>
void BST<T>::delete_node(T value)
{
delete_node(root, value);
}
template <class T>
void BST<T>::print_nodes(Node<T> *node)
{
if (!node)
return;
print_nodes(node->lf);
std::cout << "Value: " << node->value << std::endl;
print_nodes(node->rg);
}
template <class T>
void BST<T>::print_nodes(void)
{
print_nodes(root);
}
int main(int argc, char *argv[])
{
std::cout << "Binary Search Tree!" << std::endl;
int number_of_test_values = 10;
BST<int> tree = BST<int>();
std::cout << "Inserting <" << number_of_test_values;
std::cout << "> random values...." << std::endl;
srand(time(NULL));
int del_value;
for (int i=0; i < number_of_test_values; i++) {
int value = rand() % 100;
if (i == 5)
del_value = value;
std::cout << "Inserting " << value << std::endl;
tree.insert_node(value);
}
tree.print_nodes();
std::cout << "Deleting " << del_value << std::endl;
tree.delete_node(del_value);
tree.print_nodes();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 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: Nathan Binkert
*/
#include <fstream>
#include <iomanip>
#include <list>
#include <map>
#include <string>
#include "base/callback.hh"
#include "base/cprintf.hh"
#include "base/debug.hh"
#include "base/hostinfo.hh"
#include "base/misc.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "base/trace.hh"
using namespace std;
namespace Stats {
std::string Info::separatorString = "::";
typedef map<const void *, Info *> MapType;
// We wrap these in a function to make sure they're built in time.
list<Info *> &
statsList()
{
static list<Info *> the_list;
return the_list;
}
MapType &
statsMap()
{
static MapType the_map;
return the_map;
}
void
InfoAccess::setInfo(Info *info)
{
if (statsMap().find(this) != statsMap().end())
panic("shouldn't register stat twice!");
statsList().push_back(info);
#ifndef NDEBUG
pair<MapType::iterator, bool> result =
#endif
statsMap().insert(make_pair(this, info));
assert(result.second && "this should never fail");
assert(statsMap().find(this) != statsMap().end());
}
void
InfoAccess::setParams(const StorageParams *params)
{
info()->storageParams = params;
}
void
InfoAccess::setInit()
{
info()->flags.set(init);
}
Info *
InfoAccess::info()
{
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
const Info *
InfoAccess::info() const
{
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
StorageParams::~StorageParams()
{
}
typedef map<std::string, Info *> NameMapType;
NameMapType &
nameMap()
{
static NameMapType the_map;
return the_map;
}
int Info::id_count = 0;
int debug_break_id = -1;
Info::Info()
: flags(none), precision(-1), prereq(0), storageParams(NULL)
{
id = id_count++;
if (debug_break_id >= 0 and debug_break_id == id)
Debug::breakpoint();
}
Info::~Info()
{
}
void
Info::setName(const string &name)
{
pair<NameMapType::iterator, bool> p =
nameMap().insert(make_pair(name, this));
Info *other = p.first->second;
bool result = p.second;
if (!result) {
// using other->name instead of just name to avoid a compiler
// warning. They should be the same.
panic("same statistic name used twice! name=%s\n", other->name);
}
this->name = name;
}
bool
Info::less(Info *stat1, Info *stat2)
{
const string &name1 = stat1->name;
const string &name2 = stat2->name;
vector<string> v1;
vector<string> v2;
tokenize(v1, name1, '.');
tokenize(v2, name2, '.');
size_type last = min(v1.size(), v2.size()) - 1;
for (off_type i = 0; i < last; ++i)
if (v1[i] != v2[i])
return v1[i] < v2[i];
// Special compare for last element.
if (v1[last] == v2[last])
return v1.size() < v2.size();
else
return v1[last] < v2[last];
return false;
}
bool
Info::baseCheck() const
{
if (!(flags & Stats::init)) {
#ifdef DEBUG
cprintf("this is stat number %d\n", id);
#endif
panic("Not all stats have been initialized");
return false;
}
if ((flags & display) && name.empty()) {
panic("all printable stats must be named");
return false;
}
return true;
}
void
Info::enable()
{
}
void
VectorInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
VectorDistInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
Vector2dInfo::enable()
{
if (subnames.size() < x)
subnames.resize(x);
if (subdescs.size() < x)
subdescs.resize(x);
if (y_subnames.size() < y)
y_subnames.resize(y);
}
void
HistStor::grow_out()
{
int size = cvec.size();
int zero = size / 2; // round down!
int top_half = zero + (size - zero + 1) / 2; // round up!
int bottom_half = (size - zero) / 2; // round down!
// grow down
int low_pair = zero - 1;
for (int i = zero - 1; i >= bottom_half; i--) {
cvec[i] = cvec[low_pair];
if (low_pair - 1 >= 0)
cvec[i] += cvec[low_pair - 1];
low_pair -= 2;
}
assert(low_pair == 0 || low_pair == -1 || low_pair == -2);
for (int i = bottom_half - 1; i >= 0; i--)
cvec[i] = Counter();
// grow up
int high_pair = zero;
for (int i = zero; i < top_half; i++) {
cvec[i] = cvec[high_pair];
if (high_pair + 1 < size)
cvec[i] += cvec[high_pair + 1];
high_pair += 2;
}
assert(high_pair == size || high_pair == size + 1);
for (int i = top_half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
min_bucket *= 2;
bucket_size *= 2;
}
void
HistStor::grow_convert()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
//bool even = (size & 1) == 0;
int pair = size - 1;
for (int i = size - 1; i >= half; --i) {
cvec[i] = cvec[pair];
if (pair - 1 >= 0)
cvec[i] += cvec[pair - 1];
pair -= 2;
}
for (int i = half - 1; i >= 0; i--)
cvec[i] = Counter();
min_bucket = -max_bucket;// - (even ? bucket_size : 0);
bucket_size *= 2;
}
void
HistStor::grow_up()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
int pair = 0;
for (int i = 0; i < half; i++) {
cvec[i] = cvec[pair];
if (pair + 1 < size)
cvec[i] += cvec[pair + 1];
pair += 2;
}
assert(pair == size || pair == size + 1);
for (int i = half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
bucket_size *= 2;
}
Formula::Formula()
{
}
Formula::Formula(Temp r)
{
root = r;
setInit();
assert(size());
}
const Formula &
Formula::operator=(Temp r)
{
assert(!root && "Can't change formulas");
root = r;
setInit();
assert(size());
return *this;
}
const Formula &
Formula::operator+=(Temp r)
{
if (root)
root = NodePtr(new BinaryNode<std::plus<Result> >(root, r));
else {
root = r;
setInit();
}
assert(size());
return *this;
}
void
Formula::result(VResult &vec) const
{
if (root)
vec = root->result();
}
Result
Formula::total() const
{
return root ? root->total() : 0.0;
}
size_type
Formula::size() const
{
if (!root)
return 0;
else
return root->size();
}
void
Formula::reset()
{
}
bool
Formula::zero() const
{
VResult vec;
result(vec);
for (VResult::size_type i = 0; i < vec.size(); ++i)
if (vec[i] != 0.0)
return false;
return true;
}
string
Formula::str() const
{
return root ? root->str() : "";
}
void
enable()
{
typedef list<Info *>::iterator iter_t;
iter_t i, end = statsList().end();
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
assert(info);
if (!info->check() || !info->baseCheck())
panic("stat check failed for '%s' %d\n", info->name, info->id);
}
off_t j = 0;
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
if (!(info->flags & display))
info->name = "__Stat" + to_string(j++);
}
statsList().sort(Info::less);
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
info->enable();
}
}
void
prepare()
{
list<Info *>::iterator i = statsList().begin();
list<Info *>::iterator end = statsList().end();
while (i != end) {
Info *info = *i;
info->prepare();
++i;
}
}
CallbackQueue resetQueue;
void
reset()
{
list<Info *>::iterator i = statsList().begin();
list<Info *>::iterator end = statsList().end();
while (i != end) {
Info *info = *i;
info->reset();
++i;
}
resetQueue.process();
}
void
registerResetCallback(Callback *cb)
{
resetQueue.add(cb);
}
} // namespace Stats
<commit_msg>stats: ensure that stat names are valid<commit_after>/*
* Copyright (c) 2003-2005 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: Nathan Binkert
*/
#include <fstream>
#include <iomanip>
#include <list>
#include <map>
#include <string>
#include "base/callback.hh"
#include "base/cprintf.hh"
#include "base/debug.hh"
#include "base/hostinfo.hh"
#include "base/misc.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "base/trace.hh"
using namespace std;
namespace Stats {
std::string Info::separatorString = "::";
typedef map<const void *, Info *> MapType;
// We wrap these in a function to make sure they're built in time.
list<Info *> &
statsList()
{
static list<Info *> the_list;
return the_list;
}
MapType &
statsMap()
{
static MapType the_map;
return the_map;
}
void
InfoAccess::setInfo(Info *info)
{
if (statsMap().find(this) != statsMap().end())
panic("shouldn't register stat twice!");
statsList().push_back(info);
#ifndef NDEBUG
pair<MapType::iterator, bool> result =
#endif
statsMap().insert(make_pair(this, info));
assert(result.second && "this should never fail");
assert(statsMap().find(this) != statsMap().end());
}
void
InfoAccess::setParams(const StorageParams *params)
{
info()->storageParams = params;
}
void
InfoAccess::setInit()
{
info()->flags.set(init);
}
Info *
InfoAccess::info()
{
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
const Info *
InfoAccess::info() const
{
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
StorageParams::~StorageParams()
{
}
typedef map<std::string, Info *> NameMapType;
NameMapType &
nameMap()
{
static NameMapType the_map;
return the_map;
}
int Info::id_count = 0;
int debug_break_id = -1;
Info::Info()
: flags(none), precision(-1), prereq(0), storageParams(NULL)
{
id = id_count++;
if (debug_break_id >= 0 and debug_break_id == id)
Debug::breakpoint();
}
Info::~Info()
{
}
bool
validateStatName(const string &name)
{
if (name.empty())
return false;
vector<string> vec;
tokenize(vec, name, '.');
vector<string>::const_iterator item = vec.begin();
while (item != vec.end()) {
if (item->empty())
return false;
string::const_iterator c = item->begin();
// The first character is different
if (!isalpha(*c) && *c != '_')
return false;
// The rest of the characters have different rules.
while (++c != item->end()) {
if (!isalnum(*c) && *c != '_')
return false;
}
++item;
}
return true;
}
void
Info::setName(const string &name)
{
if (!validateStatName(name))
panic("invalid stat name '%s'", name);
pair<NameMapType::iterator, bool> p =
nameMap().insert(make_pair(name, this));
Info *other = p.first->second;
bool result = p.second;
if (!result) {
// using other->name instead of just name to avoid a compiler
// warning. They should be the same.
panic("same statistic name used twice! name=%s\n", other->name);
}
this->name = name;
}
bool
Info::less(Info *stat1, Info *stat2)
{
const string &name1 = stat1->name;
const string &name2 = stat2->name;
vector<string> v1;
vector<string> v2;
tokenize(v1, name1, '.');
tokenize(v2, name2, '.');
size_type last = min(v1.size(), v2.size()) - 1;
for (off_type i = 0; i < last; ++i)
if (v1[i] != v2[i])
return v1[i] < v2[i];
// Special compare for last element.
if (v1[last] == v2[last])
return v1.size() < v2.size();
else
return v1[last] < v2[last];
return false;
}
bool
Info::baseCheck() const
{
if (!(flags & Stats::init)) {
#ifdef DEBUG
cprintf("this is stat number %d\n", id);
#endif
panic("Not all stats have been initialized");
return false;
}
if ((flags & display) && name.empty()) {
panic("all printable stats must be named");
return false;
}
return true;
}
void
Info::enable()
{
}
void
VectorInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
VectorDistInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
Vector2dInfo::enable()
{
if (subnames.size() < x)
subnames.resize(x);
if (subdescs.size() < x)
subdescs.resize(x);
if (y_subnames.size() < y)
y_subnames.resize(y);
}
void
HistStor::grow_out()
{
int size = cvec.size();
int zero = size / 2; // round down!
int top_half = zero + (size - zero + 1) / 2; // round up!
int bottom_half = (size - zero) / 2; // round down!
// grow down
int low_pair = zero - 1;
for (int i = zero - 1; i >= bottom_half; i--) {
cvec[i] = cvec[low_pair];
if (low_pair - 1 >= 0)
cvec[i] += cvec[low_pair - 1];
low_pair -= 2;
}
assert(low_pair == 0 || low_pair == -1 || low_pair == -2);
for (int i = bottom_half - 1; i >= 0; i--)
cvec[i] = Counter();
// grow up
int high_pair = zero;
for (int i = zero; i < top_half; i++) {
cvec[i] = cvec[high_pair];
if (high_pair + 1 < size)
cvec[i] += cvec[high_pair + 1];
high_pair += 2;
}
assert(high_pair == size || high_pair == size + 1);
for (int i = top_half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
min_bucket *= 2;
bucket_size *= 2;
}
void
HistStor::grow_convert()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
//bool even = (size & 1) == 0;
int pair = size - 1;
for (int i = size - 1; i >= half; --i) {
cvec[i] = cvec[pair];
if (pair - 1 >= 0)
cvec[i] += cvec[pair - 1];
pair -= 2;
}
for (int i = half - 1; i >= 0; i--)
cvec[i] = Counter();
min_bucket = -max_bucket;// - (even ? bucket_size : 0);
bucket_size *= 2;
}
void
HistStor::grow_up()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
int pair = 0;
for (int i = 0; i < half; i++) {
cvec[i] = cvec[pair];
if (pair + 1 < size)
cvec[i] += cvec[pair + 1];
pair += 2;
}
assert(pair == size || pair == size + 1);
for (int i = half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
bucket_size *= 2;
}
Formula::Formula()
{
}
Formula::Formula(Temp r)
{
root = r;
setInit();
assert(size());
}
const Formula &
Formula::operator=(Temp r)
{
assert(!root && "Can't change formulas");
root = r;
setInit();
assert(size());
return *this;
}
const Formula &
Formula::operator+=(Temp r)
{
if (root)
root = NodePtr(new BinaryNode<std::plus<Result> >(root, r));
else {
root = r;
setInit();
}
assert(size());
return *this;
}
void
Formula::result(VResult &vec) const
{
if (root)
vec = root->result();
}
Result
Formula::total() const
{
return root ? root->total() : 0.0;
}
size_type
Formula::size() const
{
if (!root)
return 0;
else
return root->size();
}
void
Formula::reset()
{
}
bool
Formula::zero() const
{
VResult vec;
result(vec);
for (VResult::size_type i = 0; i < vec.size(); ++i)
if (vec[i] != 0.0)
return false;
return true;
}
string
Formula::str() const
{
return root ? root->str() : "";
}
void
enable()
{
typedef list<Info *>::iterator iter_t;
iter_t i, end = statsList().end();
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
assert(info);
if (!info->check() || !info->baseCheck())
panic("stat check failed for '%s' %d\n", info->name, info->id);
}
off_t j = 0;
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
if (!(info->flags & display))
info->name = "__Stat" + to_string(j++);
}
statsList().sort(Info::less);
for (i = statsList().begin(); i != end; ++i) {
Info *info = *i;
info->enable();
}
}
void
prepare()
{
list<Info *>::iterator i = statsList().begin();
list<Info *>::iterator end = statsList().end();
while (i != end) {
Info *info = *i;
info->prepare();
++i;
}
}
CallbackQueue resetQueue;
void
reset()
{
list<Info *>::iterator i = statsList().begin();
list<Info *>::iterator end = statsList().end();
while (i != end) {
Info *info = *i;
info->reset();
++i;
}
resetQueue.process();
}
void
registerResetCallback(Callback *cb)
{
resetQueue.add(cb);
}
} // namespace Stats
<|endoftext|> |
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <cinttypes>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <iostream>
#include <libs/include/Socket.h>
#include <libs/include/TSCTimer.h>
#include <libs/include/Timer.h>
#include <memory>
#include <stdio.h>
#include <unistd.h>
const char *classname = "UDPRaw Detector";
#define TSC_MHZ 3000
/** ----------------------------------------------------- */
class UDPRaw : public Detector {
public:
UDPRaw(BaseSettings settings);
~UDPRaw() { std::cout << " UDPRaw destroyed" << std::endl; }
void input_thread();
const char *detectorname();
};
const char *UDPRaw::detectorname() { return classname; }
UDPRaw::UDPRaw(BaseSettings settings) : Detector("UDPRaw", settings) {
std::function<void()> inputFunc = [this]() { UDPRaw::input_thread(); };
AddThreadFunction(inputFunc, "input");
std::cout << " UDPRaw created" << std::endl;
}
void UDPRaw::input_thread() {
uint64_t rx_total = 0;
uint64_t rx = 0;
uint64_t rxp = 0;
const int B1M = 1000000;
Socket::Endpoint local(EFUSettings.DetectorAddress.c_str(),
EFUSettings.DetectorPort);
UDPServer raw(local);
raw.setbuffers(4000000, 4000000);
// raw.settimeout(0, 100000);
raw.printbuffers();
Timer rate_timer;
TSCTimer report_timer;
uint32_t seqno = 1;
uint32_t dropped = 0;
uint32_t timeseq = 0;
uint32_t first_dropped = 0;
for (;;) {
char buffer[10000];
auto tmprx = raw.receive(buffer, EFUSettings.DetectorRxBufferSize);
auto tmpseq = *((uint32_t *)buffer);
if (seqno == tmpseq) {
seqno++;
} else {
// printf("seqno: %u, tmpseq: %u\n", seqno, tmpseq);
dropped += (tmpseq - seqno);
seqno = tmpseq + 1;
}
if (tmprx > 0) {
rx += tmprx;
rxp++;
}
if (report_timer.timetsc() >=
EFUSettings.UpdateIntervalSec * 1000000UL * TSC_MHZ) {
timeseq++;
auto usecs = rate_timer.timeus();
if (timeseq == 2) {
first_dropped = dropped;
printf("Recorded %d dropped frames as baseline\n", first_dropped);
}
rx_total += rx;
printf("Rx rate: %.2f Mbps, %.0f pps rx %" PRIu64 " MB (total: %" PRIu64
" MB) %" PRIu64 " usecs, seq_err %u, PER %.2e\n",
rx * 8.0 / usecs, rxp * 1000000.0 / usecs, rx / B1M,
rx_total / B1M, usecs, dropped - first_dropped,
1.0 * (dropped - first_dropped) / (seqno - first_dropped));
rx = 0;
rxp = 0;
rate_timer.now();
report_timer.now();
}
}
}
/** ----------------------------------------------------- */
class UDPRawFactory : public DetectorFactory {
public:
std::shared_ptr<Detector> create(BaseSettings settings) {
return std::shared_ptr<Detector>(new UDPRaw(settings));
}
};
UDPRawFactory Factory;
<commit_msg>UDP detector module fix.<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <cinttypes>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <iostream>
#include <libs/include/Socket.h>
#include <libs/include/TSCTimer.h>
#include <libs/include/Timer.h>
#include <memory>
#include <stdio.h>
#include <unistd.h>
const char *classname = "UDPRaw Detector";
#define TSC_MHZ 3000
/** ----------------------------------------------------- */
class UDPRaw : public Detector {
public:
UDPRaw(BaseSettings settings);
~UDPRaw() { std::cout << " UDPRaw destroyed" << std::endl; }
void input_thread();
const char *detectorname();
};
const char *UDPRaw::detectorname() { return classname; }
UDPRaw::UDPRaw(BaseSettings settings) : Detector("UDPRaw", settings) {
std::function<void()> inputFunc = [this]() { UDPRaw::input_thread(); };
AddThreadFunction(inputFunc, "input");
std::cout << " UDPRaw created" << std::endl;
}
void UDPRaw::input_thread() {
uint64_t rx_total = 0;
uint64_t rx = 0;
uint64_t rxp = 0;
const int B1M = 1000000;
Socket::Endpoint local(EFUSettings.DetectorAddress.c_str(),
EFUSettings.DetectorPort);
UDPServer raw(local);
raw.setbuffers(4000000, 4000000);
raw.settimeout(0, 100000);
raw.printbuffers();
Timer rate_timer;
TSCTimer report_timer;
uint32_t seqno = 1;
uint32_t dropped = 0;
uint32_t timeseq = 0;
uint32_t first_dropped = 0;
while (runThreads) {
char buffer[10000];
auto tmprx = raw.receive(buffer, EFUSettings.DetectorRxBufferSize); //Fix this, its blocking
auto tmpseq = *((uint32_t *)buffer);
if (seqno == tmpseq) {
seqno++;
} else {
// printf("seqno: %u, tmpseq: %u\n", seqno, tmpseq);
dropped += (tmpseq - seqno);
seqno = tmpseq + 1;
}
if (tmprx > 0) {
rx += tmprx;
rxp++;
}
if (report_timer.timetsc() >=
EFUSettings.UpdateIntervalSec * 1000000UL * TSC_MHZ) {
timeseq++;
auto usecs = rate_timer.timeus();
if (timeseq == 2) {
first_dropped = dropped;
printf("Recorded %d dropped frames as baseline\n", first_dropped);
}
rx_total += rx;
printf("Rx rate: %.2f Mbps, %.0f pps rx %" PRIu64 " MB (total: %" PRIu64
" MB) %" PRIu64 " usecs, seq_err %u, PER %.2e\n",
rx * 8.0 / usecs, rxp * 1000000.0 / usecs, rx / B1M,
rx_total / B1M, usecs, dropped - first_dropped,
1.0 * (dropped - first_dropped) / (seqno - first_dropped));
rx = 0;
rxp = 0;
rate_timer.now();
report_timer.now();
}
}
}
/** ----------------------------------------------------- */
void SetCLIArguments(CLI::App __attribute__((unused)) & parser) {}
PopulateCLIParser PopulateParser{SetCLIArguments};
class UDPRawFactory : public DetectorFactory {
public:
std::shared_ptr<Detector> create(BaseSettings settings) {
return std::shared_ptr<Detector>(new UDPRaw(settings));
}
};
UDPRawFactory Factory;
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/FixedSizeThreadPool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-logtable/TableRepository.h"
#include "fnord-logtable/TableJanitor.h"
#include "fnord-logtable/TableReplication.h"
#include "fnord-logtable/ArtifactReplication.h"
#include "fnord-logtable/ArtifactIndexReplication.h"
#include "fnord-logtable/NumericBoundsSummary.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-tsdb/TSDBNode.h"
#include "common.h"
#include "schemas.h"
#include "ModelReplication.h"
using namespace fnord;
std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;
void quit(int n) {
shutdown_sig = true;
fnord::logInfo("cm.chunkserver", "Shutting down...");
// FIXPAUL: wait for http server stop...
ev.shutdown();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
/* shutdown hook */
shutdown_sig = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"readonly",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"readonly",
"readonly");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"datadir path",
"<path>");
flags.defineFlag(
"replicate_from",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<url>");
flags.defineFlag(
"fsck",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"fsck",
"fsck");
flags.defineFlag(
"repair",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"repair",
"repair");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* args */
auto dir = flags.getString("datadir");
auto readonly = flags.isSet("readonly");
auto replica = flags.getString("replica");
auto repl_sources = flags.getStrings("replicate_from");
Vector<URI> artifact_sources;
for (const auto& rep : repl_sources) {
artifact_sources.emplace_back(
URI(StringUtil::format("http://$0:7005/", rep)));
}
/* start http server and worker pools */
fnord::thread::ThreadPool tpool;
fnord::thread::FixedSizeThreadPool wpool(8);
fnord::thread::FixedSizeThreadPool repl_wpool(8);
http::HTTPConnectionPool http(&ev);
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
wpool.start();
repl_wpool.start();
/* artifact replication */
logtable::ArtifactReplication artifact_replication(
&http,
&repl_wpool,
8);
/* model replication */
ModelReplication model_replication;
if (!readonly) {
model_replication.addArtifactIndexReplication(
"termstats",
dir,
artifact_sources,
&artifact_replication,
&http);
}
/* logtable */
logtable::TableRepository table_repo(
dir,
replica,
readonly,
&wpool);
auto joined_sessions_schema = joinedSessionsSchema();
table_repo.addTable("joined_sessions-dawanda", joined_sessions_schema);
table_repo.addTable("index_feed-dawanda", indexChangeRequestSchema());
Set<String> tbls = { "joined_sessions-dawanda", "index_feed-dawanda" };
logtable::TableReplication table_replication(&http);
if (!readonly) {
for (const auto& tbl : tbls) {
auto table = table_repo.findTableWriter(tbl);
if (StringUtil::beginsWith(tbl, "joined_sessions")) {
table->addSummary([joined_sessions_schema] () {
return new logtable::NumericBoundsSummaryBuilder(
"search_queries.time-bounds",
joined_sessions_schema.id("search_queries.time"));
});
}
table->runConsistencyCheck(
flags.isSet("fsck"),
flags.isSet("repair"));
for (const auto& rep : repl_sources) {
table_replication.replicateTableFrom(
table,
URI(StringUtil::format("http://$0:7003/logtable", rep)));
}
if (artifact_sources.size() > 0) {
artifact_replication.replicateArtifactsFrom(
table->artifactIndex(),
artifact_sources);
}
}
}
logtable::TableJanitor table_janitor(&table_repo);
//if (!readonly) {
// table_janitor.start();
// table_replication.start();
// artifact_replication.start();
// model_replication.start();
//}
logtable::LogTableServlet logtable_servlet(&table_repo);
http_router.addRouteByPrefixMatch("/logtable", &logtable_servlet, &tpool);
tsdb::TSDBNode tsdb_node("xxx", "/tmp/tsdb");
ev.run();
//if (!readonly) {
// table_janitor.stop();
// table_janitor.check();
// table_replication.stop();
// artifact_replication.stop();
// model_replication.stop();
//}
fnord::logInfo("cm.chunkserver", "Exiting...");
exit(0);
}
<commit_msg>TSDBServlet stub<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/FixedSizeThreadPool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-logtable/TableRepository.h"
#include "fnord-logtable/TableJanitor.h"
#include "fnord-logtable/TableReplication.h"
#include "fnord-logtable/ArtifactReplication.h"
#include "fnord-logtable/ArtifactIndexReplication.h"
#include "fnord-logtable/NumericBoundsSummary.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-tsdb/TSDBNode.h"
#include "fnord-tsdb/TSDBServlet.h"
#include "common.h"
#include "schemas.h"
#include "ModelReplication.h"
using namespace fnord;
std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;
void quit(int n) {
shutdown_sig = true;
fnord::logInfo("cm.chunkserver", "Shutting down...");
// FIXPAUL: wait for http server stop...
ev.shutdown();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
/* shutdown hook */
shutdown_sig = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"readonly",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"readonly",
"readonly");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"datadir path",
"<path>");
flags.defineFlag(
"replicate_from",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<url>");
flags.defineFlag(
"fsck",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"fsck",
"fsck");
flags.defineFlag(
"repair",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"repair",
"repair");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* args */
auto dir = flags.getString("datadir");
auto readonly = flags.isSet("readonly");
auto replica = flags.getString("replica");
auto repl_sources = flags.getStrings("replicate_from");
Vector<URI> artifact_sources;
for (const auto& rep : repl_sources) {
artifact_sources.emplace_back(
URI(StringUtil::format("http://$0:7005/", rep)));
}
/* start http server and worker pools */
fnord::thread::ThreadPool tpool;
fnord::thread::FixedSizeThreadPool wpool(8);
fnord::thread::FixedSizeThreadPool repl_wpool(8);
http::HTTPConnectionPool http(&ev);
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
wpool.start();
repl_wpool.start();
/* artifact replication */
logtable::ArtifactReplication artifact_replication(
&http,
&repl_wpool,
8);
/* model replication */
ModelReplication model_replication;
if (!readonly) {
model_replication.addArtifactIndexReplication(
"termstats",
dir,
artifact_sources,
&artifact_replication,
&http);
}
/* logtable */
logtable::TableRepository table_repo(
dir,
replica,
readonly,
&wpool);
auto joined_sessions_schema = joinedSessionsSchema();
table_repo.addTable("joined_sessions-dawanda", joined_sessions_schema);
table_repo.addTable("index_feed-dawanda", indexChangeRequestSchema());
Set<String> tbls = { "joined_sessions-dawanda", "index_feed-dawanda" };
logtable::TableReplication table_replication(&http);
if (!readonly) {
for (const auto& tbl : tbls) {
auto table = table_repo.findTableWriter(tbl);
if (StringUtil::beginsWith(tbl, "joined_sessions")) {
table->addSummary([joined_sessions_schema] () {
return new logtable::NumericBoundsSummaryBuilder(
"search_queries.time-bounds",
joined_sessions_schema.id("search_queries.time"));
});
}
table->runConsistencyCheck(
flags.isSet("fsck"),
flags.isSet("repair"));
for (const auto& rep : repl_sources) {
table_replication.replicateTableFrom(
table,
URI(StringUtil::format("http://$0:7003/logtable", rep)));
}
if (artifact_sources.size() > 0) {
artifact_replication.replicateArtifactsFrom(
table->artifactIndex(),
artifact_sources);
}
}
}
logtable::TableJanitor table_janitor(&table_repo);
//if (!readonly) {
// table_janitor.start();
// table_replication.start();
// artifact_replication.start();
// model_replication.start();
//}
logtable::LogTableServlet logtable_servlet(&table_repo);
http_router.addRouteByPrefixMatch("/logtable", &logtable_servlet, &tpool);
tsdb::TSDBNode tsdb_node("xxx", "/tmp/tsdb");
tsdb::TSDBServlet tsdb_servlet(&tsdb_node);
http_router.addRouteByPrefixMatch("/tsdb", &tsdb_servlet, &tpool);
ev.run();
//if (!readonly) {
// table_janitor.stop();
// table_janitor.check();
// table_replication.stop();
// artifact_replication.stop();
// model_replication.stop();
//}
fnord::logInfo("cm.chunkserver", "Exiting...");
exit(0);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <stdexcept>
#include "CallIRBuilder.h"
#include "Registers.h"
#include "SMT2Lib.h"
#include "SymbolicElement.h"
CallIRBuilder::CallIRBuilder(uint64_t address, const std::string &disassembly):
BaseIRBuilder(address, disassembly) {
}
static SymbolicElement *alignStack(AnalysisProcessor &ap, uint64_t writeSize)
{
SymbolicElement *se;
std::stringstream expr, op1, op2;
uint64_t symReg = ap.getRegSymbolicID(ID_RSP);
/*
* Create the SMT semantic.
*/
if (symReg != UNSET)
op1 << "#" << std::dec << symReg;
else
op1 << smt2lib::bv(ap.getRegisterValue(ID_RSP), writeSize * REG_SIZE);
op2 << smt2lib::bv(REG_SIZE, writeSize * REG_SIZE);
expr << smt2lib::bvsub(op1.str(), op2.str());
/* Create the symbolic element */
se = ap.createRegSE(expr, ID_RSP, "Aligns stack");
/* Apply the taint */
se->isTainted = ap.isRegTainted(ID_RSP);
return se;
}
void CallIRBuilder::reg(AnalysisProcessor &ap, Inst &inst) const {
std::cout << "TODO" << std::endl;
//OneOperandTemplate::stop(this->disas);
}
void CallIRBuilder::imm(AnalysisProcessor &ap, Inst &inst) const {
std::cout << "TODO" << std::endl;
//OneOperandTemplate::stop(this->disas);
}
void CallIRBuilder::mem(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr1;//, expr2;
//uint64_t imm = std::get<1>(this->operands[1]);
uint64_t memDst = std::get<1>(this->operands[0]); // The dst memory write
uint32_t writeSize = std::get<2>(this->operands[0]);
/* Create the SMT semantic side effect */
inst.addElement(alignStack(ap, writeSize));
/* Create the SMT semantic */
/* *RSP = Next_RIP */
expr1 << smt2lib::bv(this->nextAddress, writeSize * REG_SIZE);
/* Create the symbolic element */
se = ap.createMemSE(expr1, memDst, "Saved RIP");
/* Apply the taint */
ap.assignmentSpreadTaintMemImm(se, memDst, writeSize);
/* Add the symbolic element to the current inst */
inst.addElement(se);
// TODO: How really works XED_CALL ??
//
// /* Create the SMT semantic */
// /* RIP = imm */
// expr2 << smt2lib::bv(imm, writeSize * REG_SIZE);
//
// /* Create the symbolic element */
// se = ap.createRegSE(expr2, ID_RIP, "RIP");
//
// /* Apply the taint */
// ap.assignmentSpreadTaintRegImm(se, ID_RIP);
//
// /* Add the symbolic element to the current inst */
// inst.addElement(se);
}
void CallIRBuilder::none(AnalysisProcessor &ap, Inst &inst) const {
OneOperandTemplate::stop(this->disas);
}
Inst *CallIRBuilder::process(AnalysisProcessor &ap) const {
this->checkSetup();
Inst *inst = new Inst(ap.getThreadID(), this->address, this->disas);
try {
this->templateMethod(ap, *inst, this->operands, "CALL");
ap.incNumberOfExpressions(inst->numberOfElements()); /* Used for statistics */
}
catch (std::exception &e) {
delete inst;
throw;
}
return inst;
}
<commit_msg>Fix call<commit_after>#include <iostream>
#include <sstream>
#include <stdexcept>
#include "CallIRBuilder.h"
#include "Registers.h"
#include "SMT2Lib.h"
#include "SymbolicElement.h"
CallIRBuilder::CallIRBuilder(uint64_t address, const std::string &disassembly):
BaseIRBuilder(address, disassembly) {
}
static SymbolicElement *alignStack(AnalysisProcessor &ap, uint64_t writeSize)
{
SymbolicElement *se;
std::stringstream expr, op1, op2;
uint64_t symReg = ap.getRegSymbolicID(ID_RSP);
/*
* Create the SMT semantic.
*/
if (symReg != UNSET)
op1 << "#" << std::dec << symReg;
else
op1 << smt2lib::bv(ap.getRegisterValue(ID_RSP), writeSize * REG_SIZE);
op2 << smt2lib::bv(REG_SIZE, writeSize * REG_SIZE);
expr << smt2lib::bvsub(op1.str(), op2.str());
/* Create the symbolic element */
se = ap.createRegSE(expr, ID_RSP, "Aligns stack");
/* Apply the taint */
se->isTainted = ap.isRegTainted(ID_RSP);
return se;
}
void CallIRBuilder::reg(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr1, expr2;
uint64_t reg = std::get<1>(this->operands[0]);
uint32_t regSize = std::get<2>(this->operands[0]);
uint64_t memDst = std::get<1>(this->operands[1]); // The dst memory write
uint32_t writeSize = std::get<2>(this->operands[1]);
uint64_t symReg = ap.getRegSymbolicID(reg);
/* Create the SMT semantic side effect */
inst.addElement(alignStack(ap, writeSize));
/* Create the SMT semantic */
/* *RSP = Next_RIP */
expr1 << smt2lib::bv(this->nextAddress, writeSize * REG_SIZE);
/* Create the symbolic element */
se = ap.createMemSE(expr1, memDst, "Saved RIP");
/* Apply the taint */
ap.assignmentSpreadTaintMemImm(se, memDst, writeSize);
/* Add the symbolic element to the current inst */
inst.addElement(se);
/* Create the SMT semantic */
/* RIP = imm */
if (symReg != UNSET)
expr2 << "#" << std::dec << symReg;
else
expr2 << smt2lib::bv(ap.getRegisterValue(reg), regSize * REG_SIZE);
/* Create the symbolic element */
se = ap.createRegSE(expr2, ID_RIP, "RIP");
/* Apply the taint */
ap.assignmentSpreadTaintRegImm(se, ID_RIP);
/* Add the symbolic element to the current inst */
inst.addElement(se);
}
void CallIRBuilder::imm(AnalysisProcessor &ap, Inst &inst) const {
OneOperandTemplate::stop(this->disas);
}
void CallIRBuilder::mem(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr1;//, expr2;
//uint64_t imm = std::get<1>(this->operands[1]);
uint64_t memDst = std::get<1>(this->operands[0]); // The dst memory write
uint32_t writeSize = std::get<2>(this->operands[0]);
/* Create the SMT semantic side effect */
inst.addElement(alignStack(ap, writeSize));
/* Create the SMT semantic */
/* *RSP = Next_RIP */
expr1 << smt2lib::bv(this->nextAddress, writeSize * REG_SIZE);
/* Create the symbolic element */
se = ap.createMemSE(expr1, memDst, "Saved RIP");
/* Apply the taint */
ap.assignmentSpreadTaintMemImm(se, memDst, writeSize);
/* Add the symbolic element to the current inst */
inst.addElement(se);
// TODO: How really works XED_CALL ?? Where is the immediate operand ?
//
// /* Create the SMT semantic */
// /* RIP = imm */
// expr2 << smt2lib::bv(imm, writeSize * REG_SIZE);
//
// /* Create the symbolic element */
// se = ap.createRegSE(expr2, ID_RIP, "RIP");
//
// /* Apply the taint */
// ap.assignmentSpreadTaintRegImm(se, ID_RIP);
//
// /* Add the symbolic element to the current inst */
// inst.addElement(se);
}
void CallIRBuilder::none(AnalysisProcessor &ap, Inst &inst) const {
OneOperandTemplate::stop(this->disas);
}
Inst *CallIRBuilder::process(AnalysisProcessor &ap) const {
this->checkSetup();
Inst *inst = new Inst(ap.getThreadID(), this->address, this->disas);
try {
this->templateMethod(ap, *inst, this->operands, "CALL");
ap.incNumberOfExpressions(inst->numberOfElements()); /* Used for statistics */
}
catch (std::exception &e) {
delete inst;
throw;
}
return inst;
}
<|endoftext|> |
<commit_before><commit_msg>HMI: fix recorder bug<commit_after><|endoftext|> |
<commit_before>/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program 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, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleSetVisibleRankOpcode( WorldPacket& recv_data )
{
CHECK_PACKET_SIZE( recv_data, 4 );
uint32 ChosenRank;
recv_data >> ChosenRank;
if( ChosenRank == 0xFFFFFFFF )
_player->SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
else if( _player->HasKnownTitle( static_cast< RankTitles >( ChosenRank ) ) )
_player->SetUInt32Value( PLAYER_CHOSEN_TITLE, ChosenRank );
}
void HonorHandler::AddHonorPointsToPlayer(Player *pPlayer, uint32 uAmount)
{
pPlayer->HandleProc(PROC_ON_GAIN_EXPIERIENCE, pPlayer, NULL);
pPlayer->m_procCounter = 0;
if( pPlayer->GetMapId() == 559 || pPlayer->GetMapId() == 562 || pPlayer->GetMapId() == 572)
return;
pPlayer->m_honorPoints += uAmount;
pPlayer->m_honorToday += uAmount;
if (pPlayer->m_honorPoints > 75000) pPlayer->m_honorPoints = 75000;
RecalculateHonorFields(pPlayer);
}
int32 HonorHandler::CalculateHonorPointsForKill( Player *pPlayer, Unit* pVictim )
{
// this sucks.. ;p
if( pVictim == NULL )
{
int32 pts = rand() % 100 + 100;
return pts;
}
// Suicide lol
if( pVictim == pPlayer )
return 0;
if( pVictim->GetTypeId() != TYPEID_PLAYER )
return 0;
//use Player::m_honorless, applied with Aura::SpellAuraNoPVPCredit
// How dishonorable, you fiend!
//if( pVictim->HasActiveAura( PLAYER_HONORLESS_TARGET_SPELL ) )
// return 0;
if ( pVictim->GetTypeId() == TYPEID_PLAYER && (static_cast< Player* >(pVictim)->m_honorless || static_cast< Player* >(pVictim)->HasAura(15007)) )
return 0;
uint32 k_level = pPlayer->GetUInt32Value( UNIT_FIELD_LEVEL );
uint32 v_level = pVictim->GetUInt32Value( UNIT_FIELD_LEVEL );
int k_honor = pPlayer->m_honorPoints;
int v_honor = static_cast< Player* >( pVictim )->m_honorPoints;
uint32 k_grey = 0;
if( k_level > 5 && k_level < 40 )
{
k_grey = k_level - 5 - float2int32( floor( ((float)k_level) / 10.0f ) );
}
else
{
k_grey = k_level - 1 - float2int32( floor( ((float)k_level) / 5.0f ) );
}
if( k_honor == 0 )
k_honor = 1;
float diff_level = ((float)v_level - k_grey) / ((float)k_level - k_grey);
if( diff_level > 2 ) diff_level = 2.0f;
if( diff_level < 0 ) diff_level = 0.0f;
float diff_honor = ((float)v_honor) / ((float)k_honor);
if( diff_honor > 3 ) diff_honor = 3.0f;
if( diff_honor < 0 ) diff_honor = 0.0f;
float honor_points = diff_level * ( 150.0f + diff_honor * 60 );
honor_points *= ((float)k_level) / PLAYER_LEVEL_CAP;
honor_points *= World::getSingleton().getRate( RATE_HONOR );
return float2int32( honor_points );
}
void HonorHandler::OnPlayerKilledUnit( Player *pPlayer, Unit* pVictim )
{
if( pVictim == NULL || pPlayer == NULL )
return;
if( pPlayer->GetTypeId() != TYPEID_PLAYER || !pVictim->IsUnit() )
return;
if( !pVictim->IsPlayer() || static_cast< Player* >( pVictim )->m_honorless )
return;
if( pVictim->IsPlayer() )
{
if( pPlayer->m_bg )
{
if( static_cast< Player* >( pVictim )->m_bgTeam == pPlayer->m_bgTeam )
return;
// patch 2.4, players killed >50 times in battlegrounds won't be worth honor for the rest of that bg
if( static_cast<Player*>(pVictim)->m_bgScore.Deaths >= 50 )
return;
}
else
{
if( pPlayer->GetTeam() == static_cast< Player* >( pVictim )->GetTeam() )
return;
}
}
// Calculate points
int32 Points = CalculateHonorPointsForKill(pPlayer, pVictim);
if( Points > 0 )
{
if( pPlayer->m_bg )
{
// hackfix for battlegrounds (since the gorups there are disabled, we need to do this manually)
vector<Player*> toadd;
uint32 t = pPlayer->m_bgTeam;
toadd.reserve(15); // shouldnt have more than this
pPlayer->m_bg->Lock();
set<Player*> * s = &pPlayer->m_bg->m_players[t];
for(set<Player*>::iterator itr = s->begin(); itr != s->end(); ++itr)
{
if((*itr) == pPlayer || (*itr)->isInRange(pPlayer,100.0f))
toadd.push_back(*itr);
}
if( toadd.size() > 0 )
{
uint32 pts = Points / (uint32)toadd.size();
for(vector<Player*>::iterator vtr = toadd.begin(); vtr != toadd.end(); ++vtr)
{
AddHonorPointsToPlayer(*vtr, pts);
(*vtr)->m_killsToday++;
(*vtr)->m_killsLifetime++;
pPlayer->m_bg->HookOnHK(*vtr);
if(pVictim)
{
// Send PVP credit
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = pts * 10;
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
(*vtr)->GetSession()->SendPacket(&data);
}
}
}
pPlayer->m_bg->Unlock();
}
else
{
set<Player*> contributors;
// First loop: Get all the people in the attackermap.
pVictim->UpdateOppFactionSet();
for(std::set<Object*>::iterator itr = pVictim->GetInRangeOppFactsSetBegin(); itr != pVictim->GetInRangeOppFactsSetEnd(); itr++)
{
if(!(*itr)->IsPlayer())
continue;
bool added = false;
Player * plr = (Player*)(*itr);
if(pVictim->CombatStatus.m_attackers.find(plr->GetGUID()) != pVictim->CombatStatus.m_attackers.end())
{
added = true;
contributors.insert(plr);
}
if(added && plr->GetGroup())
{
Group * pGroup = plr->GetGroup();
uint32 groups = pGroup->GetSubGroupCount();
for(uint32 i = 0; i < groups; i++)
{
SubGroup * sg = pGroup->GetSubGroup(i);
if(!sg) continue;
for(GroupMembersSet::iterator itr2 = sg->GetGroupMembersBegin(); itr2 != sg->GetGroupMembersEnd(); itr2++)
{
PlayerInfo * pi = (*itr2);
Player * gm = objmgr.GetPlayer(pi->guid);
if(!gm) continue;
if(gm->isInRange(pVictim, 100.0f))
contributors.insert(gm);
}
}
}
}
for(set<Player*>::iterator itr = contributors.begin(); itr != contributors.end(); itr++)
{
Player * pAffectedPlayer = (*itr);
if(!pAffectedPlayer) continue;
pAffectedPlayer->m_killsToday++;
pAffectedPlayer->m_killsLifetime++;
if(pAffectedPlayer->m_bg)
pAffectedPlayer->m_bg->HookOnHK(pAffectedPlayer);
int32 contributorpts = Points / (int32)contributors.size();
AddHonorPointsToPlayer(pAffectedPlayer, contributorpts);
if(pVictim->IsPlayer())
{
sHookInterface.OnHonorableKill(pAffectedPlayer, (Player*)pVictim);
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = contributorpts * 10; // Why *10?
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
pAffectedPlayer->GetSession()->SendPacket(&data);
}
if(pAffectedPlayer->GetZoneId() == 3518)
{
// Add Halaa Battle Token
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 33004 : 33005);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
// If we are in Hellfire Peninsula <http://www.wowwiki.com/Hellfire_Peninsula#World_PvP_-_Hellfire_Fortifications>
if(pAffectedPlayer->GetZoneId() == 3483)
{
// Hellfire Horde Controlled Towers
if(pAffectedPlayer->GetMapMgr()->GetWorldState(2478) != 3 && pAffectedPlayer->GetTeam() == 1)
return;
// Hellfire Alliance Controlled Towers
if(pAffectedPlayer->GetMapMgr()->GetWorldState(2476) != 3 && pAffectedPlayer->GetTeam() == 0)
return;
// Add Mark of Thrallmar/Honor Hold
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 32158 : 32155);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
}
}
}
}
void HonorHandler::RecalculateHonorFields(Player *pPlayer)
{
pPlayer->SetUInt32Value(PLAYER_FIELD_KILLS, uint16(pPlayer->m_killsToday) | ( pPlayer->m_killsYesterday << 16 ) );
pPlayer->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, pPlayer->m_honorToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, pPlayer->m_honorYesterday);
pPlayer->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, pPlayer->m_killsLifetime);
pPlayer->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, pPlayer->m_honorPoints);
pPlayer->SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, pPlayer->m_arenaPoints);
}
bool ChatHandler::HandleAddKillCommand(const char* args, WorldSession* m_session)
{
uint32 KillAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u kills to player %s.", KillAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor kills added to your character.", KillAmount);
for(uint32 i = 0; i < KillAmount; ++i)
HonorHandler::OnPlayerKilledUnit(plr, 0);
return true;
}
bool ChatHandler::HandleAddHonorCommand(const char* args, WorldSession* m_session)
{
uint32 HonorAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u honor to player %s.", HonorAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor points added to your character.", HonorAmount);
HonorHandler::AddHonorPointsToPlayer(plr, HonorAmount);
return true;
}
bool ChatHandler::HandlePVPCreditCommand(const char* args, WorldSession* m_session)
{
uint32 Rank, Points;
if(sscanf(args, "%u %u", (unsigned int*)&Rank, (unsigned int*)&Points) != 2)
{
RedSystemMessage(m_session, "Command must be in format <rank> <points>.");
return true;
}
Points *= 10;
uint64 Guid = m_session->GetPlayer()->GetSelection();
if(Guid == 0)
{
RedSystemMessage(m_session, "A selection of a unit or player is required.");
return true;
}
BlueSystemMessage(m_session, "Building packet with Rank %u, Points %u, GUID "I64FMT".",
Rank, Points, Guid);
WorldPacket data(SMSG_PVP_CREDIT, 12);
data << Points << Guid << Rank;
m_session->SendPacket(&data);
return true;
}
bool ChatHandler::HandleGlobalHonorDailyMaintenanceCommand(const char* args, WorldSession* m_session)
{
return false;
}
bool ChatHandler::HandleNextDayCommand(const char* args, WorldSession* m_session)
{
return false;
}
<commit_msg>* compile fix and temp disabled the GetWorldState as theres no hellfire pvp script been created yet so would make this impossible to get the tokens <commit_after>/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program 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, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleSetVisibleRankOpcode( WorldPacket& recv_data )
{
CHECK_PACKET_SIZE( recv_data, 4 );
uint32 ChosenRank;
recv_data >> ChosenRank;
if( ChosenRank == 0xFFFFFFFF )
_player->SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
else if( _player->HasKnownTitle( static_cast< RankTitles >( ChosenRank ) ) )
_player->SetUInt32Value( PLAYER_CHOSEN_TITLE, ChosenRank );
}
void HonorHandler::AddHonorPointsToPlayer(Player *pPlayer, uint32 uAmount)
{
pPlayer->HandleProc(PROC_ON_GAIN_EXPIERIENCE, pPlayer, NULL);
pPlayer->m_procCounter = 0;
if( pPlayer->GetMapId() == 559 || pPlayer->GetMapId() == 562 || pPlayer->GetMapId() == 572)
return;
pPlayer->m_honorPoints += uAmount;
pPlayer->m_honorToday += uAmount;
if (pPlayer->m_honorPoints > 75000) pPlayer->m_honorPoints = 75000;
RecalculateHonorFields(pPlayer);
}
int32 HonorHandler::CalculateHonorPointsForKill( Player *pPlayer, Unit* pVictim )
{
// this sucks.. ;p
if( pVictim == NULL )
{
int32 pts = rand() % 100 + 100;
return pts;
}
// Suicide lol
if( pVictim == pPlayer )
return 0;
if( pVictim->GetTypeId() != TYPEID_PLAYER )
return 0;
//use Player::m_honorless, applied with Aura::SpellAuraNoPVPCredit
// How dishonorable, you fiend!
//if( pVictim->HasActiveAura( PLAYER_HONORLESS_TARGET_SPELL ) )
// return 0;
if ( pVictim->GetTypeId() == TYPEID_PLAYER && (static_cast< Player* >(pVictim)->m_honorless || static_cast< Player* >(pVictim)->HasAura(15007)) )
return 0;
uint32 k_level = pPlayer->GetUInt32Value( UNIT_FIELD_LEVEL );
uint32 v_level = pVictim->GetUInt32Value( UNIT_FIELD_LEVEL );
int k_honor = pPlayer->m_honorPoints;
int v_honor = static_cast< Player* >( pVictim )->m_honorPoints;
uint32 k_grey = 0;
if( k_level > 5 && k_level < 40 )
{
k_grey = k_level - 5 - float2int32( floor( ((float)k_level) / 10.0f ) );
}
else
{
k_grey = k_level - 1 - float2int32( floor( ((float)k_level) / 5.0f ) );
}
if( k_honor == 0 )
k_honor = 1;
float diff_level = ((float)v_level - k_grey) / ((float)k_level - k_grey);
if( diff_level > 2 ) diff_level = 2.0f;
if( diff_level < 0 ) diff_level = 0.0f;
float diff_honor = ((float)v_honor) / ((float)k_honor);
if( diff_honor > 3 ) diff_honor = 3.0f;
if( diff_honor < 0 ) diff_honor = 0.0f;
float honor_points = diff_level * ( 150.0f + diff_honor * 60 );
honor_points *= ((float)k_level) / PLAYER_LEVEL_CAP;
honor_points *= World::getSingleton().getRate( RATE_HONOR );
return float2int32( honor_points );
}
void HonorHandler::OnPlayerKilledUnit( Player *pPlayer, Unit* pVictim )
{
if( pVictim == NULL || pPlayer == NULL )
return;
if( pPlayer->GetTypeId() != TYPEID_PLAYER || !pVictim->IsUnit() )
return;
if( !pVictim->IsPlayer() || static_cast< Player* >( pVictim )->m_honorless )
return;
if( pVictim->IsPlayer() )
{
if( pPlayer->m_bg )
{
if( static_cast< Player* >( pVictim )->m_bgTeam == pPlayer->m_bgTeam )
return;
// patch 2.4, players killed >50 times in battlegrounds won't be worth honor for the rest of that bg
if( static_cast<Player*>(pVictim)->m_bgScore.Deaths >= 50 )
return;
}
else
{
if( pPlayer->GetTeam() == static_cast< Player* >( pVictim )->GetTeam() )
return;
}
}
// Calculate points
int32 Points = CalculateHonorPointsForKill(pPlayer, pVictim);
if( Points > 0 )
{
if( pPlayer->m_bg )
{
// hackfix for battlegrounds (since the gorups there are disabled, we need to do this manually)
vector<Player*> toadd;
uint32 t = pPlayer->m_bgTeam;
toadd.reserve(15); // shouldnt have more than this
pPlayer->m_bg->Lock();
set<Player*> * s = &pPlayer->m_bg->m_players[t];
for(set<Player*>::iterator itr = s->begin(); itr != s->end(); ++itr)
{
if((*itr) == pPlayer || (*itr)->isInRange(pPlayer,100.0f))
toadd.push_back(*itr);
}
if( toadd.size() > 0 )
{
uint32 pts = Points / (uint32)toadd.size();
for(vector<Player*>::iterator vtr = toadd.begin(); vtr != toadd.end(); ++vtr)
{
AddHonorPointsToPlayer(*vtr, pts);
(*vtr)->m_killsToday++;
(*vtr)->m_killsLifetime++;
pPlayer->m_bg->HookOnHK(*vtr);
if(pVictim)
{
// Send PVP credit
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = pts * 10;
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
(*vtr)->GetSession()->SendPacket(&data);
}
}
}
pPlayer->m_bg->Unlock();
}
else
{
set<Player*> contributors;
// First loop: Get all the people in the attackermap.
pVictim->UpdateOppFactionSet();
for(std::set<Object*>::iterator itr = pVictim->GetInRangeOppFactsSetBegin(); itr != pVictim->GetInRangeOppFactsSetEnd(); itr++)
{
if(!(*itr)->IsPlayer())
continue;
bool added = false;
Player * plr = (Player*)(*itr);
if(pVictim->CombatStatus.m_attackers.find(plr->GetGUID()) != pVictim->CombatStatus.m_attackers.end())
{
added = true;
contributors.insert(plr);
}
if(added && plr->GetGroup())
{
Group * pGroup = plr->GetGroup();
uint32 groups = pGroup->GetSubGroupCount();
for(uint32 i = 0; i < groups; i++)
{
SubGroup * sg = pGroup->GetSubGroup(i);
if(!sg) continue;
for(GroupMembersSet::iterator itr2 = sg->GetGroupMembersBegin(); itr2 != sg->GetGroupMembersEnd(); itr2++)
{
PlayerInfo * pi = (*itr2);
Player * gm = objmgr.GetPlayer(pi->guid);
if(!gm) continue;
if(gm->isInRange(pVictim, 100.0f))
contributors.insert(gm);
}
}
}
}
for(set<Player*>::iterator itr = contributors.begin(); itr != contributors.end(); itr++)
{
Player * pAffectedPlayer = (*itr);
if(!pAffectedPlayer) continue;
pAffectedPlayer->m_killsToday++;
pAffectedPlayer->m_killsLifetime++;
if(pAffectedPlayer->m_bg)
pAffectedPlayer->m_bg->HookOnHK(pAffectedPlayer);
int32 contributorpts = Points / (int32)contributors.size();
AddHonorPointsToPlayer(pAffectedPlayer, contributorpts);
if(pVictim->IsPlayer())
{
sHookInterface.OnHonorableKill(pAffectedPlayer, (Player*)pVictim);
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = contributorpts * 10; // Why *10?
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
pAffectedPlayer->GetSession()->SendPacket(&data);
}
if(pAffectedPlayer->GetZoneId() == 3518)
{
// Add Halaa Battle Token
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 33004 : 33005);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
// If we are in Hellfire Peninsula <http://www.wowwiki.com/Hellfire_Peninsula#World_PvP_-_Hellfire_Fortifications>
if(pAffectedPlayer->GetZoneId() == 3483)
{
// Hellfire Horde Controlled Towers
// Commented out until someone works on the hellfire world pvp :)
/*if(pAffectedPlayer->GetMapMgr()->GetWorldState(2478) != 3 && pAffectedPlayer->GetTeam() == 1)
return;
// Hellfire Alliance Controlled Towers
if(pAffectedPlayer->GetMapMgr()->GetWorldState(2476) != 3 && pAffectedPlayer->GetTeam() == 0)
return;*/
// Add Mark of Thrallmar/Honor Hold
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 32158 : 32155);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
}
}
}
}
void HonorHandler::RecalculateHonorFields(Player *pPlayer)
{
pPlayer->SetUInt32Value(PLAYER_FIELD_KILLS, uint16(pPlayer->m_killsToday) | ( pPlayer->m_killsYesterday << 16 ) );
pPlayer->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, pPlayer->m_honorToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, pPlayer->m_honorYesterday);
pPlayer->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, pPlayer->m_killsLifetime);
pPlayer->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, pPlayer->m_honorPoints);
pPlayer->SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, pPlayer->m_arenaPoints);
}
bool ChatHandler::HandleAddKillCommand(const char* args, WorldSession* m_session)
{
uint32 KillAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u kills to player %s.", KillAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor kills added to your character.", KillAmount);
for(uint32 i = 0; i < KillAmount; ++i)
HonorHandler::OnPlayerKilledUnit(plr, 0);
return true;
}
bool ChatHandler::HandleAddHonorCommand(const char* args, WorldSession* m_session)
{
uint32 HonorAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u honor to player %s.", HonorAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor points added to your character.", HonorAmount);
HonorHandler::AddHonorPointsToPlayer(plr, HonorAmount);
return true;
}
bool ChatHandler::HandlePVPCreditCommand(const char* args, WorldSession* m_session)
{
uint32 Rank, Points;
if(sscanf(args, "%u %u", (unsigned int*)&Rank, (unsigned int*)&Points) != 2)
{
RedSystemMessage(m_session, "Command must be in format <rank> <points>.");
return true;
}
Points *= 10;
uint64 Guid = m_session->GetPlayer()->GetSelection();
if(Guid == 0)
{
RedSystemMessage(m_session, "A selection of a unit or player is required.");
return true;
}
BlueSystemMessage(m_session, "Building packet with Rank %u, Points %u, GUID "I64FMT".",
Rank, Points, Guid);
WorldPacket data(SMSG_PVP_CREDIT, 12);
data << Points << Guid << Rank;
m_session->SendPacket(&data);
return true;
}
bool ChatHandler::HandleGlobalHonorDailyMaintenanceCommand(const char* args, WorldSession* m_session)
{
return false;
}
bool ChatHandler::HandleNextDayCommand(const char* args, WorldSession* m_session)
{
return false;
}
<|endoftext|> |
<commit_before>#include "texture_loader.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <stdint.h> // uint32_t etc.
#include <stdlib.h> // free, malloc
namespace texture
{
GLuint load_BMP_texture(const char* imagepath)
{
std::printf("Reading image %s\n", imagepath);
// Data read from the header of the BMP file
unsigned char header[54];
uint32_t dataPos;
uint32_t imageSize;
uint32_t width, height;
// Actual RGB data
unsigned char* data;
// Open the file
std::FILE* file = std::fopen(imagepath,"rb");
if (!file)
{
std::printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath);
std::getchar();
return 0;
}
// Read the header, i.e. the 54 first bytes
// If less than 54 bytes are read, problem
if (std::fread(header, 1, 54, file) != 54)
{
std::printf("Not a correct BMP file\n");
return 0;
}
// A BMP files always begins with "BM"
if ((header[0] != 'B') || (header[1] != 'M'))
{
std::printf("Not a correct BMP file\n");
return 0;
}
// Make sure this is a 24bpp file
if (*(int*) &header[0x1E] != 0)
{
std::printf("Not a correct BMP file\n");
return 0;
}
if (*(int*) &header[0x1C] != 24)
{
std::printf("Not a correct BMP file\n");
return 0;
}
// Read the information about the image
dataPos = *(int*) &header[0x0A];
imageSize = *(int*) &header[0x22];
width = *(int*) &header[0x12];
height = *(int*) &header[0x16];
// Some BMP files are misformatted, guess missing information
if (imageSize == 0)
{
imageSize = width * height * 3; // 3 : one byte for each Red, Green and Blue component
}
if (dataPos == 0)
{
dataPos = 54; // The BMP header is done that way
}
// Create a buffer
data = new unsigned char [imageSize];
// Read the actual data from the file into the buffer
std::fread(data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
// OpenGL has now copied the data. Free our own version
delete [] data;
// Poor filtering, or ...
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#define CLAMP_TEXTURES
// #define REPEAT_TEXTURES
#ifdef CLAMP_TEXTURES
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#endif
#ifdef REPEAT_TEXTURES
// ... nice trilinear filtering.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
// Return the ID of the texture we just created
return textureID;
}
// Since GLFW 3, glfwLoadTexture2D() has been removed. You have to use another texture loading library,
// or do it yourself (just like load_BMP_texture and load_DDS_texture)
//GLuint loadTGA_glfw(const char* imagepath){
//
// // Create one OpenGL texture
// GLuint textureID;
// glGenTextures(1, &textureID);
//
// // "Bind" the newly created texture : all future texture functions will modify this texture
// glBindTexture(GL_TEXTURE_2D, textureID);
//
// // Read the file, call glTexImage2D with the right parameters
// glfwLoadTexture2D(imagepath, 0);
//
// // Nice trilinear filtering.
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// glGenerateMipmap(GL_TEXTURE_2D);
//
// // Return the ID of the texture we just created
// return textureID;
//}
#define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII
#define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII
#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII
GLuint load_DDS_texture(const char* imagepath)
{
unsigned char header[124];
std::FILE* fp;
/* try to open the file */
fp = std::fopen(imagepath, "rb");
if (fp == nullptr)
{
std::printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath);
std::getchar();
return 0;
}
/* verify the type of file */
char filecode[4];
std::fread(filecode, 1, 4, fp);
if (std::strncmp(filecode, "DDS ", 4) != 0)
{
std::fclose(fp);
return 0;
}
/* get the surface desc */
std::fread(&header, 124, 1, fp);
uint32_t height = *(uint32_t*) &header[8];
uint32_t width = *(uint32_t*) &header[12];
uint32_t linearSize = *(uint32_t*) &header[16];
uint32_t mipMapCount = *(uint32_t*) &header[24];
uint32_t fourCC = *(uint32_t*) &header[80];
unsigned char* buffer;
uint32_t bufsize;
/* how big is it going to be including all mipmaps? */
bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
buffer = (unsigned char*) malloc(bufsize * sizeof(unsigned char));
std::fread(buffer, 1, bufsize, fp);
/* close the file pointer */
std::fclose(fp);
uint32_t components = (fourCC == FOURCC_DXT1) ? 3 : 4;
uint32_t format;
switch(fourCC)
{
case FOURCC_DXT1:
format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case FOURCC_DXT3:
format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case FOURCC_DXT5:
format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
default:
free(buffer);
return 0;
}
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
uint32_t blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
uint32_t offset = 0;
/* load the mipmaps */
for (uint32_t level = 0; level < mipMapCount && (width || height); ++level)
{
uint32_t size = ((width + 3) / 4) * ((height + 3) / 4) * blockSize;
glCompressedTexImage2D(
GL_TEXTURE_2D,
level,
format,
width,
height,
0,
size,
buffer + offset);
offset += size;
width /= 2;
height /= 2;
// Deal with Non-Power-Of-Two textures. This code is not included in the webpage to reduce clutter.
if (width < 1)
{
width = 1;
}
if (height < 1)
{
height = 1;
}
}
free(buffer);
return textureID;
}
}
<commit_msg>Removed `std::getchar()` in case of failing to open file.<commit_after>#include "texture_loader.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <stdint.h> // uint32_t etc.
#include <stdlib.h> // free, malloc
namespace texture
{
GLuint load_BMP_texture(const char* imagepath)
{
std::printf("Reading image %s\n", imagepath);
// Data read from the header of the BMP file
unsigned char header[54];
uint32_t dataPos;
uint32_t imageSize;
uint32_t width, height;
// Actual RGB data
unsigned char* data;
// Open the file
std::FILE* file = std::fopen(imagepath,"rb");
if (!file)
{
std::printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath);
std::getchar();
return 0;
}
// Read the header, i.e. the 54 first bytes
// If less than 54 bytes are read, problem
if (std::fread(header, 1, 54, file) != 54)
{
std::printf("Not a correct BMP file\n");
return 0;
}
// A BMP files always begins with "BM"
if ((header[0] != 'B') || (header[1] != 'M'))
{
std::printf("Not a correct BMP file\n");
return 0;
}
// Make sure this is a 24bpp file
if (*(int*) &header[0x1E] != 0)
{
std::printf("Not a correct BMP file\n");
return 0;
}
if (*(int*) &header[0x1C] != 24)
{
std::printf("Not a correct BMP file\n");
return 0;
}
// Read the information about the image
dataPos = *(int*) &header[0x0A];
imageSize = *(int*) &header[0x22];
width = *(int*) &header[0x12];
height = *(int*) &header[0x16];
// Some BMP files are misformatted, guess missing information
if (imageSize == 0)
{
imageSize = width * height * 3; // 3 : one byte for each Red, Green and Blue component
}
if (dataPos == 0)
{
dataPos = 54; // The BMP header is done that way
}
// Create a buffer
data = new unsigned char [imageSize];
// Read the actual data from the file into the buffer
std::fread(data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
// OpenGL has now copied the data. Free our own version
delete [] data;
// Poor filtering, or ...
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#define CLAMP_TEXTURES
// #define REPEAT_TEXTURES
#ifdef CLAMP_TEXTURES
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#endif
#ifdef REPEAT_TEXTURES
// ... nice trilinear filtering.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
// Return the ID of the texture we just created
return textureID;
}
// Since GLFW 3, glfwLoadTexture2D() has been removed. You have to use another texture loading library,
// or do it yourself (just like load_BMP_texture and load_DDS_texture)
//GLuint loadTGA_glfw(const char* imagepath){
//
// // Create one OpenGL texture
// GLuint textureID;
// glGenTextures(1, &textureID);
//
// // "Bind" the newly created texture : all future texture functions will modify this texture
// glBindTexture(GL_TEXTURE_2D, textureID);
//
// // Read the file, call glTexImage2D with the right parameters
// glfwLoadTexture2D(imagepath, 0);
//
// // Nice trilinear filtering.
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// glGenerateMipmap(GL_TEXTURE_2D);
//
// // Return the ID of the texture we just created
// return textureID;
//}
#define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII
#define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII
#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII
GLuint load_DDS_texture(const char* imagepath)
{
unsigned char header[124];
std::FILE* fp;
/* try to open the file */
fp = std::fopen(imagepath, "rb");
if (fp == nullptr)
{
std::printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath);
return 0;
}
/* verify the type of file */
char filecode[4];
std::fread(filecode, 1, 4, fp);
if (std::strncmp(filecode, "DDS ", 4) != 0)
{
std::fclose(fp);
return 0;
}
/* get the surface desc */
std::fread(&header, 124, 1, fp);
uint32_t height = *(uint32_t*) &header[8];
uint32_t width = *(uint32_t*) &header[12];
uint32_t linearSize = *(uint32_t*) &header[16];
uint32_t mipMapCount = *(uint32_t*) &header[24];
uint32_t fourCC = *(uint32_t*) &header[80];
unsigned char* buffer;
uint32_t bufsize;
/* how big is it going to be including all mipmaps? */
bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
buffer = (unsigned char*) malloc(bufsize * sizeof(unsigned char));
std::fread(buffer, 1, bufsize, fp);
/* close the file pointer */
std::fclose(fp);
uint32_t components = (fourCC == FOURCC_DXT1) ? 3 : 4;
uint32_t format;
switch(fourCC)
{
case FOURCC_DXT1:
format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case FOURCC_DXT3:
format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case FOURCC_DXT5:
format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
default:
free(buffer);
return 0;
}
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
uint32_t blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
uint32_t offset = 0;
/* load the mipmaps */
for (uint32_t level = 0; level < mipMapCount && (width || height); ++level)
{
uint32_t size = ((width + 3) / 4) * ((height + 3) / 4) * blockSize;
glCompressedTexImage2D(
GL_TEXTURE_2D,
level,
format,
width,
height,
0,
size,
buffer + offset);
offset += size;
width /= 2;
height /= 2;
// Deal with Non-Power-Of-Two textures. This code is not included in the webpage to reduce clutter.
if (width < 1)
{
width = 1;
}
if (height < 1)
{
height = 1;
}
}
free(buffer);
return textureID;
}
}
<|endoftext|> |
<commit_before>//===-- ELFDump.cpp - ELF-specific dumper -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the ELF-specific dumper for llvm-objdump.
///
//===----------------------------------------------------------------------===//
#include "llvm-objdump.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
template <class ELFT>
Expected<StringRef> getDynamicStrTab(const ELFFile<ELFT> *Elf) {
typedef ELFFile<ELFT> ELFO;
auto DynamicEntriesOrError = Elf->dynamicEntries();
if (!DynamicEntriesOrError)
return DynamicEntriesOrError.takeError();
for (const typename ELFO::Elf_Dyn &Dyn : *DynamicEntriesOrError) {
if (Dyn.d_tag == ELF::DT_STRTAB) {
auto MappedAddrOrError = Elf->toMappedAddr(Dyn.getPtr());
if (!MappedAddrOrError)
consumeError(MappedAddrOrError.takeError());
return StringRef(reinterpret_cast<const char *>(*MappedAddrOrError));
}
}
// If the dynamic segment is not present, we fall back on the sections.
auto SectionsOrError = Elf->sections();
if (!SectionsOrError)
return SectionsOrError.takeError();
for (const typename ELFO::Elf_Shdr &Sec : *SectionsOrError) {
if (Sec.sh_type == ELF::SHT_DYNSYM)
return Elf->getStringTableForSymtab(Sec);
}
return createError("dynamic string table not found");
}
template <class ELFT>
void printDynamicSection(const ELFFile<ELFT> *Elf, StringRef Filename) {
auto ProgramHeaderOrError = Elf->program_headers();
if (!ProgramHeaderOrError)
report_error(Filename, ProgramHeaderOrError.takeError());
auto DynamicEntriesOrError = Elf->dynamicEntries();
if (!DynamicEntriesOrError)
report_error(Filename, DynamicEntriesOrError.takeError());
outs() << "Dynamic Section:\n";
for (const auto &Dyn : *DynamicEntriesOrError) {
if (Dyn.d_tag == ELF::DT_NULL)
continue;
StringRef Str = StringRef(Elf->getDynamicTagAsString(Dyn.d_tag));
if (Str.empty()) {
std::string HexStr = utohexstr(static_cast<uint64_t>(Dyn.d_tag), true);
outs() << format(" 0x%-19s", HexStr.c_str());
} else {
// We use "-21" in order to match GNU objdump's output.
outs() << format(" %-21s", Str.data());
}
const char *Fmt =
ELFT::Is64Bits ? "0x%016" PRIx64 "\n" : "0x%08" PRIx64 "\n";
if (Dyn.d_tag == ELF::DT_NEEDED) {
Expected<StringRef> StrTabOrErr = getDynamicStrTab(Elf);
if (StrTabOrErr) {
const char *Data = StrTabOrErr.get().data();
outs() << (Data + Dyn.d_un.d_val) << "\n";
continue;
}
warn(errorToErrorCode(StrTabOrErr.takeError()).message());
consumeError(StrTabOrErr.takeError());
}
outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val);
}
}
template <class ELFT> void printProgramHeaders(const ELFFile<ELFT> *o) {
typedef ELFFile<ELFT> ELFO;
outs() << "Program Header:\n";
auto ProgramHeaderOrError = o->program_headers();
if (!ProgramHeaderOrError)
report_fatal_error(
errorToErrorCode(ProgramHeaderOrError.takeError()).message());
for (const typename ELFO::Elf_Phdr &Phdr : *ProgramHeaderOrError) {
switch (Phdr.p_type) {
case ELF::PT_DYNAMIC:
outs() << " DYNAMIC ";
break;
case ELF::PT_GNU_EH_FRAME:
outs() << "EH_FRAME ";
break;
case ELF::PT_GNU_RELRO:
outs() << " RELRO ";
break;
case ELF::PT_GNU_STACK:
outs() << " STACK ";
break;
case ELF::PT_INTERP:
outs() << " INTERP ";
break;
case ELF::PT_LOAD:
outs() << " LOAD ";
break;
case ELF::PT_NOTE:
outs() << " NOTE ";
break;
case ELF::PT_OPENBSD_BOOTDATA:
outs() << " OPENBSD_BOOTDATA ";
break;
case ELF::PT_OPENBSD_RANDOMIZE:
outs() << " OPENBSD_RANDOMIZE ";
break;
case ELF::PT_OPENBSD_WXNEEDED:
outs() << " OPENBSD_WXNEEDED ";
break;
case ELF::PT_PHDR:
outs() << " PHDR ";
break;
case ELF::PT_TLS:
outs() << " TLS ";
break;
default:
outs() << " UNKNOWN ";
}
const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
outs() << "off " << format(Fmt, (uint64_t)Phdr.p_offset) << "vaddr "
<< format(Fmt, (uint64_t)Phdr.p_vaddr) << "paddr "
<< format(Fmt, (uint64_t)Phdr.p_paddr)
<< format("align 2**%u\n",
countTrailingZeros<uint64_t>(Phdr.p_align))
<< " filesz " << format(Fmt, (uint64_t)Phdr.p_filesz)
<< "memsz " << format(Fmt, (uint64_t)Phdr.p_memsz) << "flags "
<< ((Phdr.p_flags & ELF::PF_R) ? "r" : "-")
<< ((Phdr.p_flags & ELF::PF_W) ? "w" : "-")
<< ((Phdr.p_flags & ELF::PF_X) ? "x" : "-") << "\n";
}
outs() << "\n";
}
void llvm::printELFFileHeader(const object::ObjectFile *Obj) {
// Little-endian 32-bit
if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
// Big-endian 32-bit
else if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
// Little-endian 64-bit
else if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
// Big-endian 64-bit
else if (const ELF64BEObjectFile *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
}
void llvm::printELFDynamicSection(const object::ObjectFile *Obj) {
// Little-endian 32-bit
if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
// Big-endian 32-bit
else if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
// Little-endian 64-bit
else if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
// Big-endian 64-bit
else if (const ELF64BEObjectFile *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
}
<commit_msg>[llvm-objdump] Use `auto` declaration in typecasting<commit_after>//===-- ELFDump.cpp - ELF-specific dumper -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the ELF-specific dumper for llvm-objdump.
///
//===----------------------------------------------------------------------===//
#include "llvm-objdump.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
template <class ELFT>
Expected<StringRef> getDynamicStrTab(const ELFFile<ELFT> *Elf) {
typedef ELFFile<ELFT> ELFO;
auto DynamicEntriesOrError = Elf->dynamicEntries();
if (!DynamicEntriesOrError)
return DynamicEntriesOrError.takeError();
for (const typename ELFO::Elf_Dyn &Dyn : *DynamicEntriesOrError) {
if (Dyn.d_tag == ELF::DT_STRTAB) {
auto MappedAddrOrError = Elf->toMappedAddr(Dyn.getPtr());
if (!MappedAddrOrError)
consumeError(MappedAddrOrError.takeError());
return StringRef(reinterpret_cast<const char *>(*MappedAddrOrError));
}
}
// If the dynamic segment is not present, we fall back on the sections.
auto SectionsOrError = Elf->sections();
if (!SectionsOrError)
return SectionsOrError.takeError();
for (const typename ELFO::Elf_Shdr &Sec : *SectionsOrError) {
if (Sec.sh_type == ELF::SHT_DYNSYM)
return Elf->getStringTableForSymtab(Sec);
}
return createError("dynamic string table not found");
}
template <class ELFT>
void printDynamicSection(const ELFFile<ELFT> *Elf, StringRef Filename) {
auto ProgramHeaderOrError = Elf->program_headers();
if (!ProgramHeaderOrError)
report_error(Filename, ProgramHeaderOrError.takeError());
auto DynamicEntriesOrError = Elf->dynamicEntries();
if (!DynamicEntriesOrError)
report_error(Filename, DynamicEntriesOrError.takeError());
outs() << "Dynamic Section:\n";
for (const auto &Dyn : *DynamicEntriesOrError) {
if (Dyn.d_tag == ELF::DT_NULL)
continue;
StringRef Str = StringRef(Elf->getDynamicTagAsString(Dyn.d_tag));
if (Str.empty()) {
std::string HexStr = utohexstr(static_cast<uint64_t>(Dyn.d_tag), true);
outs() << format(" 0x%-19s", HexStr.c_str());
} else {
// We use "-21" in order to match GNU objdump's output.
outs() << format(" %-21s", Str.data());
}
const char *Fmt =
ELFT::Is64Bits ? "0x%016" PRIx64 "\n" : "0x%08" PRIx64 "\n";
if (Dyn.d_tag == ELF::DT_NEEDED) {
Expected<StringRef> StrTabOrErr = getDynamicStrTab(Elf);
if (StrTabOrErr) {
const char *Data = StrTabOrErr.get().data();
outs() << (Data + Dyn.d_un.d_val) << "\n";
continue;
}
warn(errorToErrorCode(StrTabOrErr.takeError()).message());
consumeError(StrTabOrErr.takeError());
}
outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val);
}
}
template <class ELFT> void printProgramHeaders(const ELFFile<ELFT> *o) {
typedef ELFFile<ELFT> ELFO;
outs() << "Program Header:\n";
auto ProgramHeaderOrError = o->program_headers();
if (!ProgramHeaderOrError)
report_fatal_error(
errorToErrorCode(ProgramHeaderOrError.takeError()).message());
for (const typename ELFO::Elf_Phdr &Phdr : *ProgramHeaderOrError) {
switch (Phdr.p_type) {
case ELF::PT_DYNAMIC:
outs() << " DYNAMIC ";
break;
case ELF::PT_GNU_EH_FRAME:
outs() << "EH_FRAME ";
break;
case ELF::PT_GNU_RELRO:
outs() << " RELRO ";
break;
case ELF::PT_GNU_STACK:
outs() << " STACK ";
break;
case ELF::PT_INTERP:
outs() << " INTERP ";
break;
case ELF::PT_LOAD:
outs() << " LOAD ";
break;
case ELF::PT_NOTE:
outs() << " NOTE ";
break;
case ELF::PT_OPENBSD_BOOTDATA:
outs() << " OPENBSD_BOOTDATA ";
break;
case ELF::PT_OPENBSD_RANDOMIZE:
outs() << " OPENBSD_RANDOMIZE ";
break;
case ELF::PT_OPENBSD_WXNEEDED:
outs() << " OPENBSD_WXNEEDED ";
break;
case ELF::PT_PHDR:
outs() << " PHDR ";
break;
case ELF::PT_TLS:
outs() << " TLS ";
break;
default:
outs() << " UNKNOWN ";
}
const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
outs() << "off " << format(Fmt, (uint64_t)Phdr.p_offset) << "vaddr "
<< format(Fmt, (uint64_t)Phdr.p_vaddr) << "paddr "
<< format(Fmt, (uint64_t)Phdr.p_paddr)
<< format("align 2**%u\n",
countTrailingZeros<uint64_t>(Phdr.p_align))
<< " filesz " << format(Fmt, (uint64_t)Phdr.p_filesz)
<< "memsz " << format(Fmt, (uint64_t)Phdr.p_memsz) << "flags "
<< ((Phdr.p_flags & ELF::PF_R) ? "r" : "-")
<< ((Phdr.p_flags & ELF::PF_W) ? "w" : "-")
<< ((Phdr.p_flags & ELF::PF_X) ? "x" : "-") << "\n";
}
outs() << "\n";
}
void llvm::printELFFileHeader(const object::ObjectFile *Obj) {
if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
printProgramHeaders(ELFObj->getELFFile());
}
void llvm::printELFDynamicSection(const object::ObjectFile *Obj) {
if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* 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 "modules/map/relative_map/navigation_lane.h"
#include <algorithm>
#include <limits>
#include "modules/map/proto/map_lane.pb.h"
#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/util.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/relative_map/common/relative_map_gflags.h"
namespace apollo {
namespace relative_map {
using apollo::common::VehicleStateProvider;
using apollo::common::math::Vec2d;
using apollo::common::util::DistanceXY;
using apollo::hdmap::Lane;
using apollo::common::util::operator+;
using apollo::perception::PerceptionObstacles;
NavigationLane::NavigationLane(const NavigationLaneConfig &config)
: config_(config) {}
void NavigationLane::SetConfig(const NavigationLaneConfig &config) {
config_ = config;
}
bool NavigationLane::GeneratePath() {
// original_pose is in world coordination: ENU
original_pose_ = VehicleStateProvider::instance()->original_pose();
navigation_path_.Clear();
auto *path = navigation_path_.mutable_path();
const auto &lane_marker = perception_obstacles_.lane_marker();
// priority: merge > navigation line > perception lane marker
if (FLAGS_enable_navigation_line &&
navigation_info_.navigation_path_size() > 0) {
ConvertNavigationLineToPath(path);
if (path->path_point().size() <= 0) {
ConvertLaneMarkerToPath(lane_marker, path);
}
} else {
ConvertLaneMarkerToPath(lane_marker, path);
}
return true;
}
double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,
const double c2, const double c3,
const double z) const {
return ((c3 * z + c2) * z + c1) * z + c0;
}
void NavigationLane::MergeNavigationLineAndLaneMarker(
const perception::LaneMarkers &lane_marker, common::Path *path) {
CHECK_NOTNULL(path);
common::Path navigation_path;
ConvertNavigationLineToPath(&navigation_path);
common::Path lane_marker_path;
ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(),
&lane_marker_path);
const double len = std::fmin(
navigation_path.path_point(navigation_path.path_point_size() - 1).s(),
lane_marker_path.path_point(lane_marker_path.path_point_size() - 1).s());
const double ds = 1.0;
int navigation_index = 0;
int lane_marker_index = 0;
for (double s = 0.0; s < len; s += ds) {
auto p1 = GetPathPointByS(navigation_path, navigation_index, s,
&navigation_index);
auto p2 = GetPathPointByS(lane_marker_path, lane_marker_index, s,
&lane_marker_index);
auto *p = path->add_path_point();
const double kWeight = 0.9;
*p = common::util::GetWeightedAverageOfTwoPathPoints(p1, p2, kWeight,
1 - kWeight);
}
}
common::PathPoint NavigationLane::GetPathPointByS(const common::Path &path,
const int start_index,
const double s,
int *matched_index) {
CHECK_NOTNULL(matched_index);
constexpr double kEpsilon = 1e-9;
if (std::fabs(path.path_point(start_index).s() - s) < kEpsilon) {
*matched_index = start_index;
return path.path_point(start_index);
}
int i = start_index;
while (i + 1 < path.path_point_size() && path.path_point(i + 1).s() < s) {
++i;
}
*matched_index = i;
// x, y, z, theta, kappa, s, dkappa, ddkappa
const double r = (s - path.path_point(i).s()) /
(path.path_point(i + 1).s() - path.path_point(i).s());
auto p = common::util::GetWeightedAverageOfTwoPathPoints(
path.path_point(i), path.path_point(i + 1), 1 - r, r);
return p;
}
void NavigationLane::ConvertNavigationLineToPath(common::Path *path) {
CHECK_NOTNULL(path);
if (navigation_info_.navigation_path_size() == 0 ||
!navigation_info_.navigation_path(0).has_path() ||
navigation_info_.navigation_path(0).path().path_point_size() == 0) {
// path is empty
return;
}
path->set_name("Path from navigation.");
UpdateProjectionIndex();
// TODO(All): support multiple navigation path
// currently, only 1 navigation path is supported
const auto &navigation_path = navigation_info_.navigation_path(0).path();
int curr_project_index = last_project_index_;
double dist =
navigation_path.path_point(navigation_path.path_point_size() - 1).s() -
navigation_path.path_point(curr_project_index).s();
if (dist < 20) {
return;
}
// offset between the current vehicle state and navigation line
const double dx = -original_pose_.position().x();
const double dy = -original_pose_.position().y();
const double ref_s = navigation_path.path_point(curr_project_index).s();
for (int i = std::max(0, curr_project_index - 3);
i < navigation_path.path_point_size(); ++i) {
auto *point = path->add_path_point();
point->CopyFrom(navigation_path.path_point(i));
// shift to (0, 0)
double enu_x = point->x() + dx;
double enu_y = point->y() + dy;
double flu_x = 0.0;
double flu_y = 0.0;
common::math::RotateAxis(original_pose_.heading(), enu_x, enu_y, &flu_x,
&flu_y);
point->set_x(flu_x);
point->set_y(flu_y);
point->set_theta(point->theta() - original_pose_.heading());
const double accumulated_s = navigation_path.path_point(i).s() - ref_s;
point->set_s(accumulated_s);
if (accumulated_s > FLAGS_max_len_from_navigation_line) {
break;
}
}
const perception::LaneMarkers &lane_marker =
perception_obstacles_.lane_marker();
const auto &left_lane = lane_marker.left_lane_marker();
const auto &right_lane = lane_marker.right_lane_marker();
left_width_ = (std::fabs(left_lane.c0_position()) +
std::fabs(right_lane.c0_position())) /
2.0;
right_width_ = left_width_;
}
// project adc_state_ onto path
void NavigationLane::UpdateProjectionIndex() {
// TODO(All): support multiple navigation path
// currently, only 1 navigation path is supported
const auto &path = navigation_info_.navigation_path(0).path();
int index = 0;
double min_d = std::numeric_limits<double>::max();
for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {
const double d = DistanceXY(original_pose_.position(), path.path_point(i));
if (d < min_d) {
min_d = d;
index = i;
}
const double kMaxDistance = 50.0;
if (last_project_index_ != 0 && d > kMaxDistance) {
break;
}
}
last_project_index_ = index;
}
void NavigationLane::ConvertLaneMarkerToPath(
const perception::LaneMarkers &lane_marker, common::Path *path) {
CHECK_NOTNULL(path);
path->set_name("Path from lane markers.");
const auto &left_lane = lane_marker.left_lane_marker();
const auto &right_lane = lane_marker.right_lane_marker();
double path_c0 = (left_lane.c0_position() + right_lane.c0_position()) / 2.0;
double left_quality = left_lane.quality() + 0.001;
double right_quality = right_lane.quality() + 0.001;
double quality_divider = left_quality + right_quality;
double path_c1 = (left_lane.c1_heading_angle() * left_quality +
right_lane.c1_heading_angle() * right_quality) /
quality_divider;
double path_c2 = (left_lane.c2_curvature() * left_quality +
right_lane.c2_curvature() * right_quality) /
quality_divider;
double path_c3 =
(left_lane.c3_curvature_derivative() * left_quality +
right_lane.c3_curvature_derivative() * right_quality) /
quality_divider;
const double current_speed =
VehicleStateProvider::instance()->vehicle_state().linear_velocity();
double path_range = current_speed * FLAGS_ratio_navigation_lane_len_to_speed;
if (path_range <= FLAGS_min_len_for_navigation_lane) {
path_range = FLAGS_min_len_for_navigation_lane;
} else {
path_range = FLAGS_max_len_for_navigation_lane;
}
const double unit_z = 1.0;
const double start_s = -2.0;
double accumulated_s = start_s;
for (double z = start_s; z <= path_range; z += unit_z) {
double x_l = EvaluateCubicPolynomial(path_c0, path_c1, path_c2, path_c3, z);
double x1 = z;
double y1 = x_l;
auto *point = path->add_path_point();
point->set_x(x1);
point->set_y(y1);
if (path->path_point_size() > 1) {
auto &pre_point = path->path_point(path->path_point_size() - 2);
accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());
}
point->set_s(accumulated_s);
}
left_width_ = (std::fabs(left_lane.c0_position()) +
std::fabs(right_lane.c0_position())) /
2.0;
right_width_ = left_width_;
}
bool NavigationLane::CreateMap(const MapGenerationParam &map_config,
MapMsg *map_msg) const {
auto *navigation_info = map_msg->mutable_navigation_path();
auto *hdmap = map_msg->mutable_hdmap();
auto *lane_marker = map_msg->mutable_lane_marker();
lane_marker->CopyFrom(perception_obstacles_.lane_marker());
const auto &path = navigation_path_.path();
if (path.path_point_size() < 2) {
AERROR << "The path length is invalid";
return false;
}
auto *lane = hdmap->add_lane();
lane->mutable_id()->set_id(std::to_string(navigation_path_.path_priority()) +
"_" + path.name());
(*navigation_info)[lane->id().id()] = navigation_path_;
// lane types
lane->set_type(Lane::CITY_DRIVING);
lane->set_turn(Lane::NO_TURN);
// speed limit
lane->set_speed_limit(map_config.default_speed_limit());
// center line
auto *curve_segment = lane->mutable_central_curve()->add_segment();
curve_segment->set_heading(path.path_point(0).theta());
auto *line_segment = curve_segment->mutable_line_segment();
// left boundary
auto *left_boundary = lane->mutable_left_boundary();
auto *left_boundary_type = left_boundary->add_boundary_type();
left_boundary->set_virtual_(false);
left_boundary_type->set_s(0.0);
left_boundary_type->add_types(
perception_obstacles_.lane_marker().left_lane_marker().lane_type());
auto *left_segment =
left_boundary->mutable_curve()->add_segment()->mutable_line_segment();
// right boundary
auto *right_boundary = lane->mutable_right_boundary();
auto *right_boundary_type = right_boundary->add_boundary_type();
right_boundary->set_virtual_(false);
right_boundary_type->set_s(0.0);
right_boundary_type->add_types(
perception_obstacles_.lane_marker().right_lane_marker().lane_type());
auto *right_segment =
right_boundary->mutable_curve()->add_segment()->mutable_line_segment();
const double lane_left_width =
left_width_ > 0 ? left_width_ : map_config.default_left_width();
const double lane_right_width =
right_width_ > 0 ? right_width_ : map_config.default_right_width();
for (const auto &path_point : path.path_point()) {
auto *point = line_segment->add_point();
point->set_x(path_point.x());
point->set_y(path_point.y());
point->set_z(path_point.z());
auto *left_sample = lane->add_left_sample();
left_sample->set_s(path_point.s());
left_sample->set_width(lane_left_width);
left_segment->add_point()->CopyFrom(
*point +
lane_left_width * Vec2d::CreateUnitVec2d(path_point.theta() + M_PI_2));
auto *right_sample = lane->add_right_sample();
right_sample->set_s(path_point.s());
right_sample->set_width(lane_right_width);
right_segment->add_point()->CopyFrom(
*point +
lane_right_width * Vec2d::CreateUnitVec2d(path_point.theta() - M_PI_2));
}
return true;
}
} // namespace relative_map
} // namespace apollo
<commit_msg>navi: fixed the heading issue in navi lane.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* 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 "modules/map/relative_map/navigation_lane.h"
#include <algorithm>
#include <limits>
#include "modules/map/proto/map_lane.pb.h"
#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/util.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/relative_map/common/relative_map_gflags.h"
namespace apollo {
namespace relative_map {
using apollo::common::VehicleStateProvider;
using apollo::common::math::Vec2d;
using apollo::common::util::DistanceXY;
using apollo::hdmap::Lane;
using apollo::common::util::operator+;
using apollo::perception::PerceptionObstacles;
NavigationLane::NavigationLane(const NavigationLaneConfig &config)
: config_(config) {}
void NavigationLane::SetConfig(const NavigationLaneConfig &config) {
config_ = config;
}
bool NavigationLane::GeneratePath() {
// original_pose is in world coordination: ENU
original_pose_ = VehicleStateProvider::instance()->original_pose();
navigation_path_.Clear();
auto *path = navigation_path_.mutable_path();
const auto &lane_marker = perception_obstacles_.lane_marker();
// priority: merge > navigation line > perception lane marker
if (FLAGS_enable_navigation_line &&
navigation_info_.navigation_path_size() > 0) {
ConvertNavigationLineToPath(path);
if (path->path_point().size() <= 0) {
ConvertLaneMarkerToPath(lane_marker, path);
}
} else {
ConvertLaneMarkerToPath(lane_marker, path);
}
return true;
}
double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,
const double c2, const double c3,
const double z) const {
return ((c3 * z + c2) * z + c1) * z + c0;
}
void NavigationLane::MergeNavigationLineAndLaneMarker(
const perception::LaneMarkers &lane_marker, common::Path *path) {
CHECK_NOTNULL(path);
common::Path navigation_path;
ConvertNavigationLineToPath(&navigation_path);
common::Path lane_marker_path;
ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(),
&lane_marker_path);
const double len = std::fmin(
navigation_path.path_point(navigation_path.path_point_size() - 1).s(),
lane_marker_path.path_point(lane_marker_path.path_point_size() - 1).s());
const double ds = 1.0;
int navigation_index = 0;
int lane_marker_index = 0;
for (double s = 0.0; s < len; s += ds) {
auto p1 = GetPathPointByS(navigation_path, navigation_index, s,
&navigation_index);
auto p2 = GetPathPointByS(lane_marker_path, lane_marker_index, s,
&lane_marker_index);
auto *p = path->add_path_point();
const double kWeight = 0.9;
*p = common::util::GetWeightedAverageOfTwoPathPoints(p1, p2, kWeight,
1 - kWeight);
}
}
common::PathPoint NavigationLane::GetPathPointByS(const common::Path &path,
const int start_index,
const double s,
int *matched_index) {
CHECK_NOTNULL(matched_index);
constexpr double kEpsilon = 1e-9;
if (std::fabs(path.path_point(start_index).s() - s) < kEpsilon) {
*matched_index = start_index;
return path.path_point(start_index);
}
int i = start_index;
while (i + 1 < path.path_point_size() && path.path_point(i + 1).s() < s) {
++i;
}
*matched_index = i;
// x, y, z, theta, kappa, s, dkappa, ddkappa
const double r = (s - path.path_point(i).s()) /
(path.path_point(i + 1).s() - path.path_point(i).s());
auto p = common::util::GetWeightedAverageOfTwoPathPoints(
path.path_point(i), path.path_point(i + 1), 1 - r, r);
return p;
}
void NavigationLane::ConvertNavigationLineToPath(common::Path *path) {
CHECK_NOTNULL(path);
if (navigation_info_.navigation_path_size() == 0 ||
!navigation_info_.navigation_path(0).has_path() ||
navigation_info_.navigation_path(0).path().path_point_size() == 0) {
// path is empty
return;
}
path->set_name("Path from navigation.");
UpdateProjectionIndex();
// TODO(All): support multiple navigation path
// currently, only 1 navigation path is supported
const auto &navigation_path = navigation_info_.navigation_path(0).path();
int curr_project_index = last_project_index_;
double dist =
navigation_path.path_point(navigation_path.path_point_size() - 1).s() -
navigation_path.path_point(curr_project_index).s();
if (dist < 20) {
return;
}
// offset between the current vehicle state and navigation line
const double dx = -original_pose_.position().x();
const double dy = -original_pose_.position().y();
const double ref_s = navigation_path.path_point(curr_project_index).s();
for (int i = std::max(0, curr_project_index - 3);
i < navigation_path.path_point_size(); ++i) {
auto *point = path->add_path_point();
point->CopyFrom(navigation_path.path_point(i));
// shift to (0, 0)
double enu_x = point->x() + dx;
double enu_y = point->y() + dy;
double flu_x = 0.0;
double flu_y = 0.0;
common::math::RotateAxis(original_pose_.heading(), enu_x, enu_y, &flu_x,
&flu_y);
point->set_x(flu_x);
point->set_y(flu_y);
point->set_theta(common::math::NormalizeAngle(
common::math::NormalizeAngle(point->theta())
- original_pose_.heading()));
const double accumulated_s = navigation_path.path_point(i).s() - ref_s;
point->set_s(accumulated_s);
if (accumulated_s > FLAGS_max_len_from_navigation_line) {
break;
}
}
const perception::LaneMarkers &lane_marker =
perception_obstacles_.lane_marker();
const auto &left_lane = lane_marker.left_lane_marker();
const auto &right_lane = lane_marker.right_lane_marker();
left_width_ = (std::fabs(left_lane.c0_position()) +
std::fabs(right_lane.c0_position())) /
2.0;
right_width_ = left_width_;
}
// project adc_state_ onto path
void NavigationLane::UpdateProjectionIndex() {
// TODO(All): support multiple navigation path
// currently, only 1 navigation path is supported
const auto &path = navigation_info_.navigation_path(0).path();
int index = 0;
double min_d = std::numeric_limits<double>::max();
for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {
const double d = DistanceXY(original_pose_.position(), path.path_point(i));
if (d < min_d) {
min_d = d;
index = i;
}
const double kMaxDistance = 50.0;
if (last_project_index_ != 0 && d > kMaxDistance) {
break;
}
}
last_project_index_ = index;
}
void NavigationLane::ConvertLaneMarkerToPath(
const perception::LaneMarkers &lane_marker, common::Path *path) {
CHECK_NOTNULL(path);
path->set_name("Path from lane markers.");
const auto &left_lane = lane_marker.left_lane_marker();
const auto &right_lane = lane_marker.right_lane_marker();
double path_c0 = (left_lane.c0_position() + right_lane.c0_position()) / 2.0;
double left_quality = left_lane.quality() + 0.001;
double right_quality = right_lane.quality() + 0.001;
double quality_divider = left_quality + right_quality;
double path_c1 = (left_lane.c1_heading_angle() * left_quality +
right_lane.c1_heading_angle() * right_quality) /
quality_divider;
double path_c2 = (left_lane.c2_curvature() * left_quality +
right_lane.c2_curvature() * right_quality) /
quality_divider;
double path_c3 =
(left_lane.c3_curvature_derivative() * left_quality +
right_lane.c3_curvature_derivative() * right_quality) /
quality_divider;
const double current_speed =
VehicleStateProvider::instance()->vehicle_state().linear_velocity();
double path_range = current_speed * FLAGS_ratio_navigation_lane_len_to_speed;
if (path_range <= FLAGS_min_len_for_navigation_lane) {
path_range = FLAGS_min_len_for_navigation_lane;
} else {
path_range = FLAGS_max_len_for_navigation_lane;
}
const double unit_z = 1.0;
const double start_s = -2.0;
double accumulated_s = start_s;
for (double z = start_s; z <= path_range; z += unit_z) {
double x_l = EvaluateCubicPolynomial(path_c0, path_c1, path_c2, path_c3, z);
double x1 = z;
double y1 = x_l;
auto *point = path->add_path_point();
point->set_x(x1);
point->set_y(y1);
if (path->path_point_size() > 1) {
auto &pre_point = path->path_point(path->path_point_size() - 2);
accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());
}
point->set_s(accumulated_s);
}
left_width_ = (std::fabs(left_lane.c0_position()) +
std::fabs(right_lane.c0_position())) /
2.0;
right_width_ = left_width_;
}
bool NavigationLane::CreateMap(const MapGenerationParam &map_config,
MapMsg *map_msg) const {
auto *navigation_info = map_msg->mutable_navigation_path();
auto *hdmap = map_msg->mutable_hdmap();
auto *lane_marker = map_msg->mutable_lane_marker();
lane_marker->CopyFrom(perception_obstacles_.lane_marker());
const auto &path = navigation_path_.path();
if (path.path_point_size() < 2) {
AERROR << "The path length is invalid";
return false;
}
auto *lane = hdmap->add_lane();
lane->mutable_id()->set_id(std::to_string(navigation_path_.path_priority()) +
"_" + path.name());
(*navigation_info)[lane->id().id()] = navigation_path_;
// lane types
lane->set_type(Lane::CITY_DRIVING);
lane->set_turn(Lane::NO_TURN);
// speed limit
lane->set_speed_limit(map_config.default_speed_limit());
// center line
auto *curve_segment = lane->mutable_central_curve()->add_segment();
curve_segment->set_heading(path.path_point(0).theta());
auto *line_segment = curve_segment->mutable_line_segment();
// left boundary
auto *left_boundary = lane->mutable_left_boundary();
auto *left_boundary_type = left_boundary->add_boundary_type();
left_boundary->set_virtual_(false);
left_boundary_type->set_s(0.0);
left_boundary_type->add_types(
perception_obstacles_.lane_marker().left_lane_marker().lane_type());
auto *left_segment =
left_boundary->mutable_curve()->add_segment()->mutable_line_segment();
// right boundary
auto *right_boundary = lane->mutable_right_boundary();
auto *right_boundary_type = right_boundary->add_boundary_type();
right_boundary->set_virtual_(false);
right_boundary_type->set_s(0.0);
right_boundary_type->add_types(
perception_obstacles_.lane_marker().right_lane_marker().lane_type());
auto *right_segment =
right_boundary->mutable_curve()->add_segment()->mutable_line_segment();
const double lane_left_width =
left_width_ > 0 ? left_width_ : map_config.default_left_width();
const double lane_right_width =
right_width_ > 0 ? right_width_ : map_config.default_right_width();
for (const auto &path_point : path.path_point()) {
auto *point = line_segment->add_point();
point->set_x(path_point.x());
point->set_y(path_point.y());
point->set_z(path_point.z());
auto *left_sample = lane->add_left_sample();
left_sample->set_s(path_point.s());
left_sample->set_width(lane_left_width);
left_segment->add_point()->CopyFrom(
*point +
lane_left_width * Vec2d::CreateUnitVec2d(path_point.theta() + M_PI_2));
auto *right_sample = lane->add_right_sample();
right_sample->set_s(path_point.s());
right_sample->set_width(lane_right_width);
right_segment->add_point()->CopyFrom(
*point +
lane_right_width * Vec2d::CreateUnitVec2d(path_point.theta() - M_PI_2));
}
return true;
}
} // namespace relative_map
} // namespace apollo
<|endoftext|> |
<commit_before>/**
* \file
* \brief SpiPeripheral class header for SPIv2 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*/
#ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
#define SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
#include "distortos/chip/getBusFrequency.hpp"
namespace distortos
{
namespace chip
{
/// SpiPeripheral class is a raw SPI peripheral for SPIv2 in STM32
class SpiPeripheral
{
public:
/**
* \brief SpiPeripheral's constructor
*
* \param [in] spiBase is a base address of SPI peripheral
*/
constexpr explicit SpiPeripheral(const uintptr_t spiBase) :
spiBase_{spiBase},
peripheralFrequency_{getBusFrequency(spiBase)}
{
}
/**
* \return peripheral clock frequency, Hz
*/
uint32_t getPeripheralFrequency() const
{
return peripheralFrequency_;
}
/**
* \return reference to SPI_TypeDef object
*/
SPI_TypeDef& getSpi() const
{
return *reinterpret_cast<SPI_TypeDef*>(spiBase_);
}
/**
* \return current value of CR1 register
*/
uint32_t readCr1() const
{
return getSpi().CR1;
}
/**
* \return current value of CR2 register
*/
uint32_t readCr2() const
{
return getSpi().CR2;
}
/**
* \brief Reads current value of DR register.
*
* \param [in] wordLength selects word length, bits, [4; 16] or
* [ChipSpiMasterLowLevel::minWordLength; ChipSpiMasterLowLevel::maxWordLength]
*
* \return current value of DR register
*/
uint32_t readDr(const uint8_t wordLength) const
{
return wordLength <= 8 ? *reinterpret_cast<volatile uint8_t*>(&getSpi().DR) : getSpi().DR;
}
/**
* \return current value of SR register
*/
uint32_t readSr() const
{
return getSpi().SR;
}
/**
* \brief Writes value to CR1 register.
*
* \param [in] cr1 is the value that will be written to CR1 register
*/
void writeCr1(const uint32_t cr1) const
{
getSpi().CR1 = cr1;
}
/**
* \brief Writes value to CR2 register.
*
* \param [in] cr2 is the value that will be written to CR2 register
*/
void writeCr2(const uint32_t cr2) const
{
getSpi().CR2 = cr2;
}
/**
* \brief Writes value to DR register.
*
* \param [in] wordLength selects word length, bits, [4; 16] or
* [ChipSpiMasterLowLevel::minWordLength; ChipSpiMasterLowLevel::maxWordLength]
* \param [in] dr is the value that will be written to DR register
*/
void writeDr(const uint8_t wordLength, const uint32_t dr) const
{
if (wordLength <= 8)
*reinterpret_cast<volatile uint8_t*>(&getSpi().DR) = dr;
else
getSpi().DR = dr;
}
/**
* \brief Writes value to SR register.
*
* \param [in] sr is the value that will be written to SR register
*/
void writeSr(const uint32_t sr) const
{
getSpi().SR = sr;
}
private:
/// base address of SPI peripheral
uintptr_t spiBase_;
/// peripheral clock frequency, Hz
uint32_t peripheralFrequency_;
};
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
<commit_msg>Make STM32 SPIv2 SpiPeripheral::getSpi() private<commit_after>/**
* \file
* \brief SpiPeripheral class header for SPIv2 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*/
#ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
#define SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
#include "distortos/chip/getBusFrequency.hpp"
namespace distortos
{
namespace chip
{
/// SpiPeripheral class is a raw SPI peripheral for SPIv2 in STM32
class SpiPeripheral
{
public:
/**
* \brief SpiPeripheral's constructor
*
* \param [in] spiBase is a base address of SPI peripheral
*/
constexpr explicit SpiPeripheral(const uintptr_t spiBase) :
spiBase_{spiBase},
peripheralFrequency_{getBusFrequency(spiBase)}
{
}
/**
* \return peripheral clock frequency, Hz
*/
uint32_t getPeripheralFrequency() const
{
return peripheralFrequency_;
}
/**
* \return current value of CR1 register
*/
uint32_t readCr1() const
{
return getSpi().CR1;
}
/**
* \return current value of CR2 register
*/
uint32_t readCr2() const
{
return getSpi().CR2;
}
/**
* \brief Reads current value of DR register.
*
* \param [in] wordLength selects word length, bits, [4; 16] or
* [ChipSpiMasterLowLevel::minWordLength; ChipSpiMasterLowLevel::maxWordLength]
*
* \return current value of DR register
*/
uint32_t readDr(const uint8_t wordLength) const
{
return wordLength <= 8 ? *reinterpret_cast<volatile uint8_t*>(&getSpi().DR) : getSpi().DR;
}
/**
* \return current value of SR register
*/
uint32_t readSr() const
{
return getSpi().SR;
}
/**
* \brief Writes value to CR1 register.
*
* \param [in] cr1 is the value that will be written to CR1 register
*/
void writeCr1(const uint32_t cr1) const
{
getSpi().CR1 = cr1;
}
/**
* \brief Writes value to CR2 register.
*
* \param [in] cr2 is the value that will be written to CR2 register
*/
void writeCr2(const uint32_t cr2) const
{
getSpi().CR2 = cr2;
}
/**
* \brief Writes value to DR register.
*
* \param [in] wordLength selects word length, bits, [4; 16] or
* [ChipSpiMasterLowLevel::minWordLength; ChipSpiMasterLowLevel::maxWordLength]
* \param [in] dr is the value that will be written to DR register
*/
void writeDr(const uint8_t wordLength, const uint32_t dr) const
{
if (wordLength <= 8)
*reinterpret_cast<volatile uint8_t*>(&getSpi().DR) = dr;
else
getSpi().DR = dr;
}
/**
* \brief Writes value to SR register.
*
* \param [in] sr is the value that will be written to SR register
*/
void writeSr(const uint32_t sr) const
{
getSpi().SR = sr;
}
private:
/**
* \return reference to SPI_TypeDef object
*/
SPI_TypeDef& getSpi() const
{
return *reinterpret_cast<SPI_TypeDef*>(spiBase_);
}
/// base address of SPI peripheral
uintptr_t spiBase_;
/// peripheral clock frequency, Hz
uint32_t peripheralFrequency_;
};
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_STM32_SPIV2_SPIPERIPHERAL_HPP_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: enumhelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:45:10 $
*
* 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 _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//==================================================================
//= OEnumerationByName
//==================================================================
//------------------------------------------------------------------------------
OEnumerationByName::OEnumerationByName(const staruno::Reference<starcontainer::XNameAccess>& _rxAccess)
:m_aNames(_rxAccess->getElementNames())
,m_nPos(0)
,m_xAccess(_rxAccess)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByName::OEnumerationByName(const staruno::Reference<starcontainer::XNameAccess>& _rxAccess,
const staruno::Sequence< ::rtl::OUString >& _aNames )
:m_aNames(_aNames)
,m_nPos(0)
,m_xAccess(_rxAccess)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByName::~OEnumerationByName()
{
impl_stopDisposeListening();
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL OEnumerationByName::hasMoreElements( ) throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_xAccess.is() && m_aNames.getLength() > m_nPos)
return sal_True;
if (m_xAccess.is())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
return sal_False;
}
//------------------------------------------------------------------------------
staruno::Any SAL_CALL OEnumerationByName::nextElement( )
throw(starcontainer::NoSuchElementException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
staruno::Any aRes;
if (m_xAccess.is() && m_nPos < m_aNames.getLength())
aRes = m_xAccess->getByName(m_aNames.getConstArray()[m_nPos++]);
if (m_xAccess.is() && m_nPos >= m_aNames.getLength())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
if (!aRes.hasValue()) // es gibt kein Element mehr
throw starcontainer::NoSuchElementException();
return aRes;
}
//------------------------------------------------------------------------------
void SAL_CALL OEnumerationByName::disposing(const starlang::EventObject& aEvent)
throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (aEvent.Source == m_xAccess)
m_xAccess.clear();
}
//------------------------------------------------------------------------------
void OEnumerationByName::impl_startDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->addEventListener(this);
m_bListening = sal_True;
}
--m_refCount;
}
//------------------------------------------------------------------------------
void OEnumerationByName::impl_stopDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (!m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->removeEventListener(this);
m_bListening = sal_False;
}
--m_refCount;
}
//==================================================================
//= OEnumerationByIndex
//==================================================================
//------------------------------------------------------------------------------
OEnumerationByIndex::OEnumerationByIndex(const staruno::Reference< starcontainer::XIndexAccess >& _rxAccess)
:m_xAccess(_rxAccess)
,m_nPos(0)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByIndex::~OEnumerationByIndex()
{
impl_stopDisposeListening();
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL OEnumerationByIndex::hasMoreElements( ) throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_xAccess.is() && m_xAccess->getCount() > m_nPos)
return sal_True;
if (m_xAccess.is())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
return sal_False;
}
//------------------------------------------------------------------------------
staruno::Any SAL_CALL OEnumerationByIndex::nextElement( )
throw(starcontainer::NoSuchElementException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
staruno::Any aRes;
if (m_xAccess.is())
{
aRes = m_xAccess->getByIndex(m_nPos++);
if (m_nPos >= m_xAccess->getCount())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
}
if (!aRes.hasValue()) // es gibt kein Element mehr
throw starcontainer::NoSuchElementException();
return aRes;
}
//------------------------------------------------------------------------------
void SAL_CALL OEnumerationByIndex::disposing(const starlang::EventObject& aEvent)
throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (aEvent.Source == m_xAccess)
m_xAccess.clear();
}
//------------------------------------------------------------------------------
void OEnumerationByIndex::impl_startDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->addEventListener(this);
m_bListening = sal_True;
}
--m_refCount;
}
//------------------------------------------------------------------------------
void OEnumerationByIndex::impl_stopDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (!m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->removeEventListener(this);
m_bListening = sal_False;
}
--m_refCount;
}
//.........................................................................
} // namespace comphelper
//.........................................................................
<commit_msg>INTEGRATION: CWS warnings01 (1.4.184); FILE MERGED 2005/09/23 03:13:48 sb 1.4.184.2: RESYNC: (1.4-1.5); FILE MERGED 2005/09/01 13:59:56 sb 1.4.184.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: enumhelper.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:46:20 $
*
* 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 _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//==================================================================
//= OEnumerationByName
//==================================================================
//------------------------------------------------------------------------------
OEnumerationByName::OEnumerationByName(const staruno::Reference<starcontainer::XNameAccess>& _rxAccess)
:m_aNames(_rxAccess->getElementNames())
,m_nPos(0)
,m_xAccess(_rxAccess)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByName::OEnumerationByName(const staruno::Reference<starcontainer::XNameAccess>& _rxAccess,
const staruno::Sequence< ::rtl::OUString >& _aNames )
:m_aNames(_aNames)
,m_nPos(0)
,m_xAccess(_rxAccess)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByName::~OEnumerationByName()
{
impl_stopDisposeListening();
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL OEnumerationByName::hasMoreElements( ) throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_xAccess.is() && m_aNames.getLength() > m_nPos)
return sal_True;
if (m_xAccess.is())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
return sal_False;
}
//------------------------------------------------------------------------------
staruno::Any SAL_CALL OEnumerationByName::nextElement( )
throw(starcontainer::NoSuchElementException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
staruno::Any aRes;
if (m_xAccess.is() && m_nPos < m_aNames.getLength())
aRes = m_xAccess->getByName(m_aNames.getConstArray()[m_nPos++]);
if (m_xAccess.is() && m_nPos >= m_aNames.getLength())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
if (!aRes.hasValue()) // es gibt kein Element mehr
throw starcontainer::NoSuchElementException();
return aRes;
}
//------------------------------------------------------------------------------
void SAL_CALL OEnumerationByName::disposing(const starlang::EventObject& aEvent)
throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (aEvent.Source == m_xAccess)
m_xAccess.clear();
}
//------------------------------------------------------------------------------
void OEnumerationByName::impl_startDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->addEventListener(this);
m_bListening = sal_True;
}
--m_refCount;
}
//------------------------------------------------------------------------------
void OEnumerationByName::impl_stopDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (!m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->removeEventListener(this);
m_bListening = sal_False;
}
--m_refCount;
}
//==================================================================
//= OEnumerationByIndex
//==================================================================
//------------------------------------------------------------------------------
OEnumerationByIndex::OEnumerationByIndex(const staruno::Reference< starcontainer::XIndexAccess >& _rxAccess)
:m_nPos(0)
,m_xAccess(_rxAccess)
,m_bListening(sal_False)
{
impl_startDisposeListening();
}
//------------------------------------------------------------------------------
OEnumerationByIndex::~OEnumerationByIndex()
{
impl_stopDisposeListening();
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL OEnumerationByIndex::hasMoreElements( ) throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_xAccess.is() && m_xAccess->getCount() > m_nPos)
return sal_True;
if (m_xAccess.is())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
return sal_False;
}
//------------------------------------------------------------------------------
staruno::Any SAL_CALL OEnumerationByIndex::nextElement( )
throw(starcontainer::NoSuchElementException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
staruno::Any aRes;
if (m_xAccess.is())
{
aRes = m_xAccess->getByIndex(m_nPos++);
if (m_nPos >= m_xAccess->getCount())
{
impl_stopDisposeListening();
m_xAccess.clear();
}
}
if (!aRes.hasValue()) // es gibt kein Element mehr
throw starcontainer::NoSuchElementException();
return aRes;
}
//------------------------------------------------------------------------------
void SAL_CALL OEnumerationByIndex::disposing(const starlang::EventObject& aEvent)
throw(staruno::RuntimeException)
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (aEvent.Source == m_xAccess)
m_xAccess.clear();
}
//------------------------------------------------------------------------------
void OEnumerationByIndex::impl_startDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->addEventListener(this);
m_bListening = sal_True;
}
--m_refCount;
}
//------------------------------------------------------------------------------
void OEnumerationByIndex::impl_stopDisposeListening()
{
::osl::ResettableMutexGuard aLock(m_aLock);
if (!m_bListening)
return;
++m_refCount;
staruno::Reference< starlang::XComponent > xDisposable(m_xAccess, staruno::UNO_QUERY);
if (xDisposable.is())
{
xDisposable->removeEventListener(this);
m_bListening = sal_False;
}
--m_refCount;
}
//.........................................................................
} // namespace comphelper
//.........................................................................
<|endoftext|> |
<commit_before>#include <iostream>
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include <sodium.h>
int main(int argc, char **argv)
{
if (sodium_init() == -1) {
std::cerr << "Failed to initialize libsodium" << std::endl;
return 1;
}
Catch::Session session;
int ret = session.applyCommandLine(argc, argv);
if (ret)
return ret;
session.run();
return 0;
}
<commit_msg>fix unit test program return<commit_after>#include <iostream>
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include <sodium.h>
int main(int argc, char **argv)
{
if (sodium_init() == -1) {
std::cerr << "Failed to initialize libsodium" << std::endl;
return 1;
}
Catch::Session session;
int ret = session.applyCommandLine(argc, argv);
if (ret)
return ret;
ret = session.run();
return ret;
}
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2013-2017 EOS di Manlio Morini.
*
* \license
* 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/
*/
#if !defined(VITA_EVOLUTION_STRATEGY_H)
# error "Don't include this file directly, include the specific .h instead"
#endif
#if !defined(VITA_EVOLUTION_STRATEGY_TCC)
#define VITA_EVOLUTION_STRATEGY_TCC
///
/// \param[out] env environment
/// \return a strategy-specific environment
///
/// \remark For standard evolution we only need one layer.
///
template<class T>
environment std_es<T>::shape(environment env)
{
env.layers = 1;
return env;
}
///
/// \return `true` when evolution must be stopped
///
/// We use an accelerated stop condition when:
/// - all the individuals have the same fitness;
/// - after `env_.g_without_improvement` generations the situation doesn't
/// change.
///
template<class T>
bool std_es<T>::stop_condition() const
{
const auto &env(this->pop_.env());
if (env.g_without_improvement &&
this->sum_->gen - this->sum_->last_imp > env.g_without_improvement &&
issmall(this->sum_->az.fit_dist().variance()))
return true;
return false;
}
///
/// \param[out] env environemnt
/// \return a strategy-specific environment
///
/// \remark ALPS requires more than one layer.
///
template<class T, template<class> class CS>
environment basic_alps_es<T, CS>::shape(environment env)
{
env.layers = 4;
return env;
}
///
/// Increments population's age and checks if it's time to add a new layer.
///
template<class T, template<class> class CS>
void basic_alps_es<T, CS>::post_bookkeeping()
{
const auto &sum(this->sum_);
auto &pop(this->pop_);
pop.inc_age();
const auto layers(pop.layers());
for (auto l(decltype(layers){1}); l < layers; ++l)
{
const auto allowed(pop.env().individuals);
const auto current(pop.individuals(l));
if (issmall(sum->az.fit_dist(l).standard_deviation()))
{
if (current > allowed / 5)
pop.set_allowed(l, current / 2);
}
else
pop.set_allowed(l, allowed);
}
// Code executed every `age_gap` interval.
if (sum->gen && sum->gen % pop.env().alps.age_gap == 0)
{
if (layers < pop.env().layers ||
sum->az.age_dist(layers - 1).mean() >
alps::max_age(layers, pop.env().alps.age_gap))
pop.add_layer();
else
{
this->replacement.try_move_up_layer(0);
pop.init_layer(0);
}
}
}
///
/// Saves working / statistical informations about layer status.
///
/// \param[in] last_run last run processed
/// \param[in] current_run current run
///
/// Parameters from the environment:
/// * env.stat.layers if `false` the method will not write any data.
///
template<class T, template<class> class CS>
void basic_alps_es<T, CS>::log(unsigned last_run, unsigned current_run) const
{
const auto &pop(this->pop_);
const auto &env(pop.env());
if (env.stat.layers)
{
const std::string n_lys(env.stat.dir + "/" + env.stat.lys_name);
std::ofstream f_lys(n_lys, std::ios_base::app);
if (!f_lys.good())
return;
if (last_run != current_run)
f_lys << "\n\n";
auto layers(pop.layers());
for (decltype(layers) l(0); l < layers; ++l)
{
f_lys << current_run << ' ' << this->sum_->gen << ' ' << l << " <";
const auto ma(alps::allowed_age(pop, l));
if (ma == std::numeric_limits<decltype(ma)>::max())
f_lys << "inf";
else
f_lys << ma + 1;
f_lys << ' ' << this->sum_->az.age_dist(l).mean()
<< ' ' << this->sum_->az.age_dist(l).standard_deviation()
<< ' ' << static_cast<unsigned>(this->sum_->az.age_dist(l).min())
<< '-' << static_cast<unsigned>(this->sum_->az.age_dist(l).max())
<< ' ' << this->sum_->az.fit_dist(l).mean()
<< ' ' << this->sum_->az.fit_dist(l).standard_deviation()
<< ' ' << this->sum_->az.fit_dist(l).min()
<< '-' << this->sum_->az.fit_dist(l).max()
<< ' ' << pop.individuals(l) << '\n';
}
}
}
#endif // include guard
<commit_msg>[REF] ALPS can remove multiple indentical layers<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2013-2017 EOS di Manlio Morini.
*
* \license
* 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/
*/
#if !defined(VITA_EVOLUTION_STRATEGY_H)
# error "Don't include this file directly, include the specific .h instead"
#endif
#if !defined(VITA_EVOLUTION_STRATEGY_TCC)
#define VITA_EVOLUTION_STRATEGY_TCC
///
/// \param[out] env environment
/// \return a strategy-specific environment
///
/// \remark For standard evolution we only need one layer.
///
template<class T>
environment std_es<T>::shape(environment env)
{
env.layers = 1;
return env;
}
///
/// \return `true` when evolution must be stopped
///
/// We use an accelerated stop condition when:
/// - all the individuals have the same fitness;
/// - after `env_.g_without_improvement` generations the situation doesn't
/// change.
///
template<class T>
bool std_es<T>::stop_condition() const
{
const auto &env(this->pop_.env());
if (env.g_without_improvement &&
this->sum_->gen - this->sum_->last_imp > env.g_without_improvement &&
issmall(this->sum_->az.fit_dist().variance()))
return true;
return false;
}
///
/// \param[out] env environemnt
/// \return a strategy-specific environment
///
/// \remark ALPS requires more than one layer.
///
template<class T, template<class> class CS>
environment basic_alps_es<T, CS>::shape(environment env)
{
env.layers = 4;
return env;
}
///
/// Increments population's age and checks if it's time to add a new layer.
///
template<class T, template<class> class CS>
void basic_alps_es<T, CS>::post_bookkeeping()
{
const auto &sum(this->sum_);
auto &pop(this->pop_);
pop.inc_age();
for (auto l(pop.layers() - 1); l; --l)
if (almost_equal(sum->az.fit_dist(l - 1).mean(),
sum->az.fit_dist( l).mean()))
pop.remove_layer(l);
auto layers(pop.layers());
for (decltype(layers) l(1); l < layers; ++l)
if (issmall(sum->az.fit_dist(l).standard_deviation()))
{
const auto current(pop.individuals(l));
pop.set_allowed(l, std::max(pop.env().min_individuals, current / 2));
}
else
{
const auto allowed(pop.env().individuals);
pop.set_allowed(l, allowed);
}
// Code executed every `age_gap` interval.
if (sum->gen && sum->gen % pop.env().alps.age_gap == 0)
{
if (layers < pop.env().layers ||
sum->az.age_dist(layers - 1).mean() >
alps::max_age(layers, pop.env().alps.age_gap))
pop.add_layer();
else
{
this->replacement.try_move_up_layer(0);
pop.init_layer(0);
}
}
}
///
/// Saves working / statistical informations about layer status.
///
/// \param[in] last_run last run processed
/// \param[in] current_run current run
///
/// Parameters from the environment:
/// * env.stat.layers if `false` the method will not write any data.
///
template<class T, template<class> class CS>
void basic_alps_es<T, CS>::log(unsigned last_run, unsigned current_run) const
{
const auto &pop(this->pop_);
const auto &env(pop.env());
if (env.stat.layers)
{
const std::string n_lys(env.stat.dir + "/" + env.stat.lys_name);
std::ofstream f_lys(n_lys, std::ios_base::app);
if (!f_lys.good())
return;
if (last_run != current_run)
f_lys << "\n\n";
auto layers(pop.layers());
for (decltype(layers) l(0); l < layers; ++l)
{
f_lys << current_run << ' ' << this->sum_->gen << ' ' << l << " <";
const auto ma(alps::allowed_age(pop, l));
if (ma == std::numeric_limits<decltype(ma)>::max())
f_lys << "inf";
else
f_lys << ma + 1;
f_lys << ' ' << this->sum_->az.age_dist(l).mean()
<< ' ' << this->sum_->az.age_dist(l).standard_deviation()
<< ' ' << static_cast<unsigned>(this->sum_->az.age_dist(l).min())
<< '-' << static_cast<unsigned>(this->sum_->az.age_dist(l).max())
<< ' ' << this->sum_->az.fit_dist(l).mean()
<< ' ' << this->sum_->az.fit_dist(l).standard_deviation()
<< ' ' << this->sum_->az.fit_dist(l).min()
<< '-' << this->sum_->az.fit_dist(l).max()
<< ' ' << pop.individuals(l) << '\n';
}
}
}
#endif // include guard
<|endoftext|> |
<commit_before>/*
TGD2151 Computer Graphics Fundamentals
Faculty of Computing & Informatics, Multimedia University
CGLab01.hpp
Objective: Header File for Lab01 Demo Models / World
(C) 2006-2015 Ya Ping Wong, All Rights Reserved.
http://wongyaping.com
Stanford Dragon:
Original Model : Copyright by Stanford University
http://graphics.stanford.edu/data/3Dscanrep/
Low-polygons Model : Simplified by Mr. Ng Kok Why
<[email protected]>
INSTRUCTIONS
============
Please refer to CGLabmain.cpp for instructions
SPECIAL NOTES
=============
* Try loading the high-polygons version of
the Dragon model, it will be slow in slower PC.
* Try out other models from http://graphics.stanford.edu/data/3Dscanrep/
However, you will need to modify the file to comform to the
format that is being used in this program.
CHANGE LOG
==========
*/
#ifndef YP_CGLAB01_HPP
#define YP_CGLAB01_HPP
#include "CGLabmain.hpp"
#include "utilities/Mesh.hpp"
#include "utilities/Extrusion.hpp"
#include "utilities/Loft.hpp"
#include <string>
#include <vector>
namespace CGLab01 {
class SimplePolygon
{
public:
void draw();
};
class SimpleTriangles
{
public:
void draw();
};
class SimpleBox
{
public:
void draw();
};
class SimpleTeapot
{
public:
void draw();
};
class SimpleBouncingBall
{
public:
SimpleBouncingBall();
void draw();
void tickTime(long int elapseTime);
private:
long int timetick;
float vel0;
float accel;
};
class MyModelLoader
{
public:
MyModelLoader()
{
}
~MyModelLoader()
{
}
//load a model and scale it
void load(string filename, float scale = 1.0);
void draw();
private:
vector<GLfloat> vertices;
vector<int> faces;
GLuint stanforddragon; //for generating display list
};
//------------------------------------
//the main program will call methods from this class
class MyVirtualWorld
{
public:
SimplePolygon simplepolygon;
SimpleBox simplebox;
SimpleTriangles simpletriangles;
SimpleTeapot simpleteapot;
SimpleBouncingBall simplebouncingball;
MyModelLoader mymodelloader;
Mesh *deer;
Mesh *elephant;
vector<vec2> points;
Extrusion *extrude;
Loft *loft;
vector<vec3> pts, ptsTransformed,points3d;
long int timeold, timenew, elapseTime;
void draw();
~MyVirtualWorld() {
delete deer;
delete elephant;
delete extrude;
}
void tickTime()
{
timenew = glutGet(GLUT_ELAPSED_TIME);
elapseTime = timenew - timeold;
timeold = timenew;
simplebouncingball.tickTime(elapseTime);
}
//for any one-time only initialization of the
// virtual world before any rendering takes place
// BUT after OpenGL has been initialized
void init()
{
glEnable(GL_LIGHTING);
points = {
{{ -4.0f, -5.0f }}, {{ -4.0f, 5.0f }},
{{ 0.0f, 7.0f }}, {{ 4.0f, 5.0f }},
{{ 4.0f, -5.0f }}, {{ 0.0f, -7.0f }}
};
points3d = {
{{ -4.0f, -5.0f,5.0f }},
{{ 4.0f, 5.0f,5.0f }},
{{ 8.0f, 7.0f,5.0f }},
{{ 12.0f, 5.0f,5.0f }},
{{ 16.0f, -5.0f,5.0f }},
{{ 20.0f, -7.0f,5.0f }}
};
extrude = new Extrusion(points);
extrude->setDepth(8);
loft = new Loft(points, points3d);
//Low-polygons dragon (5835 triangles)
mymodelloader.load("data/model_lowpolygonstanforddragon.txt",100);
deer = new Mesh("data/deer.obj");
deer->setFlatColor({{.8, .2, .8}});
deer->setTranslateX(10.5f);
deer->setScale(0.5f);
elephant = new Mesh("data/elephant-triangulated.obj");
elephant->setFlatColor({{ .8, .1, .15 }});
elephant->setTranslateX(-10.5f);
elephant->setRotateY(-45.0f);
pts = getCircle(8, 7);
vec3 startNormal = {{ 0, 1, 0 }};
vec3 targetNormal = {{ 0.3333, 0.3333, 0.3333 }};
mat3 rotationMatrix = getRotationMatrix(startNormal, targetNormal);
for (auto &p : pts) {
ptsTransformed.push_back(mult(rotationMatrix, p));
}
//Try this:
//High-polygons dragon (original model of Stanford Dragon)
// (871414 triangles) will take some minutes for it to get loaded
//mymodelloader.load("data/model_highpolygonstanforddragon.txt",100);
//mymodelloader.load("data/model_rose.txt", 0.2);
//mymodelloader.load("data/model_shuttle.txt", 0.1);
timeold = glutGet(GLUT_ELAPSED_TIME);
}
};
}; //end of namespace CGLab01
#endif //YP_CGLAB01_HPP
<commit_msg>spring, heart<commit_after>/*
TGD2151 Computer Graphics Fundamentals
Faculty of Computing & Informatics, Multimedia University
CGLab01.hpp
Objective: Header File for Lab01 Demo Models / World
(C) 2006-2015 Ya Ping Wong, All Rights Reserved.
http://wongyaping.com
Stanford Dragon:
Original Model : Copyright by Stanford University
http://graphics.stanford.edu/data/3Dscanrep/
Low-polygons Model : Simplified by Mr. Ng Kok Why
<[email protected]>
INSTRUCTIONS
============
Please refer to CGLabmain.cpp for instructions
SPECIAL NOTES
=============
* Try loading the high-polygons version of
the Dragon model, it will be slow in slower PC.
* Try out other models from http://graphics.stanford.edu/data/3Dscanrep/
However, you will need to modify the file to comform to the
format that is being used in this program.
CHANGE LOG
==========
*/
#ifndef YP_CGLAB01_HPP
#define YP_CGLAB01_HPP
#include "CGLabmain.hpp"
#include "utilities/Mesh.hpp"
#include "utilities/Extrusion.hpp"
#include "utilities/Loft.hpp"
#include <string>
#include <vector>
namespace CGLab01 {
class SimplePolygon
{
public:
void draw();
};
class SimpleTriangles
{
public:
void draw();
};
class SimpleBox
{
public:
void draw();
};
class SimpleTeapot
{
public:
void draw();
};
class SimpleBouncingBall
{
public:
SimpleBouncingBall();
void draw();
void tickTime(long int elapseTime);
private:
long int timetick;
float vel0;
float accel;
};
class MyModelLoader
{
public:
MyModelLoader()
{
}
~MyModelLoader()
{
}
//load a model and scale it
void load(string filename, float scale = 1.0);
void draw();
private:
vector<GLfloat> vertices;
vector<int> faces;
GLuint stanforddragon; //for generating display list
};
//------------------------------------
//the main program will call methods from this class
class MyVirtualWorld
{
public:
SimplePolygon simplepolygon;
SimpleBox simplebox;
SimpleTriangles simpletriangles;
SimpleTeapot simpleteapot;
SimpleBouncingBall simplebouncingball;
MyModelLoader mymodelloader;
Mesh *deer;
Mesh *elephant;
vector<vec2> points;
Extrusion *extrude;
Loft *loft;
vector<vec3> pts, ptsTransformed,points3d;
long int timeold, timenew, elapseTime;
void draw();
~MyVirtualWorld() {
delete deer;
delete elephant;
delete extrude;
}
void tickTime()
{
timenew = glutGet(GLUT_ELAPSED_TIME);
elapseTime = timenew - timeold;
timeold = timenew;
simplebouncingball.tickTime(elapseTime);
}
//for any one-time only initialization of the
// virtual world before any rendering takes place
// BUT after OpenGL has been initialized
void init()
{
glEnable(GL_LIGHTING);
/*
points = {
{{ -4.0f, -5.0f }}, {{ -4.0f, 5.0f }},
{{ 0.0f, 7.0f }}, {{ 4.0f, 5.0f }},
{{ 4.0f, -5.0f }}, {{ 0.0f, -7.0f }}
};
*/
points3d = {
{{ -4.0f, -5.0f,5.0f }},
{{ 4.0f, 5.0f,5.0f }},
{{ 8.0f, 7.0f,5.0f }},
{{ 12.0f, 5.0f,5.0f }},
{{ 16.0f, -5.0f,5.0f }},
{{ 20.0f, -7.0f,5.0f }}
};
auto circle = getCircle(2, 10);
for (auto &v : circle) points.push_back({{ v[0], v[2] }});
//spring:
points3d = generateSpline(-50, 50, 150,
[](float z)->float { return sin(z/2.0) * 15; },
[](float x)->float { return cos(x/2.0) * 15; },
[](float y)->float { return y; });
// heart:
/*
points3d = generateSpline(-50, 50, 150,
[](float z)->float {
float t = z/5.0;
return 16 * sin(t) * sin(t) * sin(t);
},
[](float x)->float {
float t = x/5.0;
return 13 * cos(t) - 5*cos(2*t) - 2*cos(3*t) - cos(4*t);
});
*/
extrude = new Extrusion(points);
extrude->setDepth(8);
loft = new Loft(points, points3d);
//Low-polygons dragon (5835 triangles)
mymodelloader.load("data/model_lowpolygonstanforddragon.txt",100);
deer = new Mesh("data/deer.obj");
deer->setFlatColor({{.8, .2, .8}});
deer->setTranslateX(10.5f);
deer->setScale(0.5f);
elephant = new Mesh("data/elephant-triangulated.obj");
elephant->setFlatColor({{ .8, .1, .15 }});
elephant->setTranslateX(-10.5f);
elephant->setRotateY(-45.0f);
pts = getCircle(8, 7);
vec3 startNormal = {{ 0, 1, 0 }};
vec3 targetNormal = {{ 0.3333, 0.3333, 0.3333 }};
mat3 rotationMatrix = getRotationMatrix(startNormal, targetNormal);
for (auto &p : pts) {
ptsTransformed.push_back(mult(rotationMatrix, p));
}
//Try this:
//High-polygons dragon (original model of Stanford Dragon)
// (871414 triangles) will take some minutes for it to get loaded
//mymodelloader.load("data/model_highpolygonstanforddragon.txt",100);
//mymodelloader.load("data/model_rose.txt", 0.2);
//mymodelloader.load("data/model_shuttle.txt", 0.1);
timeold = glutGet(GLUT_ELAPSED_TIME);
}
};
}; //end of namespace CGLab01
#endif //YP_CGLAB01_HPP
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.